From c3013f2fb64ebcbdcace4bc827cd8d85c0a819dc Mon Sep 17 00:00:00 2001 From: KingLauri200 Date: Wed, 20 Mar 2024 13:50:30 +0100 Subject: [PATCH 1/4] git init --- server/app/exportfeatures.js | 938 +++++------ server/concatenator.js | 167 +- server/content/comments.js | 52 +- server/content/content.js | 212 +-- server/content/project.js | 217 +-- server/forum/forum.js | 88 +- server/forum/forumapp.js | 311 ++-- server/forum/post.js | 93 +- server/forum/reply.js | 40 +- server/gamify/achievements.js | 30 +- server/ratelimiter.js | 77 +- server/relay/relay.js | 148 +- server/relay/relayservice.js | 60 +- server/relay/relaysession.js | 57 +- server/relay/serverinstance.js | 120 +- server/server.js | 318 ++-- server/session/projectmanager.js | 696 ++++---- server/session/session.js | 1323 ++++++++------- server/webapp.coffee | 2 +- server/webapp.js | 1278 ++++++++------- static/js/about/about.js | 70 +- static/js/app.js | 540 +++--- static/js/appstate.js | 103 +- static/js/appui/appui.js | 1457 +++++++++-------- static/js/appui/floatingwindow.js | 134 +- static/js/assets/assetsmanager.js | 355 ++-- static/js/assets/modelviewer.js | 215 +-- static/js/assets/textviewer.js | 141 +- static/js/doc/documentation.js | 311 ++-- static/js/editor/editor.js | 695 ++++---- static/js/editor/runwindow.js | 749 +++++---- static/js/explore/explore.js | 702 ++++---- static/js/explore/projectdetails.js | 648 ++++---- static/js/folderview.js | 439 ++--- static/js/languages/javascript/runner.js | 41 +- .../js/languages/microscript/v2/compiler.js | 1441 ++++++++-------- static/js/languages/microscript/v2/parser.js | 1381 ++++++++-------- .../languages/microscript/v2/processor.coffee | 4 +- .../js/languages/microscript/v2/processor.js | 331 ++-- static/js/languages/microscript/v2/program.js | 252 +-- static/js/languages/microscript/v2/routine.js | 332 ++-- static/js/languages/microscript/v2/runner.js | 148 +- static/js/languages/microscript/v2/token.js | 14 +- static/js/languages/python/runner.js | 97 +- static/js/mapeditor/mapeditor.js | 487 +++--- static/js/music/musiceditor.js | 145 +- static/js/options/options.js | 411 +++-- static/js/options/tabmanager.js | 579 +++---- static/js/play/playerclient.js | 248 +-- static/js/play/server.js | 131 +- static/js/play/server_export/mpserver.js | 185 ++- static/js/play/server_export/server.js | 89 +- static/js/play/serverclient.js | 248 +-- static/js/project/project.js | 566 ++++--- static/js/project/projectfolder.js | 91 +- static/js/publish/publish.js | 208 ++- static/js/runtime/assetmanager.js | 195 ++- static/js/runtime/audio/sound.js | 160 +- static/js/runtime/m2d/m2d.js | 68 +- static/js/runtime/microvm.js | 184 ++- static/js/runtime/mpserver.js | 236 +-- static/js/runtime/mpserverconnection.js | 188 ++- static/js/runtime/msimage.js | 1335 +++++++-------- static/js/runtime/pixi/screen.js | 155 +- static/js/runtime/runtime.js | 483 +++--- static/js/runtime/runtime_server.js | 190 ++- static/js/runtime/screen.js | 396 ++--- static/js/runtime/sprite.js | 80 +- static/js/runtime/timemachine.js | 96 +- static/js/runtime/watcher.js | 41 +- static/js/sound/soundeditor.js | 151 +- static/js/spriteeditor/colorpicker.js | 91 +- static/js/spriteeditor/drawtool.js | 405 +++-- static/js/spriteeditor/spriteeditor.js | 934 ++++++----- static/js/spriteeditor/spriteframe.js | 54 +- static/js/spriteeditor/spriteview.js | 306 ++-- static/js/terminal/terminal.js | 254 +-- static/js/tutorial/highlighter.js | 94 +- static/js/tutorial/tutorials.js | 108 +- static/js/tutorial/tutorialspage.js | 389 +++-- static/js/tutorial/tutorialwindow.js | 220 +-- static/js/user/usersettings.js | 572 ++++--- static/js/util/confirm.js | 36 +- static/js/util/diff.js | 3 +- static/js/util/splitbar.js | 120 +- 85 files changed, 14804 insertions(+), 12955 deletions(-) diff --git a/server/app/exportfeatures.js b/server/app/exportfeatures.js index 2b65a618..6e99b394 100644 --- a/server/app/exportfeatures.js +++ b/server/app/exportfeatures.js @@ -10,69 +10,69 @@ pug = require("pug"); JobQueue = require(__dirname + "/jobqueue.js"); -this.ExportFeatures = class ExportFeatures { - constructor(webapp) { +this.ExportFeatures = (function() { + function ExportFeatures(webapp) { this.webapp = webapp; this.addSpritesExport(); this.addPublishHTML(); this.addProjectFilesExport(); } - addProjectFilesExport() { - // /user/project[/code]/export/project/ - return this.webapp.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+\/([^\/\|\?\&\.]+\/)?export\/project\/$/, (req, res) => { - var HH, MM, SS, access, date, dd, f, folders, j, last_modified, len, manager, mm, project, projectInfo, queue, user, yyyy, zip; - access = this.webapp.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - manager = this.webapp.getProjectManager(project); - folders = this.getFoldersWithTypes(); - projectInfo = this.prepareExportProjectInfo(project); - date = new Date(); - if (project.last_modified) { - date.setTime(project.last_modified); - } - yyyy = (date.getFullYear()).toString().padStart(4, '0000'); - mm = (date.getMonth() + 1).toString().padStart(2, '0'); - dd = (date.getDate()).toString().padStart(2, '0'); - HH = (date.getHours()).toString().padStart(2, '0'); - MM = (date.getMinutes()).toString().padStart(2, '0'); - SS = (date.getSeconds()).toString().padStart(2, '0'); - last_modified = `${yyyy}${mm}${dd}-${HH}${MM}${SS}`; - zip = new JSZip; - queue = new JobQueue(() => { - return zip.generateAsync({ - type: "nodebuffer" - }).then((content) => { - res.setHeader("Content-Type", "application/zip"); - res.setHeader("Content-Disposition", `attachement; filename="${project.slug}_${last_modified}_archive.zip"`); - return res.send(content); + ExportFeatures.prototype.addProjectFilesExport = function() { + return this.webapp.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+\/([^\/\|\?\&\.]+\/)?export\/project\/$/, (function(_this) { + return function(req, res) { + var HH, MM, SS, access, date, dd, f, fn, folders, j, last_modified, len, manager, mm, project, projectInfo, queue, user, yyyy, zip; + access = _this.webapp.getProjectAccess(req, res); + if (access == null) { + return; + } + user = access.user; + project = access.project; + manager = _this.webapp.getProjectManager(project); + folders = _this.getFoldersWithTypes(); + projectInfo = _this.prepareExportProjectInfo(project); + date = new Date(); + if (project.last_modified) { + date.setTime(project.last_modified); + } + yyyy = (date.getFullYear()).toString().padStart(4, '0000'); + mm = (date.getMonth() + 1).toString().padStart(2, '0'); + dd = (date.getDate()).toString().padStart(2, '0'); + HH = (date.getHours()).toString().padStart(2, '0'); + MM = (date.getMinutes()).toString().padStart(2, '0'); + SS = (date.getSeconds()).toString().padStart(2, '0'); + last_modified = "" + yyyy + mm + dd + "-" + HH + MM + SS; + zip = new JSZip; + queue = new JobQueue(function() { + return zip.generateAsync({ + type: "nodebuffer" + }).then(function(content) { + res.setHeader("Content-Type", "application/zip"); + res.setHeader("Content-Disposition", "attachement; filename=\"" + project.slug + "_" + last_modified + "_archive.zip\""); + return res.send(content); + }); }); - }); - zip.file("project.json", JSON.stringify(projectInfo)); - for (j = 0, len = folders.length; j < len; j++) { - f = folders[j]; - ((f) => { - return this.enqueueFolderZipping(zip, queue, manager, user, project, f.name, f.fileType); - })(f); - } - return queue.start(); - }); - } + zip.file("project.json", JSON.stringify(projectInfo)); + fn = function(f) { + return _this.enqueueFolderZipping(zip, queue, manager, user, project, f.name, f.fileType); + }; + for (j = 0, len = folders.length; j < len; j++) { + f = folders[j]; + fn(f); + } + return queue.start(); + }; + })(this)); + }; - enqueueFolderZipping(zip, queue, manager, user, project, folder, fileType) { - return queue.add(() => { - return manager.listFiles(folder, (files) => { - var f, j, len; - for (j = 0, len = files.length; j < len; j++) { - f = files[j]; - ((f) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify f - return this.webapp.server.content.files.read(`${user.id}/${project.id}/${folder}/${f.file}`, fileType, (content) => { + ExportFeatures.prototype.enqueueFolderZipping = function(zip, queue, manager, user, project, folder, fileType) { + return queue.add((function(_this) { + return function() { + return manager.listFiles(folder, function(files) { + var f, fn, j, len; + fn = function(f) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/" + folder + "/" + f.file, fileType, function(content) { var name; if (content != null) { name = f.file.replace(/-/g, "/"); @@ -90,64 +90,58 @@ this.ExportFeatures = class ExportFeatures { } zip.folder(folder).file(name, content); } - //zip.folder(folder).file("#{f.file}.meta", JSON.stringify f) return queue.next(); }); }); - })(f); - } - return queue.next(); - }); - }); - } + }; + for (j = 0, len = files.length; j < len; j++) { + f = files[j]; + fn(f); + } + return queue.next(); + }); + }; + })(this)); + }; - getFoldersWithTypes() { + ExportFeatures.prototype.getFoldersWithTypes = function() { var folders; return folders = [ { name: "sprites", fileType: "binary" - }, - { + }, { name: "ms", fileType: "text" - }, - { + }, { name: "doc", fileType: "text" - }, - { + }, { name: "maps", fileType: "text" - }, - { + }, { name: "sounds", fileType: "binary" - }, - { + }, { name: "sounds_th", fileType: "binary" - }, - { + }, { name: "music", fileType: "binary" - }, - { + }, { name: "music_th", fileType: "binary" - }, - { + }, { name: "assets", fileType: "binary" - }, - { + }, { name: "assets_th", fileType: "binary" } ]; - } + }; - prepareExportProjectInfo(project) { + ExportFeatures.prototype.prepareExportProjectInfo = function(project) { return { owner: project.owner.nick, title: project.title, @@ -171,194 +165,191 @@ this.ExportFeatures = class ExportFeatures { files: project.files, description: project.description }; - } + }; - addSpritesExport() { - // /user/project[/code]/export/sprites/ - return this.webapp.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+\/([^\/\|\?\&\.]+\/)?export\/sprites\/$/, (req, res) => { - var access, manager, project, queue, user, zip; - access = this.webapp.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - manager = this.webapp.getProjectManager(project); - zip = new JSZip; - queue = new JobQueue(() => { - return zip.generateAsync({ - type: "nodebuffer" - }).then((content) => { - res.setHeader("Content-Type", "application/zip"); - res.setHeader("Content-Disposition", `attachement; filename="${project.slug}_sprites.zip"`); - return res.send(content); + ExportFeatures.prototype.addSpritesExport = function() { + return this.webapp.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+\/([^\/\|\?\&\.]+\/)?export\/sprites\/$/, (function(_this) { + return function(req, res) { + var access, manager, project, queue, user, zip; + access = _this.webapp.getProjectAccess(req, res); + if (access == null) { + return; + } + user = access.user; + project = access.project; + manager = _this.webapp.getProjectManager(project); + zip = new JSZip; + queue = new JobQueue(function() { + return zip.generateAsync({ + type: "nodebuffer" + }).then(function(content) { + res.setHeader("Content-Type", "application/zip"); + res.setHeader("Content-Disposition", "attachement; filename=\"" + project.slug + "_sprites.zip\""); + return res.send(content); + }); }); - }); - queue.add(() => { - return manager.listFiles("sprites", (sprites) => { - var j, len, s; - for (j = 0, len = sprites.length; j < len; j++) { - s = sprites[j]; - ((s) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify s - return this.webapp.server.content.files.read(`${user.id}/${project.id}/sprites/${s.file}`, "binary", (content) => { + queue.add(function() { + return manager.listFiles("sprites", function(sprites) { + var fn, j, len, s; + fn = function(s) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/sprites/" + s.file, "binary", function(content) { if (content != null) { zip.file(s.file.replace(/-/g, "/"), content); } return queue.next(); }); }); - })(s); - } - return queue.next(); + }; + for (j = 0, len = sprites.length; j < len; j++) { + s = sprites[j]; + fn(s); + } + return queue.next(); + }); }); - }); - queue.add(() => { - return manager.listFiles("doc", (docs) => { - var doc, j, len; - for (j = 0, len = docs.length; j < len; j++) { - doc = docs[j]; - ((doc) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify doc - return this.webapp.server.content.files.read(`${user.id}/${project.id}/doc/${doc.file}`, "text", (content) => { + queue.add(function() { + return manager.listFiles("doc", function(docs) { + var doc, fn, j, len; + fn = function(doc) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/doc/" + doc.file, "text", function(content) { if (content != null) { zip.file(doc.file, content); } return queue.next(); }); }); - })(doc); - } - return queue.next(); + }; + for (j = 0, len = docs.length; j < len; j++) { + doc = docs[j]; + fn(doc); + } + return queue.next(); + }); }); - }); - return queue.start(); - }); - } - - addPublishHTML() { - // /user/project[/code]/publish/html/ - return this.webapp.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+\/([^\/\|\?\&\.]+\/)?publish\/html\/$/, (req, res) => { - var access, assets_list, fonts, fullsource, g, i, images, j, k, l, len, len1, len2, len3, lib, libs, manager, maps_dict, music_list, n, optlib, p, proglang, project, queue, ref, ref1, ref2, s, sounds_list, user, wrapsource, zip; - if ((req.query != null) && (req.query.server != null)) { - return this.publishServer(req, res); - } - access = this.webapp.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - manager = this.webapp.getProjectManager(project); - zip = new JSZip; - // icon16,32,64,180,192,512,1024.png - // manifest.json - maps_dict = {}; - images = []; - assets_list = []; - fonts = []; - sounds_list = []; - music_list = []; - fullsource = "\n\n"; - wrapsource = function(s) { - return s; + return queue.start(); }; - if (project.language === "microscript_v2") { // this is to prevent local variables contamination between files + })(this)); + }; + + ExportFeatures.prototype.addPublishHTML = function() { + return this.webapp.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+\/([^\/\|\?\&\.]+\/)?publish\/html\/$/, (function(_this) { + return function(req, res) { + var access, assets_list, fn, fonts, fullsource, g, i, images, j, k, l, len, len1, len2, len3, lib, libs, manager, maps_dict, music_list, n, optlib, p, proglang, project, queue, ref, ref1, ref2, s, sounds_list, user, wrapsource, zip; + if ((req.query != null) && (req.query.server != null)) { + return _this.publishServer(req, res); + } + access = _this.webapp.getProjectAccess(req, res); + if (access == null) { + return; + } + user = access.user; + project = access.project; + manager = _this.webapp.getProjectManager(project); + zip = new JSZip; + maps_dict = {}; + images = []; + assets_list = []; + fonts = []; + sounds_list = []; + music_list = []; + fullsource = "\n\n"; wrapsource = function(s) { - if (/^\s*\/\/\s*javascript\s*\n/.test(s)) { - return '\nsystem.javascript("""\n\n' + s.replace(/\\/g, "\\\\") + '\n\n""")\n'; - } else { - return `\nfunction()\n${s}\nend()\n`; - } + return s; }; - } - libs = []; - if ((project.graphics != null) && typeof project.graphics === "string") { - g = project.graphics.toLowerCase(); - p = this.webapp.concatenator.findAltPlayer(g); - if (p) { - libs = [].concat(p.lib_path); // clone the array, will be modified + if (project.language === "microscript_v2") { + wrapsource = function(s) { + if (/^\s*\/\/\s*javascript\s*\n/.test(s)) { + return '\nsystem.javascript("""\n\n' + s.replace(/\\/g, "\\\\") + '\n\n""")\n'; + } else { + return "\nfunction()\n" + s + "\nend()\n"; + } + }; } - } - ref = project.libs; - for (j = 0, len = ref.length; j < len; j++) { - optlib = ref[j]; - lib = this.webapp.concatenator.findOptionalLib(optlib); - if (lib) { - libs.push(lib.lib_path); + libs = []; + if ((project.graphics != null) && typeof project.graphics === "string") { + g = project.graphics.toLowerCase(); + p = _this.webapp.concatenator.findAltPlayer(g); + if (p) { + libs = [].concat(p.lib_path); + } } - } - proglang = this.webapp.concatenator.language_engines[project.language]; - if ((proglang != null) && proglang.scripts) { - ref1 = proglang.scripts; - for (k = 0, len1 = ref1.length; k < len1; k++) { - s = ref1[k]; - libs.push(`../static${s}`); + ref = project.libs; + for (j = 0, len = ref.length; j < len; j++) { + optlib = ref[j]; + lib = _this.webapp.concatenator.findOptionalLib(optlib); + if (lib) { + libs.push(lib.lib_path); + } } - } - if ((proglang != null) && (proglang.lib_path != null)) { - ref2 = proglang.lib_path; - for (l = 0, len2 = ref2.length; l < len2; l++) { - s = ref2[l]; - libs.push(s); + proglang = _this.webapp.concatenator.language_engines[project.language]; + if ((proglang != null) && proglang.scripts) { + ref1 = proglang.scripts; + for (k = 0, len1 = ref1.length; k < len1; k++) { + s = ref1[k]; + libs.push("../static" + s); + } } - } - queue = new JobQueue(() => { - var export_funk, html, mani, resources; - resources = JSON.stringify({ - images: images, - assets: assets_list, - maps: maps_dict, - sounds: sounds_list, - music: music_list - }); - resources = `var resources = ${resources};\n`; - resources += `var graphics = "${project.graphics}";\n`; - export_funk = pug.compileFile("../templates/export/html.pug"); - html = export_funk({ - user: user, - javascript_files: libs.concat(["microengine.js"]), - fonts: fonts, - game: { - name: project.slug, - title: project.title, - author: user.nick, - resources: resources, - orientation: project.orientation, - aspect: project.aspect, - libs: JSON.stringify(project.libs), - code: fullsource, - language: project.language, - use_server: project.networking || false + if ((proglang != null) && (proglang.lib_path != null)) { + ref2 = proglang.lib_path; + for (l = 0, len2 = ref2.length; l < len2; l++) { + s = ref2[l]; + libs.push(s); } + } + queue = new JobQueue(function() { + var export_funk, html, mani, resources; + resources = JSON.stringify({ + images: images, + assets: assets_list, + maps: maps_dict, + sounds: sounds_list, + music: music_list + }); + resources = "var resources = " + resources + ";\n"; + resources += "var graphics = \"" + project.graphics + "\";\n"; + export_funk = pug.compileFile("../templates/export/html.pug"); + html = export_funk({ + user: user, + javascript_files: libs.concat(["microengine.js"]), + fonts: fonts, + game: { + name: project.slug, + title: project.title, + author: user.nick, + resources: resources, + orientation: project.orientation, + aspect: project.aspect, + libs: JSON.stringify(project.libs), + code: fullsource, + language: project.language, + use_server: project.networking || false + } + }); + zip.file("index.html", html); + mani = _this.webapp.manifest_template.toString().replace(/SCOPE/g, ""); + mani = mani.toString().replace("APPNAME", project.title); + mani = mani.toString().replace("APPSHORTNAME", project.title); + mani = mani.toString().replace("ORIENTATION", project.orientation); + mani = mani.toString().replace(/USER/g, user.nick); + mani = mani.toString().replace(/PROJECT/g, project.slug); + mani = mani.toString().replace(/ICONVERSION/g, "0"); + mani = mani.replace("START_URL", "."); + zip.file("manifest.json", mani); + zip.file("microengine.js", _this.webapp.concatenator.getEngineExport(project.graphics)); + return zip.generateAsync({ + type: "nodebuffer" + }).then(function(content) { + res.setHeader("Content-Type", "application/zip"); + res.setHeader("Content-Disposition", "attachement; filename=\"" + project.slug + ".zip\""); + res.setHeader("Cache-Control", "no-cache"); + return res.send(content); + }); }); - zip.file("index.html", html); - mani = this.webapp.manifest_template.toString().replace(/SCOPE/g, ""); - mani = mani.toString().replace("APPNAME", project.title); - mani = mani.toString().replace("APPSHORTNAME", project.title); - mani = mani.toString().replace("ORIENTATION", project.orientation); - mani = mani.toString().replace(/USER/g, user.nick); - mani = mani.toString().replace(/PROJECT/g, project.slug); - mani = mani.toString().replace(/ICONVERSION/g, "0"); - mani = mani.replace("START_URL", "."); - zip.file("manifest.json", mani); - zip.file("microengine.js", this.webapp.concatenator.getEngineExport(project.graphics)); - return zip.generateAsync({ - type: "nodebuffer" - }).then((content) => { - res.setHeader("Content-Type", "application/zip"); - res.setHeader("Content-Disposition", `attachement; filename="${project.slug}.zip"`); - res.setHeader("Cache-Control", "no-cache"); - return res.send(content); - }); - }); - for (i = n = 0, len3 = libs.length; n < len3; i = ++n) { - lib = libs[i]; - ((lib, i) => { - return queue.add(() => { - return fs.readFile(lib, (err, data) => { + fn = function(lib, i) { + return queue.add(function() { + return fs.readFile(lib, function(err, data) { if (data != null) { data = data.toString("utf-8"); lib = lib.split("/"); @@ -369,207 +360,211 @@ this.ExportFeatures = class ExportFeatures { return queue.next(); }); }); - })(lib, i); - } - queue.add(() => { - return manager.listFiles("sprites", (sprites) => { - var len4, o; - for (o = 0, len4 = sprites.length; o < len4; o++) { - s = sprites[o]; - ((s) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify s - return this.webapp.server.content.files.read(`${user.id}/${project.id}/sprites/${s.file}`, "binary", (content) => { + }; + for (i = n = 0, len3 = libs.length; n < len3; i = ++n) { + lib = libs[i]; + fn(lib, i); + } + queue.add(function() { + return manager.listFiles("sprites", function(sprites) { + var fn1, len4, o; + fn1 = function(s) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/sprites/" + s.file, "binary", function(content) { if (content != null) { - zip.file(`sprites/${s.file}`, content); + zip.file("sprites/" + s.file, content); images.push(s); } return queue.next(); }); }); - })(s); - } - return queue.next(); + }; + for (o = 0, len4 = sprites.length; o < len4; o++) { + s = sprites[o]; + fn1(s); + } + return queue.next(); + }); }); - }); - queue.add(() => { - return manager.listFiles("maps", (maps) => { - var len4, map, o; - for (o = 0, len4 = maps.length; o < len4; o++) { - map = maps[o]; - ((map) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify map - return this.webapp.server.content.files.read(`${user.id}/${project.id}/maps/${map.file}`, "text", (content) => { + queue.add(function() { + return manager.listFiles("maps", function(maps) { + var fn1, len4, map, o; + fn1 = function(map) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/maps/" + map.file, "text", function(content) { if (content != null) { maps_dict[map.file.split(".")[0].replace(/-/g, "/")] = content; } return queue.next(); }); }); - })(map); - } - return queue.next(); + }; + for (o = 0, len4 = maps.length; o < len4; o++) { + map = maps[o]; + fn1(map); + } + return queue.next(); + }); }); - }); - queue.add(() => { - return manager.listFiles("sounds", (sounds) => { - var len4, o; - for (o = 0, len4 = sounds.length; o < len4; o++) { - s = sounds[o]; - ((s) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify s - return this.webapp.server.content.files.read(`${user.id}/${project.id}/sounds/${s.file}`, "binary", (content) => { + queue.add(function() { + return manager.listFiles("sounds", function(sounds) { + var fn1, len4, o; + fn1 = function(s) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/sounds/" + s.file, "binary", function(content) { if (content != null) { - zip.file(`sounds/${s.file}`, content); + zip.file("sounds/" + s.file, content); sounds_list.push(s); } return queue.next(); }); }); - })(s); - } - return queue.next(); + }; + for (o = 0, len4 = sounds.length; o < len4; o++) { + s = sounds[o]; + fn1(s); + } + return queue.next(); + }); }); - }); - queue.add(() => { - return manager.listFiles("music", (music) => { - var len4, m, o; - for (o = 0, len4 = music.length; o < len4; o++) { - m = music[o]; - ((m) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify m - return this.webapp.server.content.files.read(`${user.id}/${project.id}/music/${m.file}`, "binary", (content) => { + queue.add(function() { + return manager.listFiles("music", function(music) { + var fn1, len4, m, o; + fn1 = function(m) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/music/" + m.file, "binary", function(content) { if (content != null) { - zip.file(`music/${m.file}`, content); + zip.file("music/" + m.file, content); music_list.push(m); } return queue.next(); }); }); - })(m); - } - return queue.next(); + }; + for (o = 0, len4 = music.length; o < len4; o++) { + m = music[o]; + fn1(m); + } + return queue.next(); + }); }); - }); - queue.add(() => { - return manager.listFiles("assets", (assets) => { - var asset, len4, o; - for (o = 0, len4 = assets.length; o < len4; o++) { - asset = assets[o]; - ((asset) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify asset - return this.webapp.server.content.files.read(`${user.id}/${project.id}/assets/${asset.file}`, "binary", (content) => { + queue.add(function() { + return manager.listFiles("assets", function(assets) { + var asset, fn1, len4, o; + fn1 = function(asset) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/assets/" + asset.file, "binary", function(content) { if (content != null) { - zip.file(`assets/${asset.file}`, content); + zip.file("assets/" + asset.file, content); assets_list.push(asset); } return queue.next(); }); }); - })(asset); - } - return queue.next(); + }; + for (o = 0, len4 = assets.length; o < len4; o++) { + asset = assets[o]; + fn1(asset); + } + return queue.next(); + }); }); - }); - queue.add(() => { - return manager.listFiles("doc", (docs) => { - var doc, len4, o; - for (o = 0, len4 = docs.length; o < len4; o++) { - doc = docs[o]; - ((doc) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify doc - return this.webapp.server.content.files.read(`${user.id}/${project.id}/doc/${doc.file}`, "text", (content) => { + queue.add(function() { + return manager.listFiles("doc", function(docs) { + var doc, fn1, len4, o; + fn1 = function(doc) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/doc/" + doc.file, "text", function(content) { if (content != null) { zip.file(doc.file, content); } return queue.next(); }); }); - })(doc); - } - return queue.next(); + }; + for (o = 0, len4 = docs.length; o < len4; o++) { + doc = docs[o]; + fn1(doc); + } + return queue.next(); + }); }); - }); - queue.add(() => { - return manager.listFiles("ms", (ms) => { - var len4, o, src; - for (o = 0, len4 = ms.length; o < len4; o++) { - src = ms[o]; - ((src) => { - return queue.add(() => { - //console.info "reading: "+JSON.stringify src - return this.webapp.server.content.files.read(`${user.id}/${project.id}/ms/${src.file}`, "text", (content) => { + queue.add(function() { + return manager.listFiles("ms", function(ms) { + var fn1, len4, o, src; + fn1 = function(src) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/ms/" + src.file, "text", function(content) { if (content != null) { fullsource += wrapsource(content) + "\n\n"; } return queue.next(); }); }); - })(src); - } - queue.add(() => { - var font, len5, q, ref3; - ref3 = this.webapp.fonts.fonts; - for (q = 0, len5 = ref3.length; q < len5; q++) { - font = ref3[q]; - if (font === "BitCell" || fullsource.indexOf(`"${font}"`) >= 0) { - fonts.push(font); - ((font) => { - return queue.add(() => { - //console.info "reading font: #{font}" - return this.webapp.fonts.read(font, (data) => { - if (data != null) { - zip.file(`fonts/${font}.ttf`, data); - } - return queue.next(); + }; + for (o = 0, len4 = ms.length; o < len4; o++) { + src = ms[o]; + fn1(src); + } + queue.add(function() { + var font, len5, q, ref3; + ref3 = _this.webapp.fonts.fonts; + for (q = 0, len5 = ref3.length; q < len5; q++) { + font = ref3[q]; + if (font === "BitCell" || fullsource.indexOf("\"" + font + "\"") >= 0) { + fonts.push(font); + (function(font) { + return queue.add(function() { + return _this.webapp.fonts.read(font, function(data) { + if (data != null) { + zip.file("fonts/" + font + ".ttf", data); + } + return queue.next(); + }); }); - }); - })(font); + })(font); + } } - } + return queue.next(); + }); return queue.next(); }); - return queue.next(); }); - }); - queue.add(() => { - var path; - path = `${user.id}/${project.id}/sprites/icon.png`; - path = this.webapp.server.content.files.folder + "/" + this.webapp.server.content.files.sanitize(path); - return Jimp.read(path, (err, img) => { - var len4, o, ref3, size; - if (!err) { - ref3 = [16, 32, 64, 180, 192, 512, 1024]; - for (o = 0, len4 = ref3.length; o < len4; o++) { - size = ref3[o]; - ((size) => { - return queue.add(() => { - return img.clone().resize(size, size, Jimp.RESIZE_NEAREST_NEIGHBOR).getBuffer(Jimp.MIME_PNG, (err, buffer) => { + queue.add(function() { + var path; + path = user.id + "/" + project.id + "/sprites/icon.png"; + path = _this.webapp.server.content.files.folder + "/" + _this.webapp.server.content.files.sanitize(path); + return Jimp.read(path, function(err, img) { + var fn1, len4, o, ref3, size; + if (!err) { + ref3 = [16, 32, 64, 180, 192, 512, 1024]; + fn1 = function(size) { + return queue.add(function() { + return img.clone().resize(size, size, Jimp.RESIZE_NEAREST_NEIGHBOR).getBuffer(Jimp.MIME_PNG, function(err, buffer) { if (err) { return queue.next(); } else { - zip.file(`icon${size}.png`, buffer); + zip.file("icon" + size + ".png", buffer); return queue.next(); } }); }); - })(size); + }; + for (o = 0, len4 = ref3.length; o < len4; o++) { + size = ref3[o]; + fn1(size); + } } - } - return queue.next(); + return queue.next(); + }); }); - }); - return queue.start(); - }); - } + return queue.start(); + }; + })(this)); + }; - publishServer(req, res) { - var access, assets_list, fonts, fullsource, g, i, images, j, k, l, len, len1, len2, len3, lib, libs, manager, maps_dict, music_list, n, optlib, proglang, project, queue, ref, ref1, ref2, s, server_src, sounds_list, user, wrapsource, zip; + ExportFeatures.prototype.publishServer = function(req, res) { + var access, assets_list, fn, fonts, fullsource, g, i, images, j, k, l, len, len1, len2, len3, lib, libs, manager, maps_dict, music_list, n, optlib, proglang, project, queue, ref, ref1, ref2, s, server_src, sounds_list, user, wrapsource, zip; access = this.webapp.getProjectAccess(req, res); if (access == null) { return; @@ -589,12 +584,12 @@ this.ExportFeatures = class ExportFeatures { wrapsource = function(s) { return s; }; - if (project.language === "microscript_v2") { // this is to prevent local variables contamination between files + if (project.language === "microscript_v2") { wrapsource = function(s) { if (/^\s*\/\/\s*javascript\s*\n/.test(s)) { return '\nsystem.javascript("""\n\n' + s.replace(/\\/g, "\\\\") + '\n\n""")\n'; } else { - return `\nfunction()\n${s}\nend()\n`; + return "\nfunction()\n" + s + "\nend()\n"; } }; } @@ -602,7 +597,7 @@ this.ExportFeatures = class ExportFeatures { if ((project.graphics != null) && typeof project.graphics === "string") { g = project.graphics.toLowerCase(); if (this.webapp.concatenator.alt_players[g] != null) { - libs = [].concat(this.webapp.concatenator.alt_players[g].lib_path); // clone the array, will be modified + libs = [].concat(this.webapp.concatenator.alt_players[g].lib_path); } } ref = project.libs; @@ -618,7 +613,7 @@ this.ExportFeatures = class ExportFeatures { ref1 = proglang.scripts; for (k = 0, len1 = ref1.length; k < len1; k++) { s = ref1[k]; - libs.push(`../static${s}`); + libs.push("../static" + s); } } if ((proglang != null) && (proglang.lib_path != null)) { @@ -628,105 +623,118 @@ this.ExportFeatures = class ExportFeatures { libs.push(s); } } - queue = new JobQueue(() => { - var config_json, package_json, resources; - resources = JSON.stringify({ - images: images, - assets: assets_list, - maps: maps_dict, - sounds: sounds_list, - music: music_list - }); - resources = `var resources = ${resources};\n`; - resources += `var graphics = "${project.graphics}";\n`; - server_src += `\n\n${this.webapp.concatenator.getServerEngineExport(project.graphics)}`; - server_src = `var window = global ;\n\nvar start = function() {\n window.player = new this.Player(function(event) {\n if (event.name == "started") {\n // signal that the game is started\n }\n else if (event.name == "log") {\n // console.info(event.data) ;\n }\n }) ;\n}\n\nvar resources = ${JSON.stringify(resources)};\nvar graphics = "${project.graphics}";\n\nglobal.location = {\n pathname: "",\n hash: ""\n}\nglobal.navigator = {\n language: "en"\n}\n\nwindow.ms_libs = [] ;\n\nserver_code = \`\n${fullsource.replace(/`/g, "\\\`")}\n\`\n ${server_src}\n\nfor (const prop in this) {\n global[prop] = this[prop] ;\n}\n\nvar fs = require("fs") ;\nfs.readFile("./config.json",(err,data)=> {\n global.server_port = 3000 ;\n if (! err) {\n console.info("config.json loaded") ;\n try {\n var config = JSON.parse(data) ;\n global.server_port = config.port || 3000 ;\n } catch (err) {\n console.info("could not parse config file") ;\n }\n } else {\n console.info("could not read config file") ;\n }\n console.info( "starting with port set to: "+global.server_port ) ;\n start() ;\n}) ;`; - zip.file("server.js", server_src); - package_json = { - name: project.slug, - version: "1.0.0", - description: "", - main: "server.js", - scripts: { - start: "node server.js" - }, - author: project.owner.nick, - license: "", - dependencies: { - ws: "^8.10.0" - } - }; - config_json = { - port: 3000 + queue = new JobQueue((function(_this) { + return function() { + var config_json, package_json, resources; + resources = JSON.stringify({ + images: images, + assets: assets_list, + maps: maps_dict, + sounds: sounds_list, + music: music_list + }); + resources = "var resources = " + resources + ";\n"; + resources += "var graphics = \"" + project.graphics + "\";\n"; + server_src += "\n\n" + (_this.webapp.concatenator.getServerEngineExport(project.graphics)); + server_src = "var window = global ;\n\nvar start = function() {\n window.player = new this.Player(function(event) {\n if (event.name == \"started\") {\n // signal that the game is started\n }\n else if (event.name == \"log\") {\n // console.info(event.data) ;\n }\n }) ;\n}\n\nvar resources = " + (JSON.stringify(resources)) + ";\nvar graphics = \"" + project.graphics + "\";\n\nglobal.location = {\n pathname: \"\",\n hash: \"\"\n}\nglobal.navigator = {\n language: \"en\"\n}\n\nwindow.ms_libs = [] ;\n\nserver_code = `\n" + (fullsource.replace(/`/g, "\\\`")) + "\n`\n " + server_src + "\n\nfor (const prop in this) {\n global[prop] = this[prop] ;\n}\n\nvar fs = require(\"fs\") ;\nfs.readFile(\"./config.json\",(err,data)=> {\n global.server_port = 3000 ;\n if (! err) {\n console.info(\"config.json loaded\") ;\n try {\n var config = JSON.parse(data) ;\n global.server_port = config.port || 3000 ;\n } catch (err) {\n console.info(\"could not parse config file\") ;\n }\n } else {\n console.info(\"could not read config file\") ;\n }\n console.info( \"starting with port set to: \"+global.server_port ) ;\n start() ;\n}) ;"; + zip.file("server.js", server_src); + package_json = { + name: project.slug, + version: "1.0.0", + description: "", + main: "server.js", + scripts: { + start: "node server.js" + }, + author: project.owner.nick, + license: "", + dependencies: { + ws: "^8.10.0" + } + }; + config_json = { + port: 3000 + }; + zip.file("package.json", JSON.stringify(package_json, null, 2)); + zip.file("config.json", JSON.stringify(config_json, null, 2)); + zip.file("README.md", SERVER_EXPORT_README); + return zip.generateAsync({ + type: "nodebuffer" + }).then(function(content) { + res.setHeader("Content-Type", "application/zip"); + res.setHeader("Content-Disposition", "attachement; filename=\"" + project.slug + ".zip\""); + res.setHeader("Cache-Control", "no-cache"); + return res.send(content); + }); }; - zip.file("package.json", JSON.stringify(package_json, null, 2)); - zip.file("config.json", JSON.stringify(config_json, null, 2)); - zip.file("README.md", SERVER_EXPORT_README); - return zip.generateAsync({ - type: "nodebuffer" - }).then((content) => { - res.setHeader("Content-Type", "application/zip"); - res.setHeader("Content-Disposition", `attachement; filename="${project.slug}.zip"`); - res.setHeader("Cache-Control", "no-cache"); - return res.send(content); - }); - }); - for (i = n = 0, len3 = libs.length; n < len3; i = ++n) { - lib = libs[i]; - ((lib, i) => { - return queue.add(() => { - return fs.readFile(lib, (err, data) => { + })(this)); + fn = (function(_this) { + return function(lib, i) { + return queue.add(function() { + return fs.readFile(lib, function(err, data) { if (data != null) { data = data.toString("utf-8"); - server_src += `\n\n${data}`; + server_src += "\n\n" + data; } return queue.next(); }); }); - })(lib, i); + }; + })(this); + for (i = n = 0, len3 = libs.length; n < len3; i = ++n) { + lib = libs[i]; + fn(lib, i); } - queue.add(() => { - return manager.listFiles("maps", (maps) => { - var len4, map, o; - for (o = 0, len4 = maps.length; o < len4; o++) { - map = maps[o]; - ((map) => { - return queue.add(() => { - return this.webapp.server.content.files.read(`${user.id}/${project.id}/maps/${map.file}`, "text", (content) => { + queue.add((function(_this) { + return function() { + return manager.listFiles("maps", function(maps) { + var fn1, len4, map, o; + fn1 = function(map) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/maps/" + map.file, "text", function(content) { if (content != null) { maps_dict[map.file.split(".")[0].replace(/-/g, "/")] = content; } return queue.next(); }); }); - })(map); - } - return queue.next(); - }); - }); - queue.add(() => { - return manager.listFiles("ms", (ms) => { - var len4, o, src; - for (o = 0, len4 = ms.length; o < len4; o++) { - src = ms[o]; - ((src) => { - return queue.add(() => { - return this.webapp.server.content.files.read(`${user.id}/${project.id}/ms/${src.file}`, "text", (content) => { + }; + for (o = 0, len4 = maps.length; o < len4; o++) { + map = maps[o]; + fn1(map); + } + return queue.next(); + }); + }; + })(this)); + queue.add((function(_this) { + return function() { + return manager.listFiles("ms", function(ms) { + var fn1, len4, o, src; + fn1 = function(src) { + return queue.add(function() { + return _this.webapp.server.content.files.read(user.id + "/" + project.id + "/ms/" + src.file, "text", function(content) { if (content != null) { fullsource += wrapsource(content) + "\n\n"; } return queue.next(); }); }); - })(src); - } - return queue.next(); - }); - }); + }; + for (o = 0, len4 = ms.length; o < len4; o++) { + src = ms[o]; + fn1(src); + } + return queue.next(); + }); + }; + })(this)); return queue.start(); - } + }; + + return ExportFeatures; -}; +})(); SERVER_EXPORT_README = "# Running your microStudio game server\n\nPreliminary step: you should have NodeJS installed on your server.\n\nAfter unzipping the server export and changing directory to the folder containing this README:\n\n* Run `npm install`\n* Edit `config.json` to set the desired port for your game server\n* Run `npm run start` to start your game server\n\nYou can test your server by running your game locally. You should set the address of your own server\nwhen creating a new ServerConnection from the client, example: `connection = new ServerConnection('ws://127.0.0.1:3000')`."; diff --git a/server/concatenator.js b/server/concatenator.js index 96ee6e24..4686dc80 100644 --- a/server/concatenator.js +++ b/server/concatenator.js @@ -2,26 +2,34 @@ var fs; fs = require("fs"); -this.Concatenator = class Concatenator { - constructor(webapp) { - var k, key, ref, ref1, ref2, v, value; +this.Concatenator = (function() { + function Concatenator(webapp) { + var fn, k, key, ref, ref1, ref2, v, value; this.webapp = webapp; - this.webapp.app.get(/^\/all.js$/, (req, res) => { - res.setHeader("Content-Type", "text/javascript"); - return res.send(this.webapp_js_concat); - }); - this.webapp.app.get(/^\/all.css$/, (req, res) => { - res.setHeader("Content-Type", "text/css"); - return res.send(this.webapp_css_concat); - }); - this.webapp.app.get(/^\/play.js$/, (req, res) => { - res.setHeader("Content-Type", "text/javascript"); - return res.send(this.player_js_concat); - }); - this.webapp.app.get(/^\/server.js$/, (req, res) => { - res.setHeader("Content-Type", "text/javascript"); - return res.send(this.server_js_concat); - }); + this.webapp.app.get(/^\/all.js$/, (function(_this) { + return function(req, res) { + res.setHeader("Content-Type", "text/javascript"); + return res.send(_this.webapp_js_concat); + }; + })(this)); + this.webapp.app.get(/^\/all.css$/, (function(_this) { + return function(req, res) { + res.setHeader("Content-Type", "text/css"); + return res.send(_this.webapp_css_concat); + }; + })(this)); + this.webapp.app.get(/^\/play.js$/, (function(_this) { + return function(req, res) { + res.setHeader("Content-Type", "text/javascript"); + return res.send(_this.player_js_concat); + }; + })(this)); + this.webapp.app.get(/^\/server.js$/, (function(_this) { + return function(req, res) { + res.setHeader("Content-Type", "text/javascript"); + return res.send(_this.server_js_concat); + }; + })(this)); this.alt_player_base = ['/js/util/canvas2d.js', "/js/languages/microscript/random.js", "/js/runtime/microvm.js", "/js/runtime/mpserverconnection.js", '/js/runtime/runtime.js', '/js/runtime/watcher.js', '/js/runtime/projectinterface.js', '/js/runtime/timemachine.js', '/js/runtime/assetmanager.js', '/js/runtime/keyboard.js', '/js/runtime/gamepad.js', '/js/runtime/sprite.js', '/js/runtime/msimage.js', '/js/runtime/map.js', "/js/runtime/audio/audio.js", "/js/runtime/audio/beeper.js", "/js/runtime/audio/sound.js", "/js/runtime/audio/music.js", '/js/play/player.js', '/js/play/playerclient.js']; this.alt_players = { m2d: { @@ -51,7 +59,7 @@ this.Concatenator = class Concatenator { lib: ["/lib/pixijs/v7/pixi.min.js"], lib_path: ["../static/lib/pixijs/v7/pixi.min.js"], scripts: ['/js/runtime/pixi/screen.js', '/js/runtime/pixi/pixi.js'], - default: true + "default": true } } }, @@ -78,7 +86,7 @@ this.Concatenator = class Concatenator { lib: ["/lib/babylonjs/v6/babylon.js", "/lib/babylonjs/v6/babylonjs.loaders.min.js"], lib_path: ["../static/lib/babylonjs/v6/babylon.js", "../static/lib/babylonjs/v6/babylonjs.loaders.min.js"], scripts: ['/js/runtime/babylon/screen.js', '/js/runtime/babylon/babylon.js'], - default: true + "default": true } } } @@ -104,7 +112,7 @@ this.Concatenator = class Concatenator { name: "version 0.19", lib: "/lib/matterjs/v019/matter.min.js", lib_path: "../static/lib/matterjs/v019/matter.min.js", - default: true + "default": true } } }, @@ -149,29 +157,32 @@ this.Concatenator = class Concatenator { } }; ref = this.alt_players; - for (key in ref) { - value = ref[key]; - ((key, value) => { + fn = (function(_this) { + return function(key, value) { var k, ref1, results, v; - this.webapp.app.get(new RegExp(`^\\/${key}.js$`), (req, res) => { + _this.webapp.app.get(new RegExp("^\\/" + key + ".js$"), function(req, res) { res.setHeader("Content-Type", "text/javascript"); - return res.send(this[`${key}_js_concat`]); + return res.send(_this[key + "_js_concat"]); }); if (value.versions) { ref1 = value.versions; results = []; for (k in ref1) { v = ref1[k]; - results.push(((k, v) => { - return this.webapp.app.get(new RegExp(`^\\/${k}.js$`), (req, res) => { + results.push((function(k, v) { + return _this.webapp.app.get(new RegExp("^\\/" + k + ".js$"), function(req, res) { res.setHeader("Content-Type", "text/javascript"); - return res.send(this[`${k}_js_concat`]); + return res.send(_this[k + "_js_concat"]); }); })(k, v)); } return results; } - })(key, value); + }; + })(this); + for (key in ref) { + value = ref[key]; + fn(key, value); } this.webapp_css = ["/css/style.css", "/css/home.css", "/css/doc.css", "/css/code.css", "/css/debug.css", "/css/assets.css", "/css/sprites.css", "/css/sounds.css", "/css/synth.css", "/css/music.css", "/css/maps.css", "/css/publish.css", "/css/explore.css", "/css/options.css", "/css/sync.css", "/css/user.css", "/css/media.css", "/css/terminal.css", "/css/tutorial.css", "/css/md.css", "/css/common.css"]; this.webapp_js = ["/js/languages/microscript/random.js", "/js/languages/microscript/v2/parser.js", "/js/languages/microscript/v2/program.js", "/js/languages/microscript/v2/token.js", "/js/languages/microscript/v2/tokenizer.js", "/js/languages/microscript/microscript.js", "/js/languages/python/python.js", "/js/languages/javascript/javascript.js", "/js/languages/lua/lua.js", "/js/client/client.js", "/js/util/confirm.js", "/js/util/canvas2d.js", "/js/util/regexlib.js", "/js/util/inputvalidator.js", "/js/util/translator.js", "/js/manager.js", "/js/folderview.js", "/js/about/about.js", "/js/doc/documentation.js", "/js/doceditor/doceditor.js", "/js/editor/editor.js", "/js/editor/runwindow.js", "/js/editor/projectaccess.js", "/js/editor/rulercanvas.js", "/js/editor/valuetool.js", "/js/editor/libmanager.js", "/js/options/options.js", "/js/options/tabmanager.js", "/js/options/pluginview.js", "/js/sync/sync.js", "/js/publish/publish.js", "/js/publish/appbuild.js", "/js/explore/explore.js", "/js/explore/projectdetails.js", "/js/user/usersettings.js", "/js/user/translationapp.js", "/js/user/progress.js", "/js/spriteeditor/drawtool.js", "/js/spriteeditor/spritelist.js", "/js/spriteeditor/spriteeditor.js", "/js/spriteeditor/colorpicker.js", "/js/spriteeditor/spriteview.js", "/js/spriteeditor/animationpanel.js", "/js/spriteeditor/autopalette.js", "/js/spriteeditor/sprite.js", "/js/spriteeditor/spriteframe.js", "/js/mapeditor/mapview.js", "/js/mapeditor/mapeditor.js", "/js/mapeditor/tilepicker.js", "/js/mapeditor/map.js", "/js/assets/assetsmanager.js", "/js/assets/modelviewer.js", "/js/assets/imageviewer.js", "/js/assets/textviewer.js", "/js/assets/fontviewer.js", "/js/sound/soundeditor.js", "/js/sound/soundthumbnailer.js", "/js/music/musiceditor.js", "/js/util/undo.js", "/js/util/random.js", "/js/util/splitbar.js", "/js/util/pixelartscaler.js", "/js/runtime/microvm.js", "/js/debug/debug.js", "/js/debug/watch.js", "/js/debug/timemachine.js", "/js/terminal/terminal.js", "/js/project/project.js", "/js/project/projectfolder.js", "/js/project/projectsource.js", "/js/project/projectsprite.js", "/js/project/projectmap.js", "/js/project/projectasset.js", "/js/project/projectsound.js", "/js/project/projectmusic.js", "/js/appui/floatingwindow.js", "/js/appui/appui.js", "/js/app.js", "/js/appstate.js", "/js/tutorial/tutorials.js", "/js/tutorial/tutorial.js", "/js/tutorial/tutorialwindow.js", "/js/tutorial/highlighter.js", "/js/tutorial/tutorialspage.js"]; @@ -181,19 +192,19 @@ this.Concatenator = class Concatenator { ref1 = this.alt_players; for (key in ref1) { value = ref1[key]; - this[`${key}_js`] = this.alt_player_base.concat(value.scripts); + this[key + "_js"] = this.alt_player_base.concat(value.scripts); if (value.versions) { ref2 = value.versions; for (k in ref2) { v = ref2[k]; - this[`${k}_js`] = this.alt_player_base.concat(v.scripts); + this[k + "_js"] = this.alt_player_base.concat(v.scripts); } } } this.refresh(); } - refresh() { + Concatenator.prototype.refresh = function() { var k, key, ref, ref1, v, value; this.concat(this.webapp_js, "webapp_js_concat"); this.concat(this.player_js, "player_js_concat"); @@ -202,35 +213,35 @@ this.Concatenator = class Concatenator { ref = this.alt_players; for (key in ref) { value = ref[key]; - this.concat(this[`${key}_js`], `${key}_js_concat`); + this.concat(this[key + "_js"], key + "_js_concat"); if (value.versions != null) { ref1 = value.versions; for (k in ref1) { v = ref1[k]; - this.concat(this[`${k}_js`], `${k}_js_concat`); + this.concat(this[k + "_js"], k + "_js_concat"); } } } return this.concat(this.webapp_css, "webapp_css_concat"); - } + }; - getHomeJSFiles() { + Concatenator.prototype.getHomeJSFiles = function() { if (this.webapp.server.use_cache && (this.webapp_js_concat != null)) { return ["/all.js"]; } else { return this.webapp_js; } - } + }; - getHomeCSSFiles() { + Concatenator.prototype.getHomeCSSFiles = function() { if (this.webapp.server.use_cache && (this.webapp_css_concat != null)) { return ["/all.css"]; } else { return this.webapp_css; } - } + }; - findAltPlayer(graphics) { + Concatenator.prototype.findAltPlayer = function(graphics) { var id, player; if ((graphics != null) && typeof graphics === "string") { graphics = graphics.toLowerCase(); @@ -245,18 +256,18 @@ this.Concatenator = class Concatenator { } } return null; - } + }; - getPlayerJSFiles(graphics) { + Concatenator.prototype.getPlayerJSFiles = function(graphics) { var player; if ((graphics != null) && typeof graphics === "string") { graphics = graphics.toLowerCase(); player = this.findAltPlayer(graphics); if (player != null) { if (this.webapp.server.use_cache && (this.babylon_js_concat != null)) { - return player.lib.concat([`/${graphics}.js`]); + return player.lib.concat(["/" + graphics + ".js"]); } else { - return player.lib.concat(this[`${graphics}_js`]); + return player.lib.concat(this[graphics + "_js"]); } } else { if (this.webapp.server.use_cache && (this.player_js_concat != null)) { @@ -266,30 +277,30 @@ this.Concatenator = class Concatenator { } } } - } + }; - getServerJSFiles() { + Concatenator.prototype.getServerJSFiles = function() { if (this.webapp.server.use_cache && (this.server_js_concat != null)) { return ["/server.js"]; } else { return this.server_js; } - } + }; - getEngineExport(graphics) { + Concatenator.prototype.getEngineExport = function(graphics) { if ((graphics != null) && typeof graphics === "string") { graphics = graphics.toLowerCase(); - return this[`${graphics}_js_concat`] || this.player_js_concat; + return this[graphics + "_js_concat"] || this.player_js_concat; } else { return this.player_js_concat; } - } + }; - getServerEngineExport() { + Concatenator.prototype.getServerEngineExport = function() { return this.server_export_js_concat; - } + }; - findOptionalLib(lib) { + Concatenator.prototype.findOptionalLib = function(lib) { var id, l; if (typeof lib !== "string") { return false; @@ -305,9 +316,9 @@ this.Concatenator = class Concatenator { } else { return false; } - } + }; - concat(files, variable, callback) { + Concatenator.prototype.concat = function(files, variable, callback) { var f, funk, list, res; list = (function() { var i, len, results; @@ -319,28 +330,32 @@ this.Concatenator = class Concatenator { return results; })(); res = ""; - funk = () => { - if (list.length > 0) { - f = list.splice(0, 1)[0]; - f = "../static" + f; - return fs.readFile(f, (err, data) => { - if ((data != null) && (err == null)) { - res += data + "\n"; - return funk(); - } else if (err) { - return console.info(err); + funk = (function(_this) { + return function() { + if (list.length > 0) { + f = list.splice(0, 1)[0]; + f = "../static" + f; + return fs.readFile(f, function(err, data) { + if ((data != null) && (err == null)) { + res += data + "\n"; + return funk(); + } else if (err) { + return console.info(err); + } + }); + } else { + _this[variable] = res; + if (callback != null) { + return callback(); } - }); - } else { - this[variable] = res; - if (callback != null) { - return callback(); } - } - }; + }; + })(this); return funk(); - } + }; + + return Concatenator; -}; +})(); module.exports = this.Concatenator; diff --git a/server/content/comments.js b/server/content/comments.js index 0072140a..ea98fa63 100644 --- a/server/content/comments.js +++ b/server/content/comments.js @@ -1,13 +1,13 @@ var Comment; -this.Comments = class Comments { - constructor(project, data) { +this.Comments = (function() { + function Comments(project, data) { this.project = project; this.comments = []; this.load(data); } - load(data) { + Comments.prototype.load = function(data) { var c, j, len, user; if ((data != null) && data.length > 0) { for (j = 0, len = data.length; j < len; j++) { @@ -18,9 +18,9 @@ this.Comments = class Comments { } } } - } + }; - save() { + Comments.prototype.save = function() { var c, j, len, ref, res; res = []; ref = this.comments; @@ -34,9 +34,9 @@ this.Comments = class Comments { }); } return this.project.set("comments", res, false); - } + }; - getAll() { + Comments.prototype.getAll = function() { var c, i, j, len, ref, res; res = []; ref = this.comments; @@ -56,35 +56,33 @@ this.Comments = class Comments { } } return res; - } + }; - get(id) { + Comments.prototype.get = function(id) { return this.comments[id]; - } + }; - add(user, text) { + Comments.prototype.add = function(user, text) { this.comments.push(new Comment(this, user, { text: text, flags: {}, time: Date.now() })); return this.save(); - } + }; - remove(comment) { + Comments.prototype.remove = function(comment) { if (comment != null) { return comment.flags.deleted = true; } - } + }; + + return Comments; -}; +})(); -// index = @comments.indexOf(comment) -// if index>=0 -// @comments.splice(index,1) -// @save() -Comment = class Comment { - constructor(comments, user1, data) { +Comment = (function() { + function Comment(comments, user1, data) { this.comments = comments; this.user = user1; this.text = data.text; @@ -92,15 +90,17 @@ Comment = class Comment { this.time = data.time; } - edit(text1) { + Comment.prototype.edit = function(text1) { this.text = text1; return this.comments.save(); - } + }; - remove() { + Comment.prototype.remove = function() { return this.comments.remove(this); - } + }; + + return Comment; -}; +})(); module.exports = this.Comments; diff --git a/server/content/content.js b/server/content/content.js index 2432a60a..59787037 100644 --- a/server/content/content.js +++ b/server/content/content.js @@ -16,8 +16,8 @@ Forum = require(__dirname + "/../forum/forum.js"); Cleaner = require(__dirname + "/cleaner.js"); -this.Content = class Content { - constructor(server, db, files) { +this.Content = (function() { + function Content(server, db, files) { this.server = server; this.db = db; this.files = files; @@ -38,46 +38,52 @@ this.Content = class Content { this.plugin_projects = []; this.library_projects = []; this.updatePublicProjects(); - console.info(`Content loaded: ${this.user_count} users and ${this.project_count} projects`); - this.top_interval = setInterval((() => { - return this.sortPublicProjects(); - }), 10001); - this.log_interval = setInterval((() => { - return this.statusLog(); - }), 6000); + console.info("Content loaded: " + this.user_count + " users and " + this.project_count + " projects"); + this.top_interval = setInterval(((function(_this) { + return function() { + return _this.sortPublicProjects(); + }; + })(this)), 10001); + this.log_interval = setInterval(((function(_this) { + return function() { + return _this.statusLog(); + }; + })(this)), 6000); this.translator = new Translator(this); this.forum = new Forum(this); this.cleaner = new Cleaner(this); } - close() { + Content.prototype.close = function() { clearInterval(this.top_interval); clearInterval(this.log_interval); this.forum.close(); if (this.cleaner != null) { return this.cleaner.stop(); } - } - - statusLog() { - return usage(process.pid, (err, result) => { - if (result == null) { - return; - } - console.info("------------"); - console.info(`${new Date().toString()}`); - console.info(`cpu: ${Math.round(result.cpu)}%`); - console.info(`memory: ${Math.round(result.memory / 1000000)} mb`); - console.info(`users: ${this.user_count}`); - console.info(`projects: ${this.project_count}`); - this.current_cpu = Math.round(result.cpu); - this.current_memory = Math.round(result.memory / 1000000); - this.server.stats.max("cpu_max", Math.round(result.cpu)); - return this.server.stats.max("memory_max", this.current_memory); - }); - } + }; - load() { + Content.prototype.statusLog = function() { + return usage(process.pid, (function(_this) { + return function(err, result) { + if (result == null) { + return; + } + console.info("------------"); + console.info("" + (new Date().toString())); + console.info("cpu: " + (Math.round(result.cpu)) + "%"); + console.info("memory: " + (Math.round(result.memory / 1000000)) + " mb"); + console.info("users: " + _this.user_count); + console.info("projects: " + _this.project_count); + _this.current_cpu = Math.round(result.cpu); + _this.current_memory = Math.round(result.memory / 1000000); + _this.server.stats.max("cpu_max", Math.round(result.cpu)); + return _this.server.stats.max("memory_max", _this.current_memory); + }; + })(this)); + }; + + Content.prototype.load = function() { var j, k, l, len, len1, len2, projects, record, token, tokens, user, users; users = this.db.list("users"); for (j = 0, len = users.length; j < len; j++) { @@ -112,9 +118,9 @@ this.Content = class Content { this.loadProject(record); } this.initLikes(); - } + }; - loadUser(record) { + Content.prototype.loadUser = function(record) { var data, user; data = record.get(); user = new User(this, record); @@ -130,9 +136,9 @@ this.Content = class Content { this.users_by_nick[user.nick] = user; this.user_count++; return user; - } + }; - loadProject(record) { + Content.prototype.loadProject = function(record) { var data, project; data = record.get(); project = new Project(this, record); @@ -142,9 +148,9 @@ this.Content = class Content { this.project_count++; } return project; - } + }; - loadTags(project) { + Content.prototype.loadTags = function(project) { var j, len, ref, t, tag; ref = project.tags; for (j = 0, len = ref.length; j < len; j++) { @@ -157,9 +163,9 @@ this.Content = class Content { } tag.add(project); } - } + }; - loadToken(record) { + Content.prototype.loadToken = function(record) { var data, token; data = record.get(); token = new Token(this, record); @@ -167,9 +173,9 @@ this.Content = class Content { this.tokens[token.value] = token; } return token; - } + }; - initLikes() { + Content.prototype.initLikes = function() { var f, j, key, len, ref, ref1, user; ref = this.users; for (key in ref) { @@ -182,9 +188,9 @@ this.Content = class Content { } } } - } + }; - updatePublicProjects() { + Content.prototype.updatePublicProjects = function() { var key, project, ref; this.hot_projects = []; this.top_projects = []; @@ -194,7 +200,7 @@ this.Content = class Content { ref = this.projects; for (key in ref) { project = ref[key]; - if (project.public && !project.unlisted && project.owner.flags["validated"] && !project.deleted && !project.owner.flags["censored"]) { + if (project["public"] && !project.unlisted && project.owner.flags["validated"] && !project.deleted && !project.owner.flags["censored"]) { this.hot_projects.push(project); this.top_projects.push(project); this.new_projects.push(project); @@ -207,9 +213,9 @@ this.Content = class Content { } } return this.sortPublicProjects(); - } + }; - sortPublicProjects() { + Content.prototype.sortPublicProjects = function() { var fade, maxLikes, note, now, time; time = Date.now(); this.top_projects.sort(function(a, b) { @@ -244,10 +250,10 @@ this.Content = class Content { this.hot_projects.sort(function(a, b) { return note(b) - note(a); }); - return console.info(`Sorting public projects took: ${Date.now() - time} ms`); - } + return console.info("Sorting public projects took: " + (Date.now() - time) + " ms"); + }; - setProjectPublic(project, pub) { + Content.prototype.setProjectPublic = function(project, pub) { var index; project.set("public", pub); if (pub && project.first_published === 0) { @@ -270,7 +276,6 @@ this.Content = class Content { return this.library_projects.push(project); } } else { - //@sortPublicProjects() index = this.hot_projects.indexOf(project); if (index >= 0) { this.hot_projects.splice(index, 1); @@ -292,12 +297,12 @@ this.Content = class Content { return this.library_projects.splice(index, 1); } } - } + }; - setProjectType(project, type) { + Content.prototype.setProjectType = function(project, type) { var index; project.set("type", type); - if (project.public) { + if (project["public"]) { if (project.type === "plugin") { if (this.plugin_projects.indexOf(project) < 0) { this.plugin_projects.push(project); @@ -319,9 +324,9 @@ this.Content = class Content { } } } - } + }; - projectDeleted(project) { + Content.prototype.projectDeleted = function(project) { var index; this.project_count -= 1; index = this.hot_projects.indexOf(project); @@ -344,9 +349,9 @@ this.Content = class Content { if (index >= 0) { return this.library_projects.splice(index, 1); } - } + }; - addProjectTag(project, t) { + Content.prototype.addProjectTag = function(project, t) { var tag; tag = this.tags[t]; if (tag == null) { @@ -355,17 +360,17 @@ this.Content = class Content { this.sorted_tags.push(tag); } return tag.add(project); - } + }; - removeProjectTag(project, t) { + Content.prototype.removeProjectTag = function(project, t) { var tag; tag = this.tags[t]; if (tag != null) { return tag.remove(project); } - } + }; - setProjectTags(project, tags) { + Content.prototype.setProjectTags = function(project, tags) { var j, k, len, len1, ref, t; ref = project.tags; for (j = 0, len = ref.length; j < len; j++) { @@ -381,15 +386,15 @@ this.Content = class Content { } } return project.set("tags", tags); - } + }; - createUser(data) { + Content.prototype.createUser = function(data) { var record; record = this.db.create("users", data); return this.loadUser(record); - } + }; - createToken(user) { + Content.prototype.createToken = function(user) { var chars, i, j, record, value; value = ""; chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; @@ -402,23 +407,23 @@ this.Content = class Content { date_created: Date.now() }); return this.loadToken(record); - } + }; - findUserByNick(nick) { + Content.prototype.findUserByNick = function(nick) { return this.users_by_nick[nick]; - } + }; - findUserByEmail(email) { + Content.prototype.findUserByEmail = function(email) { return this.users_by_email[email]; - } + }; - changeUserNick(user, nick) { + Content.prototype.changeUserNick = function(user, nick) { delete this.users_by_nick[user.nick]; user.set("nick", nick); return this.users_by_nick[nick] = user; - } + }; - changeUserEmail(user, email) { + Content.prototype.changeUserEmail = function(user, email) { if (user.email != null) { delete this.users_by_email[user.email]; } else { @@ -426,9 +431,9 @@ this.Content = class Content { } user.set("email", email); return this.users_by_email[email] = user; - } + }; - userDeleted(user) { + Content.prototype.userDeleted = function(user) { delete this.users_by_nick[user.nick]; if (user.email != null) { delete this.users_by_email[user.email]; @@ -436,14 +441,17 @@ this.Content = class Content { this.guest_count -= 1; } return this.user_count -= 1; - } + }; - findToken(token) { + Content.prototype.findToken = function(token) { return this.tokens[token]; - } + }; - createProject(owner, data, callback, empty = false) { + Content.prototype.createProject = function(owner, data, callback, empty) { var content, count, d, project, record, slug; + if (empty == null) { + empty = false; + } slug = data.slug; if (owner.findProjectBySlug(slug)) { count = 2; @@ -457,7 +465,7 @@ this.Content = class Content { slug: data.slug, tags: [], likes: [], - public: data.public || false, + "public": data["public"] || false, date_created: Date.now(), last_modified: Date.now(), deleted: false, @@ -484,21 +492,23 @@ this.Content = class Content { } else { content = DEFAULT_CODE.microscript; } - return this.files.write(`${owner.id}/${project.id}/ms/main.ms`, content, () => { - return this.files.copyFile("../static/img/defaultappicon.png", `${owner.id}/${project.id}/sprites/icon.png`, () => { - return callback(project); - }); - }); + return this.files.write(owner.id + "/" + project.id + "/ms/main.ms", content, (function(_this) { + return function() { + return _this.files.copyFile("../static/img/defaultappicon.png", owner.id + "/" + project.id + "/sprites/icon.png", function() { + return callback(project); + }); + }; + })(this)); } - } + }; - getConsoleGameList() { + Content.prototype.getConsoleGameList = function() { var key, list, p, ref; list = []; ref = this.projects; for (key in ref) { p = ref[key]; - if (p.public && !p.deleted) { + if (p["public"] && !p.deleted) { list.push({ author: p.owner.nick, slug: p.slug, @@ -507,9 +517,9 @@ this.Content = class Content { } } return list; - } + }; - sendValidationMail(user) { + Content.prototype.sendValidationMail = function(user) { var subject, text, token, translator; if (user.email == null) { return; @@ -519,11 +529,11 @@ this.Content = class Content { subject = translator.get("Microstudio e-mail validation"); text = translator.get("Thank you for using Microstudio!") + "\n\n"; text += translator.get("Click on the link below to validate your e-mail address:") + "\n\n"; - text += `https://microstudio.dev/v/${user.id}/${token}` + "\n\n"; + text += ("https://microstudio.dev/v/" + user.id + "/" + token) + "\n\n"; return this.server.mailer.sendMail(user.email, subject, text); - } + }; - sendPasswordRecoveryMail(user) { + Content.prototype.sendPasswordRecoveryMail = function(user) { var subject, text, token, translator; if (user.email == null) { return; @@ -532,26 +542,28 @@ this.Content = class Content { translator = this.translator.getTranslator(user.language); subject = translator.get("Reset your microStudio password"); text = translator.get("Click on the link below to choose a new microStudio password:") + "\n\n"; - text += `https://microstudio.dev/pw/${user.id}/${token}` + "\n\n"; + text += ("https://microstudio.dev/pw/" + user.id + "/" + token) + "\n\n"; return this.server.mailer.sendMail(user.email, subject, text); - } + }; - checkValidationToken(user, token) { + Content.prototype.checkValidationToken = function(user, token) { return token === user.getValidationToken(); - } + }; - validateEMailAddress(user, token) { + Content.prototype.validateEMailAddress = function(user, token) { var translator; - console.info(`verifying ${token} against ${user.getValidationToken()}`); + console.info("verifying " + token + " against " + (user.getValidationToken())); if ((token != null) && token.length > 0 && this.checkValidationToken(user, token)) { user.resetValidationToken(); user.setFlag("validated", true); translator = this.translator.getTranslator(user.language); return user.notify(translator.get("Your e-mail address is now validated")); } - } + }; -}; + return Content; + +})(); DEFAULT_CODE = { python: "def init():\n pass\n\ndef update():\n pass\n\ndef draw():\n pass", diff --git a/server/content/project.js b/server/content/project.js index dd17570a..8427011d 100644 --- a/server/content/project.js +++ b/server/content/project.js @@ -4,8 +4,8 @@ Comments = require(__dirname + "/comments.js"); fs = require("fs"); -ProjectLink = class ProjectLink { - constructor(project, data) { +ProjectLink = (function() { + function ProjectLink(project, data) { this.project = project; this.user = this.project.content.users[data.user]; this.accepted = data.accepted; @@ -14,22 +14,24 @@ ProjectLink = class ProjectLink { } } - accept() { + ProjectLink.prototype.accept = function() { if (!this.accepted) { this.accepted = true; return this.project.saveUsers(); } - } + }; - remove() { + ProjectLink.prototype.remove = function() { this.project.removeUser(this); return this.user.removeLink(this.project.id); - } + }; + + return ProjectLink; -}; +})(); -this.Project = class Project { - constructor(content, record) { +this.Project = (function() { + function Project(content, record) { var data, j, len, link, ref, u; this.content = content; this.record = record; @@ -51,7 +53,7 @@ this.Project = class Project { this.flags = data.flags || {}; this.description = data.description || ""; this.likes = 0; - this.public = data.public; + this["public"] = data["public"]; this.unlisted = data.unlisted; this.date_created = data.date_created; this.last_modified = data.last_modified; @@ -96,7 +98,7 @@ this.Project = class Project { } } - createCode() { + Project.prototype.createCode = function() { var code, i, j, letters; letters = "ABCDEFGHJKMNPRSTUVWXYZ23456789"; code = ""; @@ -105,36 +107,39 @@ this.Project = class Project { } this.set("code", code); return code; - } + }; - touch() { + Project.prototype.touch = function() { var data; this.last_modified = Date.now(); data = this.record.get(); data.last_modified = this.last_modified; return this.record.set(data); - } + }; - set(prop, value, update_local = true) { + Project.prototype.set = function(prop, value, update_local) { var data; + if (update_local == null) { + update_local = true; + } data = this.record.get(); data[prop] = value; this.record.set(data); if (update_local) { return this[prop] = value; } - } + }; - setTitle(title) { + Project.prototype.setTitle = function(title) { if ((title != null) && title.trim().length > 0 && title.length < 50) { this.set("title", title); return true; } else { return false; } - } + }; - setSlug(slug) { + Project.prototype.setSlug = function(slug) { if ((slug != null) && /^([a-z0-9_][a-z0-9_-]{0,29})$/.test(slug)) { if (this.owner.findProjectBySlug(slug) != null) { return false; @@ -144,52 +149,52 @@ this.Project = class Project { } else { return false; } - } + }; - setCode(code) { + Project.prototype.setCode = function(code) { if ((code != null) && /^([a-zA-Z0-9_][a-zA-Z0-9_-]{0,29})$/.test(code)) { this.set("code", code); return true; } else { return false; } - } + }; - setType(type) { + Project.prototype.setType = function(type) { return this.set("type", type); - } + }; - setOrientation(orientation) { + Project.prototype.setOrientation = function(orientation) { return this.set("orientation", orientation); - } + }; - setAspect(aspect) { + Project.prototype.setAspect = function(aspect) { return this.set("aspect", aspect); - } + }; - setGraphics(graphics) { + Project.prototype.setGraphics = function(graphics) { return this.set("graphics", graphics); - } + }; - setFlag(flag, value) { + Project.prototype.setFlag = function(flag, value) { if (value) { this.flags[flag] = value; } else { delete this.flags[flag]; } return this.set("flags", this.flags); - } + }; - setProperty(prop, value) { + Project.prototype.setProperty = function(prop, value) { if (value != null) { this.properties[prop] = value; } else { delete this.properties[prop]; } return this.set("properties", this.properties); - } + }; - saveUsers() { + Project.prototype.saveUsers = function() { var data, j, len, link, ref; data = []; ref = this.users; @@ -201,9 +206,9 @@ this.Project = class Project { }); } return this.set("users", data, false); - } + }; - inviteUser(user) { + Project.prototype.inviteUser = function(user) { var j, len, link, ref; if (user === this.owner) { return; @@ -223,18 +228,18 @@ this.Project = class Project { this.users.push(link); return this.saveUsers(); } - } + }; - removeUser(link) { + Project.prototype.removeUser = function(link) { var index; index = this.users.indexOf(link); if (index >= 0) { this.users.splice(index, 1); return this.saveUsers(); } - } + }; - listUsers() { + Project.prototype.listUsers = function() { var j, len, link, list, ref; list = []; ref = this.users; @@ -249,9 +254,9 @@ this.Project = class Project { } } return list; - } + }; - delete() { + Project.prototype["delete"] = function() { var folder, i, j, link, ref; this.deleted = true; this.record.set({ @@ -263,37 +268,37 @@ this.Project = class Project { link.remove(); } delete this.manager; - folder = `${this.owner.id}/${this.id}`; + folder = this.owner.id + "/" + this.id; this.content.files.deleteFolder(folder); - } + }; - getFileInfo(file) { + Project.prototype.getFileInfo = function(file) { return this.files[file] || {}; - } + }; - setFileInfo(file, key, value) { + Project.prototype.setFileInfo = function(file, key, value) { var info; info = this.getFileInfo(file); info[key] = value; this.files[file] = info; this.set("files", this.files); return this.update_project_size = true; - } + }; - deleteFileInfo(file) { + Project.prototype.deleteFileInfo = function(file) { delete this.files[file]; this.set("files", this.files); return this.update_project_size = true; - } + }; - getSize() { + Project.prototype.getSize = function() { if (this.update_project_size) { this.updateProjectSize(); } return this.byte_size; - } + }; - updateProjectSize() { + Project.prototype.updateProjectSize = function() { var file, key, ref; this.byte_size = 0; this.update_project_size = false; @@ -304,78 +309,84 @@ this.Project = class Project { this.byte_size += file.size; } } - } + }; - filenameChanged(previous, next) { + Project.prototype.filenameChanged = function(previous, next) { if (this.files[previous] != null) { this.files[next] = this.files[previous]; delete this.files[previous]; return this.set("files", this.files); } - } + }; - fileDeleted(file) { + Project.prototype.fileDeleted = function(file) { if (this.files[file]) { delete this.files[file]; return this.set("files", this.files); } - } + }; - updateFileSizes(callback) { + Project.prototype.updateFileSizes = function(callback) { var list, maps, process, source, sprites; - source = "../files/" + this.content.files.sanitize(`${this.owner.id}/${this.id}/ms`); - sprites = "../files/" + this.content.files.sanitize(`${this.owner.id}/${this.id}/sprites`); - maps = "../files/" + this.content.files.sanitize(`${this.owner.id}/${this.id}/maps`); + source = "../files/" + this.content.files.sanitize(this.owner.id + "/" + this.id + "/ms"); + sprites = "../files/" + this.content.files.sanitize(this.owner.id + "/" + this.id + "/sprites"); + maps = "../files/" + this.content.files.sanitize(this.owner.id + "/" + this.id + "/maps"); list = []; - process = () => { - var f, file; - if (list.length > 0) { - f = list.splice(0, 1)[0]; - file = "../files/" + this.content.files.sanitize(`${this.owner.id}/${this.id}/${f}`); - return fs.lstat(file, (err, stat) => { - if ((stat != null) && (stat.size != null)) { - this.setFileInfo(f, "size", stat.size); + process = (function(_this) { + return function() { + var f, file; + if (list.length > 0) { + f = list.splice(0, 1)[0]; + file = "../files/" + _this.content.files.sanitize(_this.owner.id + "/" + _this.id + "/" + f); + return fs.lstat(file, function(err, stat) { + if ((stat != null) && (stat.size != null)) { + _this.setFileInfo(f, "size", stat.size); + } + return setTimeout((function() { + return process(); + }), 0); + }); + } else { + if (callback != null) { + return callback(); } - return setTimeout((() => { - return process(); - }), 0); - }); - } else { - if (callback != null) { - return callback(); - } - } - }; - return fs.readdir(source, (err, files) => { - var f, j, len; - if (files) { - for (j = 0, len = files.length; j < len; j++) { - f = files[j]; - list.push(`ms/${f}`); } - } - return fs.readdir(sprites, (err, files) => { - var k, len1; + }; + })(this); + return fs.readdir(source, (function(_this) { + return function(err, files) { + var f, j, len; if (files) { - for (k = 0, len1 = files.length; k < len1; k++) { - f = files[k]; - list.push(`sprites/${f}`); + for (j = 0, len = files.length; j < len; j++) { + f = files[j]; + list.push("ms/" + f); } } - return fs.readdir(maps, (err, files) => { - var l, len2; + return fs.readdir(sprites, function(err, files) { + var k, len1; if (files) { - for (l = 0, len2 = files.length; l < len2; l++) { - f = files[l]; - list.push(`maps/${f}`); + for (k = 0, len1 = files.length; k < len1; k++) { + f = files[k]; + list.push("sprites/" + f); } } - return process(); + return fs.readdir(maps, function(err, files) { + var l, len2; + if (files) { + for (l = 0, len2 = files.length; l < len2; l++) { + f = files[l]; + list.push("maps/" + f); + } + } + return process(); + }); }); - }); - }); - } + }; + })(this)); + }; + + return Project; -}; +})(); module.exports = this.Project; diff --git a/server/forum/forum.js b/server/forum/forum.js index 77d0b556..cdea02fe 100644 --- a/server/forum/forum.js +++ b/server/forum/forum.js @@ -8,8 +8,8 @@ ForumReply = require(__dirname + "/reply.js"); Indexer = require(__dirname + "/indexer.js"); -this.Forum = class Forum { - constructor(content) { +this.Forum = (function() { + function Forum(content) { this.content = content; this.db = this.content.db; this.server = this.content.server; @@ -25,16 +25,16 @@ this.Forum = class Forum { this.load(); } - close() { + Forum.prototype.close = function() { var i, indexer, key, len, ref; ref = this.indexers; for (indexer = i = 0, len = ref.length; i < len; indexer = ++i) { key = ref[indexer]; indexer.stop(); } - } + }; - load() { + Forum.prototype.load = function() { var categories, i, j, k, len, len1, len2, posts, record, replies; categories = this.db.list("forum_categories"); for (i = 0, len = categories.length; i < len; i++) { @@ -52,9 +52,9 @@ this.Forum = class Forum { this.loadReply(record); } this.updateActivity(); - } + }; - index(language, text, target, uid) { + Forum.prototype.index = function(language, text, target, uid) { var indexer; if (language == null) { return; @@ -64,9 +64,9 @@ this.Forum = class Forum { this.indexers[language] = indexer = new Indexer(); } return indexer.add(text, target, uid); - } + }; - loadCategory(record) { + Forum.prototype.loadCategory = function(record) { var cat; cat = new ForumCategory(this, record); if ((cat.language != null) && !cat.deleted) { @@ -79,9 +79,9 @@ this.Forum = class Forum { this.category_count++; } return cat; - } + }; - loadPost(record) { + Forum.prototype.loadPost = function(record) { var category, catid, post; catid = record.getField("category"); category = this.categories[catid]; @@ -92,15 +92,15 @@ this.Forum = class Forum { this.posts[post.id] = post; if (!category.hidden) { this.post_count++; - this.index(post.category.language, `${post.title} ${post.category.name} ${post.author.nick}`, post, post.id); + this.index(post.category.language, post.title + " " + post.category.name + " " + post.author.nick, post, post.id); this.index(post.category.language, post.text, post, post.id); } } return post; } - } + }; - loadReply(record) { + Forum.prototype.loadReply = function(record) { var post, postid, reply; postid = record.getField("post"); post = this.posts[postid]; @@ -116,9 +116,9 @@ this.Forum = class Forum { return reply; } } - } + }; - createPost(category, user, title, text) { + Forum.prototype.createPost = function(category, user, title, text) { var data, err, i, id, len, post, record, ref; data = { author: user, @@ -146,9 +146,9 @@ this.Forum = class Forum { } } return post; - } + }; - createReply(post, user, text) { + Forum.prototype.createReply = function(post, user, text) { var data, i, id, len, record, ref, reply; data = { post: post.id, @@ -167,9 +167,9 @@ this.Forum = class Forum { this.sendReplyNotification(id, reply); } return reply; - } + }; - sendPostNotification(userid, post) { + Forum.prototype.sendPostNotification = function(userid, post) { var subject, text, translator, user; user = this.content.users[userid]; if (user == null) { @@ -185,15 +185,15 @@ this.Forum = class Forum { return; } translator = this.content.translator.getTranslator(user.language); - subject = translator.get("%USER% posted in %CATEGORY%").replace("%USER%", post.author.nick).replace("%CATEGORY%", post.category.name) + ` - ${translator.get("microStudio Community")}`; + subject = translator.get("%USER% posted in %CATEGORY%").replace("%USER%", post.author.nick).replace("%CATEGORY%", post.category.name) + (" - " + (translator.get("microStudio Community"))); text = translator.get("%USER% published a new post in %CATEGORY%:").replace("%USER%", post.author.nick).replace("%CATEGORY%", post.category.name) + "\n\n"; text += post.title + "\n"; - text += `https://microstudio.dev${post.getPath()}\n\n`; + text += "https://microstudio.dev" + (post.getPath()) + "\n\n"; text += post.text.length < 500 ? post.text : post.text.substring(0, 500) + " (...)"; return this.server.mailer.sendMail(user.email, subject, text); - } + }; - sendReplyNotification(userid, reply) { + Forum.prototype.sendReplyNotification = function(userid, reply) { var subject, text, translator, user; user = this.content.users[userid]; if (user == null) { @@ -209,14 +209,14 @@ this.Forum = class Forum { return; } translator = this.content.translator.getTranslator(user.language); - subject = translator.get("%USER% posted a reply").replace("%USER%", reply.author.nick) + ` - ${translator.get("microStudio Community")}`; + subject = translator.get("%USER% posted a reply").replace("%USER%", reply.author.nick) + (" - " + (translator.get("microStudio Community"))); text = translator.get("%USER% posted a reply to %POST%:").replace("%USER%", reply.author.nick).replace("%POST%", reply.post.title) + "\n\n"; - text += `https://microstudio.dev${reply.post.getPath()}${reply.post.replies.length - 1}/\n\n`; + text += "https://microstudio.dev" + (reply.post.getPath()) + (reply.post.replies.length - 1) + "/\n\n"; text += reply.text.length < 500 ? reply.text : reply.text.substring(0, 500) + " (...)"; return this.server.mailer.sendMail(user.email, subject, text); - } + }; - createCategory(language, name, slug, description, hue, permissions) { + Forum.prototype.createCategory = function(language, name, slug, description, hue, permissions) { var cat, data, record; data = { language: language, @@ -230,15 +230,15 @@ this.Forum = class Forum { }; record = this.db.create("forum_categories", data); return cat = this.loadCategory(record); - } + }; - editCategory(user, category, data) {} + Forum.prototype.editCategory = function(user, category, data) {}; - editPost(user, post, data) {} + Forum.prototype.editPost = function(user, post, data) {}; - editReply(user, post, reply, data) {} + Forum.prototype.editReply = function(user, post, reply, data) {}; - listCategories(lang) { + Forum.prototype.listCategories = function(lang) { var c, cats, i, len, res; cats = this.languages[lang]; if (cats != null) { @@ -256,9 +256,9 @@ this.Forum = class Forum { } else { return []; } - } + }; - updateActivity() { + Forum.prototype.updateActivity = function() { var cat, key, ref; this.activity = 0; ref = this.categories; @@ -267,30 +267,32 @@ this.Forum = class Forum { this.activity = Math.max(this.activity, cat.activity); } return this.sorted = false; - } + }; - getLanguages() { + Forum.prototype.getLanguages = function() { var key, lang; lang = []; for (key in this.languages) { lang.push(key); } return lang; - } + }; - getCategory(language, slug) { + Forum.prototype.getCategory = function(language, slug) { var lang; lang = this.languages[language]; if (!lang) { return null; } return lang[slug]; - } + }; - escapeHTML(s) { + Forum.prototype.escapeHTML = function(s) { return s.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>'); - } + }; + + return Forum; -}; +})(); module.exports = this.Forum; diff --git a/server/forum/forumapp.js b/server/forum/forumapp.js index 354baa05..62762a2a 100644 --- a/server/forum/forumapp.js +++ b/server/forum/forumapp.js @@ -2,8 +2,8 @@ var pug; pug = require("pug"); -this.ForumApp = class ForumApp { - constructor(server, webapp) { +this.ForumApp = (function() { + function ForumApp(server, webapp) { this.server = server; this.webapp = webapp; this.app = this.webapp.app; @@ -16,181 +16,184 @@ this.ForumApp = class ForumApp { } return hue % 360; }; - // main forum page - this.app.get(/^\/(..\/)?community\/?$/, (req, res) => { - var c, cats, description, j, k, l, lang, len, len1, len2, len3, list, m, n, p, posts, ps, ref; - if (this.webapp.ensureDevArea(req, res)) { - return; - } - lang = "en"; - ref = this.webapp.languages; - for (j = 0, len = ref.length; j < len; j++) { - l = ref[j]; - if (req.path.startsWith(`/${l}/`)) { - lang = l; + this.app.get(/^\/(..\/)?community\/?$/, (function(_this) { + return function(req, res) { + var c, cats, description, j, k, l, lang, len, len1, len2, len3, list, m, n, p, posts, ps, ref; + if (_this.webapp.ensureDevArea(req, res)) { + return; } - } - list = this.forum.listCategories(lang); - cats = []; - cats.push({ - name: this.server.content.translator.get(lang, "All"), - slug: "all", - hue: 220, - path: `${(lang !== "en" ? `/${lang}` : "")}/community/` - }); - for (k = 0, len1 = list.length; k < len1; k++) { - c = list[k]; - cats.push(c); - } - posts = []; - for (m = 0, len2 = list.length; m < len2; m++) { - c = list[m]; - ps = c.getSortedPosts(); - for (n = 0, len3 = ps.length; n < len3; n++) { - p = ps[n]; - if (!p.isDeleted()) { - posts.push(p); + lang = "en"; + ref = _this.webapp.languages; + for (j = 0, len = ref.length; j < len; j++) { + l = ref[j]; + if (req.path.startsWith("/" + l + "/")) { + lang = l; } } - } - posts.sort(function(a, b) { - return b.activity - a.activity; - }); - description = `${this.server.content.translator.get(lang, "Welcome!")}\n${this.server.content.translator.get(lang, "In this space you can ask for help, share your best tips, read articles, submit bugs or feature requests, follow the roadmap and progress of microStudio.")}\n${this.server.content.translator.get(lang, "You can discuss programming, game development, art, sound, music, useful tools and resources, microStudio and other game engines.")}\n${this.server.content.translator.get(lang, "For anything else there is an Off Topic category.")}`; - return this.categoryPage(req, res, lang, cats, "all", this.server.content.translator.get(lang, "Community"), description, posts); - }); - // forum category - this.app.get(/^\/(..\/)?community\/([^\/\|\?\&\.]+)\/?$/, (req, res) => { - var c, category, cats, description, j, k, l, lang, len, len1, len2, list, m, p, path, posts, ref; - if (this.webapp.ensureDevArea(req, res)) { - return; - } - lang = "en"; - ref = this.webapp.languages; - for (j = 0, len = ref.length; j < len; j++) { - l = ref[j]; - if (req.path.startsWith(`/${l}/`)) { - lang = l; - } - } - path = req.path.split("/"); - path.splice(0, 1); - if (path[0] !== "community") { - path.splice(0, 1); - } - category = path[1]; - category = this.forum.category_by_slug[category]; - if (category) { - list = this.forum.listCategories(lang); + list = _this.forum.listCategories(lang); cats = []; - cats.push(category); cats.push({ - name: this.server.content.translator.get(lang, "All"), + name: _this.server.content.translator.get(lang, "All"), slug: "all", hue: 220, - path: `${(lang !== "en" ? `/${lang}` : "")}/community/` + path: (lang !== "en" ? "/" + lang : "") + "/community/" }); for (k = 0, len1 = list.length; k < len1; k++) { c = list[k]; - if (c !== category) { - cats.push(c); - } + cats.push(c); } - list = category.getSortedPosts(); posts = []; for (m = 0, len2 = list.length; m < len2; m++) { - p = list[m]; - if (!p.isDeleted()) { - posts.push(p); + c = list[m]; + ps = c.getSortedPosts(); + for (n = 0, len3 = ps.length; n < len3; n++) { + p = ps[n]; + if (!p.isDeleted()) { + posts.push(p); + } } } - description = category.description; - return this.categoryPage(req, res, lang, cats, category.slug, category.name, description, posts, category.permissions); - } else { - return this.webapp.return404(req, res); - } - }); - // forum post - this.app.get(/^\/(..\/)?community\/([^\/\|\?\&\.]+)\/([^\/\|\?\&\.]+)\/\d+(\/\d+)?\/?$/, (req, res) => { - var c, cat, category, cats, id, j, k, l, lang, len, len1, list, path, post, ref, scroll, slug, theme; - if (this.webapp.ensureDevArea(req, res)) { - return; - } - lang = "en"; - ref = this.webapp.languages; - for (j = 0, len = ref.length; j < len; j++) { - l = ref[j]; - if (req.path.startsWith(`/${l}/`)) { - lang = l; + posts.sort(function(a, b) { + return b.activity - a.activity; + }); + description = (_this.server.content.translator.get(lang, "Welcome!")) + "\n" + (_this.server.content.translator.get(lang, "In this space you can ask for help, share your best tips, read articles, submit bugs or feature requests, follow the roadmap and progress of microStudio.")) + "\n" + (_this.server.content.translator.get(lang, "You can discuss programming, game development, art, sound, music, useful tools and resources, microStudio and other game engines.")) + "\n" + (_this.server.content.translator.get(lang, "For anything else there is an Off Topic category.")); + return _this.categoryPage(req, res, lang, cats, "all", _this.server.content.translator.get(lang, "Community"), description, posts); + }; + })(this)); + this.app.get(/^\/(..\/)?community\/([^\/\|\?\&\.]+)\/?$/, (function(_this) { + return function(req, res) { + var c, category, cats, description, j, k, l, lang, len, len1, len2, list, m, p, path, posts, ref; + if (_this.webapp.ensureDevArea(req, res)) { + return; } - } - path = req.path.split("/"); - path.splice(0, 1); - if (path[0] !== "community") { + lang = "en"; + ref = _this.webapp.languages; + for (j = 0, len = ref.length; j < len; j++) { + l = ref[j]; + if (req.path.startsWith("/" + l + "/")) { + lang = l; + } + } + path = req.path.split("/"); path.splice(0, 1); - } - category = path[1]; - slug = path[2]; - id = path[3]; - scroll = path[4]; - post = this.forum.posts[id]; - if ((post != null) && !post.isDeleted() && !post.author.flags.censored && !post.author.flags.banned) { - cat = post.category; - list = this.forum.listCategories(lang); - cats = []; - cats.push(cat); - cats.push({ - name: this.server.content.translator.get(lang, "All"), - slug: "all", - hue: 220, - path: `${(lang !== "en" ? `/${lang}` : "")}/community/` - }); - for (k = 0, len1 = list.length; k < len1; k++) { - c = list[k]; - if (c !== cat) { - cats.push(c); + if (path[0] !== "community") { + path.splice(0, 1); + } + category = path[1]; + category = _this.forum.category_by_slug[category]; + if (category) { + list = _this.forum.listCategories(lang); + cats = []; + cats.push(category); + cats.push({ + name: _this.server.content.translator.get(lang, "All"), + slug: "all", + hue: 220, + path: (lang !== "en" ? "/" + lang : "") + "/community/" + }); + for (k = 0, len1 = list.length; k < len1; k++) { + c = list[k]; + if (c !== category) { + cats.push(c); + } + } + list = category.getSortedPosts(); + posts = []; + for (m = 0, len2 = list.length; m < len2; m++) { + p = list[m]; + if (!p.isDeleted()) { + posts.push(p); + } } + description = category.description; + return _this.categoryPage(req, res, lang, cats, category.slug, category.name, description, posts, category.permissions); + } else { + return _this.webapp.return404(req, res); } - if ((this.post == null) || !this.server.use_cache) { - this.post = pug.compileFile("../templates/forum/post.pug"); + }; + })(this)); + this.app.get(/^\/(..\/)?community\/([^\/\|\?\&\.]+)\/([^\/\|\?\&\.]+)\/\d+(\/\d+)?\/?$/, (function(_this) { + return function(req, res) { + var c, cat, category, cats, id, j, k, l, lang, len, len1, list, path, post, ref, scroll, slug, theme; + if (_this.webapp.ensureDevArea(req, res)) { + return; } - theme = req.cookies.theme || "light"; - res.send(this.post({ - translator: this.server.content.translator.getTranslator(lang), - language: lang, - categories: cats, - selected: category, - post: post, - scroll: scroll, - getHue: this.getHue, - theme: theme, - translation: this.server.content.translator.languages[lang] != null ? this.server.content.translator.languages[lang].export() : "{}", - post_info: { - id: post.id, - slug: post.slug, - category: category, - permissions: post.category.permissions, - post_permissions: post.permissions, - url: `${req.protocol}://${req.hostname}/${(lang === "en" ? "" : `${lang}/`)}community/${category}/${slug}/${id}/` - }, - community: { - language: lang, - category: category + lang = "en"; + ref = _this.webapp.languages; + for (j = 0, len = ref.length; j < len; j++) { + l = ref[j]; + if (req.path.startsWith("/" + l + "/")) { + lang = l; } - })); - return post.view(req.connection.remoteAddress); - } else { - return this.webapp.return404(req, res); - } - }); + } + path = req.path.split("/"); + path.splice(0, 1); + if (path[0] !== "community") { + path.splice(0, 1); + } + category = path[1]; + slug = path[2]; + id = path[3]; + scroll = path[4]; + post = _this.forum.posts[id]; + if ((post != null) && !post.isDeleted() && !post.author.flags.censored && !post.author.flags.banned) { + cat = post.category; + list = _this.forum.listCategories(lang); + cats = []; + cats.push(cat); + cats.push({ + name: _this.server.content.translator.get(lang, "All"), + slug: "all", + hue: 220, + path: (lang !== "en" ? "/" + lang : "") + "/community/" + }); + for (k = 0, len1 = list.length; k < len1; k++) { + c = list[k]; + if (c !== cat) { + cats.push(c); + } + } + if ((_this.post == null) || !_this.server.use_cache) { + _this.post = pug.compileFile("../templates/forum/post.pug"); + } + theme = req.cookies.theme || "light"; + res.send(_this.post({ + translator: _this.server.content.translator.getTranslator(lang), + language: lang, + categories: cats, + selected: category, + post: post, + scroll: scroll, + getHue: _this.getHue, + theme: theme, + translation: _this.server.content.translator.languages[lang] != null ? _this.server.content.translator.languages[lang]["export"]() : "{}", + post_info: { + id: post.id, + slug: post.slug, + category: category, + permissions: post.category.permissions, + post_permissions: post.permissions, + url: req.protocol + "://" + req.hostname + "/" + (lang === "en" ? "" : lang + "/") + "community/" + category + "/" + slug + "/" + id + "/" + }, + community: { + language: lang, + category: category + } + })); + return post.view(req.connection.remoteAddress); + } else { + return _this.webapp.return404(req, res); + } + }; + })(this)); } - categoryPage(req, res, lang, cats, selected, name, description, posts, permissions) { + ForumApp.prototype.categoryPage = function(req, res, lang, cats, selected, name, description, posts, permissions) { var langpath, theme; if ((this.category == null) || !this.server.use_cache) { this.category = pug.compileFile("../templates/forum/forum.pug"); } - langpath = lang === "en" ? "" : `/${lang}`; + langpath = lang === "en" ? "" : "/" + lang; theme = req.cookies.theme || "light"; return res.send(this.category({ translator: this.server.content.translator.getTranslator(lang), @@ -202,7 +205,7 @@ this.ForumApp = class ForumApp { name: name, theme: theme, description: description, - translation: this.server.content.translator.languages[lang] != null ? this.server.content.translator.languages[lang].export() : "{}", + translation: this.server.content.translator.languages[lang] != null ? this.server.content.translator.languages[lang]["export"]() : "{}", community: { language: lang, category: selected, @@ -211,8 +214,10 @@ this.ForumApp = class ForumApp { }, getHue: this.getHue })); - } + }; + + return ForumApp; -}; +})(); module.exports = this.ForumApp; diff --git a/server/forum/post.js b/server/forum/post.js index 82504360..46339256 100644 --- a/server/forum/post.js +++ b/server/forum/post.js @@ -5,8 +5,8 @@ sanitizeHTML = require("sanitize-html"); allowedTags = sanitizeHTML.defaults.allowedTags.concat(["img"]); -this.ForumPost = class ForumPost { - constructor(category, record) { +this.ForumPost = (function() { + function ForumPost(category, record) { var data; this.category = category; this.record = record; @@ -26,7 +26,6 @@ this.ForumPost = class ForumPost { this.likes = data.likes || []; this.watch = data.watch || []; this.users_watching = []; - // @reactions = data.reactions or [] this.pinned = data.pinned; this.replies = []; this.slug = this.slugify(this.title); @@ -37,18 +36,18 @@ this.ForumPost = class ForumPost { this.reverse = data.reverse; } - isDeleted() { + ForumPost.prototype.isDeleted = function() { return this.deleted || (this.author == null) || this.author.flags.deleted; - } + }; - addReply(reply) { + ForumPost.prototype.addReply = function(reply) { this.replies.push(reply); if (!reply.deleted) { return this.addPeople(reply.author); } - } + }; - addPeople(author) { + ForumPost.prototype.addPeople = function(author) { var i, len, p, ref; this.sort_people = true; ref = this.people; @@ -63,9 +62,9 @@ this.ForumPost = class ForumPost { author: author, replies: 1 }); - } + }; - getPeople() { + ForumPost.prototype.getPeople = function() { if (this.sort_people) { this.sort_people = false; this.people.sort(function(a, b) { @@ -73,35 +72,35 @@ this.ForumPost = class ForumPost { }); } return this.people; - } + }; - set(prop, value) { + ForumPost.prototype.set = function(prop, value) { var data; data = this.record.get(); data[prop] = value; this.record.set(data); return this[prop] = value; - } + }; - setCategoryId(id) { + ForumPost.prototype.setCategoryId = function(id) { var data; data = this.record.get(); data["category"] = id; return this.record.set(data); - } + }; - edit(text) { + ForumPost.prototype.edit = function(text) { this.set("text", text); this.set("edits", this.edits + 1); return this.updateActivity(); - } + }; - setTitle(title) { + ForumPost.prototype.setTitle = function(title) { this.set("title", title); return this.slug = this.slugify(this.title); - } + }; - addLike(id) { + ForumPost.prototype.addLike = function(id) { var index; index = this.likes.indexOf(id); if (index < 0) { @@ -109,9 +108,9 @@ this.ForumPost = class ForumPost { this.set("likes", this.likes); } return this.likes.length; - } + }; - removeLike(id) { + ForumPost.prototype.removeLike = function(id) { var index; index = this.likes.indexOf(id); if (index >= 0) { @@ -119,40 +118,40 @@ this.ForumPost = class ForumPost { this.set("likes", this.likes); } return this.likes.length; - } + }; - isLiked(id) { + ForumPost.prototype.isLiked = function(id) { return this.likes.indexOf(id) >= 0; - } + }; - addWatch(id) { + ForumPost.prototype.addWatch = function(id) { var index; index = this.watch.indexOf(id); if (index < 0) { this.watch.push(id); return this.set("watch", this.watch); } - } + }; - removeWatch(id) { + ForumPost.prototype.removeWatch = function(id) { var index; index = this.watch.indexOf(id); if (index >= 0) { this.watch.splice(index, 1); return this.set("watch", this.watch); } - } + }; - isWatching(id) { + ForumPost.prototype.isWatching = function(id) { return this.watch.indexOf(id) >= 0; - } + }; - view(ip) { + ForumPost.prototype.view = function(ip) { if (ip == null) { return; } if ((this.views_buffer == null) || Date.now() > this.views_buffer_expiration) { - this.views_buffer_expiration = Date.now() + 2 * 60 * 60 * 1000; // one view per 2 hours per ip + this.views_buffer_expiration = Date.now() + 2 * 60 * 60 * 1000; this.views_buffer = {}; } if (this.views_buffer[ip]) { @@ -160,38 +159,40 @@ this.ForumPost = class ForumPost { } this.views_buffer[ip] = true; return this.set("views", this.views + 1); - } + }; - updateActivity() { + ForumPost.prototype.updateActivity = function() { this.set("activity", Date.now()); return this.category.updateActivity(); - } + }; - getPath() { + ForumPost.prototype.getPath = function() { var path; path = "/"; if (this.category.language !== "en") { - path += `${this.category.language}/`; + path += this.category.language + "/"; } - path += `community/${this.category.slug}/`; - return path += `${this.slug}/${this.id}/`; - } + path += "community/" + this.category.slug + "/"; + return path += this.slug + "/" + this.id + "/"; + }; - slugify(text) { + ForumPost.prototype.slugify = function(text) { var res; res = text.normalize('NFD').replace(/[\s]/g, "-").replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase(); if (res.length === 0) { res = "_"; } return res; - } + }; - getHTMLText() { + ForumPost.prototype.getHTMLText = function() { return sanitizeHTML(marked(this.text), { allowedTags: allowedTags }); - } + }; + + return ForumPost; -}; +})(); module.exports = this.ForumPost; diff --git a/server/forum/reply.js b/server/forum/reply.js index f8e0ae1a..2dcb3526 100644 --- a/server/forum/reply.js +++ b/server/forum/reply.js @@ -5,8 +5,8 @@ sanitizeHTML = require("sanitize-html"); allowedTags = sanitizeHTML.defaults.allowedTags.concat(["img"]); -this.ForumReply = class ForumReply { - constructor(post, record) { +this.ForumReply = (function() { + function ForumReply(post, record) { var data; this.post = post; this.record = record; @@ -23,25 +23,25 @@ this.ForumReply = class ForumReply { this.pinned = data.pinned; } - isDeleted() { + ForumReply.prototype.isDeleted = function() { return this.deleted || (this.author == null) || this.author.flags.deleted; - } + }; - set(prop, value) { + ForumReply.prototype.set = function(prop, value) { var data; data = this.record.get(); data[prop] = value; this.record.set(data); return this[prop] = value; - } + }; - edit(text) { + ForumReply.prototype.edit = function(text) { this.set("text", text); this.set("edits", this.edits + 1); return this.set("activity", Date.now()); - } + }; - addLike(id) { + ForumReply.prototype.addLike = function(id) { var index; index = this.likes.indexOf(id); if (index < 0) { @@ -49,9 +49,9 @@ this.ForumReply = class ForumReply { this.set("likes", this.likes); } return this.likes.length; - } + }; - removeLike(id) { + ForumReply.prototype.removeLike = function(id) { var index; index = this.likes.indexOf(id); if (index >= 0) { @@ -59,23 +59,25 @@ this.ForumReply = class ForumReply { this.set("likes", this.likes); } return this.likes.length; - } + }; - isLiked(id) { + ForumReply.prototype.isLiked = function(id) { return this.likes.indexOf(id) >= 0; - } + }; - updateActivity() { + ForumReply.prototype.updateActivity = function() { this.set("activity", Date.now()); return this.post.updateActivity(); - } + }; - getHTMLText() { + ForumReply.prototype.getHTMLText = function() { return sanitizeHTML(marked(this.text), { allowedTags: allowedTags }); - } + }; + + return ForumReply; -}; +})(); module.exports = this.ForumReply; diff --git a/server/gamify/achievements.js b/server/gamify/achievements.js index cde7078c..5b5d2a08 100644 --- a/server/gamify/achievements.js +++ b/server/gamify/achievements.js @@ -1,5 +1,5 @@ -this.Achievement = class { - constructor(props) { +this.Achievement = (function() { + function _Class(props) { this.id = props.id; this.name = props.name; this.description = props.description; @@ -9,16 +9,18 @@ this.Achievement = class { this.xp = props.xp || 0; } -}; + return _Class; -this.Achievements = new class { - constructor() { +})(); + +this.Achievements = new ((function() { + function _Class() { this.list = []; this.by_stat = {}; this.by_id = {}; } - add(a) { + _Class.prototype.add = function(a) { var by_stat; this.list.push(a); this.by_id[a.id] = a; @@ -29,12 +31,12 @@ this.Achievements = new class { } return by_stat.push(a); } - } + }; + + return _Class; -}; +})()); -// Code achievements -//######################### this.Achievements.add(new this.Achievement({ id: "code/al_khwarizmi", name: "Al Khwarizmi", @@ -155,8 +157,6 @@ this.Achievements.add(new this.Achievement({ xp: 6000 })); -// Art achievements -//######################### this.Achievements.add(new this.Achievement({ id: "art/cave_art", name: "Cave Art", @@ -247,8 +247,6 @@ this.Achievements.add(new this.Achievement({ xp: 5000 })); -// Level design achievements -//########################## this.Achievements.add(new this.Achievement({ id: "level_design/level1", name: "Level Design Rookie", @@ -348,8 +346,6 @@ this.Achievements.add(new this.Achievement({ xp: 5500 })); -// Tutorial achievements -//########################## this.Achievements.add(new this.Achievement({ id: "tutorials/tutorial_tour", name: "microStudio Tourist", @@ -378,8 +374,6 @@ this.Achievements.add(new this.Achievement({ xp: 2000 })); -// Community achievements -//######################### this.Achievements.add(new this.Achievement({ id: "community/5_likes", name: "Recognition", diff --git a/server/ratelimiter.js b/server/ratelimiter.js index b189874b..2c82d852 100644 --- a/server/ratelimiter.js +++ b/server/ratelimiter.js @@ -1,43 +1,44 @@ var RateLimiterClass; -this.RateLimiter = class RateLimiter { - constructor(server) { +this.RateLimiter = (function() { + function RateLimiter(server) { this.server = server; this.map = {}; - this.map.request = new RateLimiterClass(this, 1, 1000 * 100); // > 1000 home page loads per minute (> 5000 realtime) - this.map.request_ip = new RateLimiterClass(this, 1, 100 * 100); // > 100 home page loads per minute per ip (> 500 realtime) - this.map.login_ip = new RateLimiterClass(this, 1, 20); // 20 tentatives de login par minute de la même IP - this.map.login_user = new RateLimiterClass(this, 2, 10); // 10 tentatives de login par username par 2 minutes - this.map.delete_account = new RateLimiterClass(this, 5, 5); // 5 tentatives de suppression par user par 5 minutes - this.map.send_mail_user = new RateLimiterClass(this, 5, 5); // 5 mails max en 5 minutes - this.map.create_account_ip = new RateLimiterClass(this, 30, 30); // 30 comptes pour 30 minutes => classroom check - this.map.create_project_user = new RateLimiterClass(this, 60, 10); // max 10 projects per hour - this.map.import_project_user = new RateLimiterClass(this, 60, 10); // max 10 projects per hour - this.map.file_upload_user = new RateLimiterClass(this, 10, 10); // max 10 large file uploads per ten minutes - this.map.create_file_user = new RateLimiterClass(this, 5, 40); // max 40 new files per 5 minutes - //@map.change_file_user = new RateLimiterClass(@,10,200) - this.map.post_comment_user = new RateLimiterClass(this, 10, 10); // max 10 new comments per 10 minutes - this.map.create_forum_post = new RateLimiterClass(this, 60, 10); // max 10 new posts per hour - this.map.create_forum_reply = new RateLimiterClass(this, 10, 10); // max 10 new replies per 10 minutes - this.map.search_forum = new RateLimiterClass(this, 1, 15); // max 15 searches per minute - this.interval = setInterval((() => { - return this.log(); - }), 5000); + this.map.request = new RateLimiterClass(this, 1, 1000 * 100); + this.map.request_ip = new RateLimiterClass(this, 1, 100 * 100); + this.map.login_ip = new RateLimiterClass(this, 1, 20); + this.map.login_user = new RateLimiterClass(this, 2, 10); + this.map.delete_account = new RateLimiterClass(this, 5, 5); + this.map.send_mail_user = new RateLimiterClass(this, 5, 5); + this.map.create_account_ip = new RateLimiterClass(this, 30, 30); + this.map.create_project_user = new RateLimiterClass(this, 60, 10); + this.map.import_project_user = new RateLimiterClass(this, 60, 10); + this.map.file_upload_user = new RateLimiterClass(this, 10, 10); + this.map.create_file_user = new RateLimiterClass(this, 5, 40); + this.map.post_comment_user = new RateLimiterClass(this, 10, 10); + this.map.create_forum_post = new RateLimiterClass(this, 60, 10); + this.map.create_forum_reply = new RateLimiterClass(this, 10, 10); + this.map.search_forum = new RateLimiterClass(this, 1, 15); + this.interval = setInterval(((function(_this) { + return function() { + return _this.log(); + }; + })(this)), 5000); } - accept(type, key) { + RateLimiter.prototype.accept = function(type, key) { if (this.map[type] != null) { return this.map[type].accept(key); } else { return false; } - } + }; - close() { + RateLimiter.prototype.close = function() { return clearInterval(this.interval); - } + }; - log() { + RateLimiter.prototype.log = function() { var key, limiter, max, ref; ref = this.map; for (key in ref) { @@ -45,15 +46,17 @@ this.RateLimiter = class RateLimiter { limiter.checkTime(); max = Math.round(limiter.max_count / limiter.quantity * 100); if (max > 10) { - console.info(`rate limiter ${key} at ${max}% for ${limiter.maxer}`); + console.info("rate limiter " + key + " at " + max + "% for " + limiter.maxer); } } - } + }; + + return RateLimiter; -}; +})(); -RateLimiterClass = class RateLimiterClass { - constructor(rate_limiter, minutes, quantity) { +RateLimiterClass = (function() { + function RateLimiterClass(rate_limiter, minutes, quantity) { this.rate_limiter = rate_limiter; this.minutes = minutes; this.quantity = quantity; @@ -63,7 +66,7 @@ RateLimiterClass = class RateLimiterClass { this.maxer = ""; } - checkTime() { + RateLimiterClass.prototype.checkTime = function() { var now; now = Math.floor(Date.now() / (this.minutes * 60000)); if (now !== this.current) { @@ -72,9 +75,9 @@ RateLimiterClass = class RateLimiterClass { this.max_count = 0; return this.maxer = ""; } - } + }; - accept(key) { + RateLimiterClass.prototype.accept = function(key) { this.checkTime(); if (key == null) { return false; @@ -92,8 +95,10 @@ RateLimiterClass = class RateLimiterClass { } return true; } - } + }; + + return RateLimiterClass; -}; +})(); module.exports = this.RateLimiter; diff --git a/server/relay/relay.js b/server/relay/relay.js index 759ab163..062db7c4 100644 --- a/server/relay/relay.js +++ b/server/relay/relay.js @@ -4,28 +4,30 @@ WebSocket = require("ws"); RelaySession = require(__dirname + "/relaysession.js"); -Relay = class Relay { - constructor(config = {}) { - this.config = config; +Relay = (function() { + function Relay(config) { + this.config = config != null ? config : {}; this.sessions = []; this.create(); this.token_requests = {}; } - create() { + Relay.prototype.create = function() { this.io = new WebSocket.Server({ port: this.config.relay_port }); this.sessions = []; - this.io.on("connection", (socket, request) => { - socket.request = request; - socket.remoteAddress = request.connection.remoteAddress; - return this.sessions.push(new RelaySession(this, socket)); - }); + this.io.on("connection", (function(_this) { + return function(socket, request) { + socket.request = request; + socket.remoteAddress = request.connection.remoteAddress; + return _this.sessions.push(new RelaySession(_this, socket)); + }; + })(this)); return this.startClient(); - } + }; - startClient() { + Relay.prototype.startClient = function() { var err, interval, msg; try { console.info("connecting to main server..."); @@ -35,83 +37,99 @@ Relay = class Relay { key: this.config.key, address: this.config.relay_address }); - this.client.on("open", () => { - console.info("connected to main server"); - return this.client.send(msg); - }); - this.client.on("message", (msg) => { - var data; - try { - data = JSON.parse(msg.data); - if (data.name === "check_server_token") { - if (data.valid && (this.token_requests[data.token] != null)) { - this.token_requests[data.token](); - return delete this.token_requests[data.token]; + this.client.on("open", (function(_this) { + return function() { + console.info("connected to main server"); + return _this.client.send(msg); + }; + })(this)); + this.client.on("message", (function(_this) { + return function(msg) { + var data; + try { + data = JSON.parse(msg.data); + if (data.name === "check_server_token") { + if (data.valid && (_this.token_requests[data.token] != null)) { + _this.token_requests[data.token](); + return delete _this.token_requests[data.token]; + } } + } catch (error) {} + }; + })(this)); + interval = setInterval(((function(_this) { + return function() { + var err; + try { + return _this.client.send(msg); + } catch (error) { + err = error; } - } catch (error) {} - }); - interval = setInterval((() => { - var err; - try { - return this.client.send(msg); - } catch (error) { - err = error; - } - }), 60000); - this.client.on("error", (err) => { - console.info(err); - clearInterval(interval); - setTimeout((() => { - return this.startClient(); - }), 5000); - return this.client.close(); - }); - return this.client.on("close", (msg) => { - clearInterval(interval); - return setTimeout((() => { - return this.startClient(); - }), 5000); - }); + }; + })(this)), 60000); + this.client.on("error", (function(_this) { + return function(err) { + console.info(err); + clearInterval(interval); + setTimeout((function() { + return _this.startClient(); + }), 5000); + return _this.client.close(); + }; + })(this)); + return this.client.on("close", (function(_this) { + return function(msg) { + clearInterval(interval); + return setTimeout((function() { + return _this.startClient(); + }), 5000); + }; + })(this)); } catch (error) { err = error; console.error(err); if (interval != null) { clearInterval(interval); } - return setTimeout((() => { - return this.startClient(); - }), 5000); + return setTimeout(((function(_this) { + return function() { + return _this.startClient(); + }; + })(this)), 5000); } - } + }; - sessionClosed(session) { + Relay.prototype.sessionClosed = function(session) { var index; index = this.sessions.indexOf(session); if (index >= 0) { return this.sessions.splice(index, 1); } - } + }; - serverTokenCheck(token, server_id, callback) { + Relay.prototype.serverTokenCheck = function(token, server_id, callback) { this.token_requests[token] = callback(); return this.client.send(JSON.stringify({ name: "check_server_token", server_id: server_id, token: token })); - } + }; -}; + return Relay; + +})(); fs = require("fs"); -fs.readFile(__dirname + "/config.json", (err, data) => { - if (!err) { - this.config = JSON.parse(data); - console.info("config.json loaded"); - } else { - console.info("No config.json file found, running with default settings"); - } - return this.relay = new Relay(this.config); -}); +fs.readFile(__dirname + "/config.json", (function(_this) { + return function(err, data) { + if (!err) { + _this.config = JSON.parse(data); + console.info("config.json loaded"); + } else { + console.info("No config.json file found, running with default settings"); + } + return _this.relay = new Relay(_this.config); + }; +})(this)); diff --git a/server/relay/relayservice.js b/server/relay/relayservice.js index 780d60e4..2bc7ff8e 100644 --- a/server/relay/relayservice.js +++ b/server/relay/relayservice.js @@ -2,41 +2,49 @@ var ServerInstance; ServerInstance = require(__dirname + "/serverinstance.js"); -this.RelayService = class RelayService { - constructor(session) { +this.RelayService = (function() { + function RelayService(session) { this.session = session; - this.session.register("mp_start_server", (msg) => { - return this.startServer(msg); - }); - this.session.register("mp_client_connection", (msg) => { - return this.clientConnection(msg); - }); - this.session.register("mp_server_status", (msg) => { - return this.serverStatus(msg); - }); + this.session.register("mp_start_server", (function(_this) { + return function(msg) { + return _this.startServer(msg); + }; + })(this)); + this.session.register("mp_client_connection", (function(_this) { + return function(msg) { + return _this.clientConnection(msg); + }; + })(this)); + this.session.register("mp_server_status", (function(_this) { + return function(msg) { + return _this.serverStatus(msg); + }; + })(this)); } - startServer(msg) { + RelayService.prototype.startServer = function(msg) { if (msg.server_id == null) { return; } if (msg.token == null) { return; } - return this.session.serverTokenCheck(msg.token, msg.server_id, () => { - var instance; - instance = new ServerInstance(this, msg.server_id, this.session); - return RelayService.servers[msg.server_id] = instance; - }); - } + return this.session.serverTokenCheck(msg.token, msg.server_id, (function(_this) { + return function() { + var instance; + instance = new ServerInstance(_this, msg.server_id, _this.session); + return RelayService.servers[msg.server_id] = instance; + }; + })(this)); + }; - serverDisconnected(server) { + RelayService.prototype.serverDisconnected = function(server) { if (server === RelayService.servers[server.id]) { return delete RelayService.servers[server.id]; } - } + }; - clientConnection(msg) { + RelayService.prototype.clientConnection = function(msg) { var server; if (msg.server_id == null) { return; @@ -47,9 +55,9 @@ this.RelayService = class RelayService { } else { return this.session.socket.close(); } - } + }; - serverStatus(msg) { + RelayService.prototype.serverStatus = function(msg) { var server; if (msg.server_id == null) { return; @@ -60,9 +68,11 @@ this.RelayService = class RelayService { server_id: msg.server_id, running: server != null }); - } + }; + + return RelayService; -}; +})(); this.RelayService.servers = {}; diff --git a/server/relay/relaysession.js b/server/relay/relaysession.js index 88ec8ee4..faa15c91 100644 --- a/server/relay/relaysession.js +++ b/server/relay/relaysession.js @@ -2,39 +2,44 @@ var RelayService; RelayService = require(__dirname + "/relayservice.js"); -this.RelaySession = class RelaySession { - constructor(server, socket) { +this.RelaySession = (function() { + function RelaySession(server, socket) { this.server = server; this.socket = socket; - this.socket.on("message", (msg) => { - this.messageReceived(msg); - return this.last_active = Date.now(); - }); - this.socket.on("close", () => { - this.server.sessionClosed(this); - return this.disconnected(); - }); - this.socket.on("error", (err) => { - console.error("WS ERROR"); - return console.error(err); - }); + this.socket.on("message", (function(_this) { + return function(msg) { + _this.messageReceived(msg); + return _this.last_active = Date.now(); + }; + })(this)); + this.socket.on("close", (function(_this) { + return function() { + _this.server.sessionClosed(_this); + return _this.disconnected(); + }; + })(this)); + this.socket.on("error", (function(_this) { + return function(err) { + console.error("WS ERROR"); + return console.error(err); + }; + })(this)); this.commands = {}; this.relay_service = new RelayService(this); } - register(name, callback) { + RelaySession.prototype.register = function(name, callback) { return this.commands[name] = callback; - } + }; - disconnected() {} + RelaySession.prototype.disconnected = function() {}; - messageReceived(msg) { + RelaySession.prototype.messageReceived = function(msg) { var c, err; if (typeof msg !== "string") { return this.bufferReceived(msg); } try { - //console.info msg msg = JSON.parse(msg); if (msg.name != null) { c = this.commands[msg.name]; @@ -46,16 +51,18 @@ this.RelaySession = class RelaySession { err = error; return console.info(err); } - } + }; - send(data) { + RelaySession.prototype.send = function(data) { return this.socket.send(JSON.stringify(data)); - } + }; - serverTokenCheck(token, server_id, callback) { + RelaySession.prototype.serverTokenCheck = function(token, server_id, callback) { return this.server.serverTokenCheck(token, server_id, callback); - } + }; + + return RelaySession; -}; +})(); module.exports = this.RelaySession; diff --git a/server/relay/serverinstance.js b/server/relay/serverinstance.js index f8a08cf3..3467e752 100644 --- a/server/relay/serverinstance.js +++ b/server/relay/serverinstance.js @@ -1,36 +1,44 @@ -this.ServerInstance = class ServerInstance { - constructor(relay, id, session) { +this.ServerInstance = (function() { + function ServerInstance(relay, id, session) { this.relay = relay; this.id = id; this.session = session; this.connected_clients = {}; - this.interval = setInterval((() => { - return this.timer(); - }), 8); + this.interval = setInterval(((function(_this) { + return function() { + return _this.timer(); + }; + })(this)), 8); this.start_time = Date.now(); this.time = 0; this.client_id = 1; - this.session.register("mp_server_message", (msg) => { - return this.message(msg); - }); - this.session.register("mp_disconnect_client", (msg) => { - return this.disconnectClient(msg); - }); - this.session.disconnected = () => { - var client, key, ref, results; - this.relay.serverDisconnected(this); - this.stop(); - ref = this.connected_clients; - results = []; - for (key in ref) { - client = ref[key]; - results.push(client.socket.close()); - } - return results; - }; + this.session.register("mp_server_message", (function(_this) { + return function(msg) { + return _this.message(msg); + }; + })(this)); + this.session.register("mp_disconnect_client", (function(_this) { + return function(msg) { + return _this.disconnectClient(msg); + }; + })(this)); + this.session.disconnected = (function(_this) { + return function() { + var client, key, ref, results; + _this.relay.serverDisconnected(_this); + _this.stop(); + ref = _this.connected_clients; + results = []; + for (key in ref) { + client = ref[key]; + results.push(client.socket.close()); + } + return results; + }; + })(this); } - message(msg) { + ServerInstance.prototype.message = function(msg) { var client; client = this.connected_clients[msg.client_id]; if (client != null) { @@ -39,9 +47,9 @@ this.ServerInstance = class ServerInstance { data: msg.data }); } - } + }; - disconnectClient(msg) { + ServerInstance.prototype.disconnectClient = function(msg) { var client, err; client = this.connected_clients[msg.client_id]; if (client != null) { @@ -52,13 +60,13 @@ this.ServerInstance = class ServerInstance { return console.error(err); } } - } + }; - stop() { + ServerInstance.prototype.stop = function() { return clearInterval(this.interval); - } + }; - timer() { + ServerInstance.prototype.timer = function() { var t; t = Date.now() - this.start_time; if (t > this.time + 100) { @@ -70,35 +78,43 @@ this.ServerInstance = class ServerInstance { name: "mp_update" }); } - } + }; - clientConnection(clientsession) { - clientsession.disconnected = () => { - if (clientsession.client_id != null) { - return delete this.connected_clients[clientsession.client_id]; - } - }; + ServerInstance.prototype.clientConnection = function(clientsession) { + clientsession.disconnected = (function(_this) { + return function() { + if (clientsession.client_id != null) { + return delete _this.connected_clients[clientsession.client_id]; + } + }; + })(this); clientsession.client_id = this.client_id++; this.connected_clients[clientsession.client_id] = clientsession; - clientsession.register("mp_client_message", (msg) => { - return this.session.send({ - name: "mp_client_message", - client_id: clientsession.client_id, - data: msg.data - }); - }); - clientsession.disconnected = () => { - return this.session.send({ - name: "mp_client_disconnected", - client_id: clientsession.client_id - }); - }; + clientsession.register("mp_client_message", (function(_this) { + return function(msg) { + return _this.session.send({ + name: "mp_client_message", + client_id: clientsession.client_id, + data: msg.data + }); + }; + })(this)); + clientsession.disconnected = (function(_this) { + return function() { + return _this.session.send({ + name: "mp_client_disconnected", + client_id: clientsession.client_id + }); + }; + })(this); return this.session.send({ name: "mp_client_connection", client_id: clientsession.client_id }); - } + }; + + return ServerInstance; -}; +})(); module.exports = this.ServerInstance; diff --git a/server/server.js b/server/server.js index 7d279cce..20781852 100644 --- a/server/server.js +++ b/server/server.js @@ -1,4 +1,5 @@ -var BuildManager, Content, DB, FileStorage, RateLimiter, Session, WebApp, WebSocket, compression, cookieParser, express, fs, path, process; +var BuildManager, Content, DB, FileStorage, RateLimiter, Session, WebApp, WebSocket, compression, cookieParser, express, fs, path, process, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; compression = require("compression"); @@ -28,19 +29,19 @@ WebSocket = require("ws"); process = require("process"); -this.Server = class Server { - constructor(config = {}, callback1) { - this.exit = this.exit.bind(this); - this.config = config; +this.Server = (function() { + function Server(config, callback1) { + this.config = config != null ? config : {}; this.callback = callback1; + this.exit = bind(this.exit, this); process.chdir(__dirname); this.app_data = this.config.app_data || ".."; - this.mailer = { // STUB + this.mailer = { sendMail: function(recipient, subject, text) { - return console.info(`send mail to:${recipient} subject:${subject} text:${text}`); + return console.info("send mail to:" + recipient + " subject:" + subject + " text:" + text); } }; - this.stats = { // STUB + this.stats = { set: function(name, value) {}, max: function(name, value) {}, unique: function(name, id) {}, @@ -57,37 +58,41 @@ this.Server = class Server { this.PORT = this.config.port || 8080; this.PROD = false; } - this.loadPlugins(() => { - return this.create(); - }); + this.loadPlugins((function(_this) { + return function() { + return _this.create(); + }; + })(this)); } - create() { + Server.prototype.create = function() { var app, folder, i, len, plugin, ref, static_files; app = express(); static_files = "../static"; this.date_started = Date.now(); this.rate_limiter = new RateLimiter(this); - app.use((req, res, next) => { - var referrer; - if (this.rate_limiter.accept("request", "general") && this.rate_limiter.accept("request_ip", req.connection.remoteAddress)) { - next(); - } else { - res.status(500).send(""); - } - this.stats.inc("http_requests"); - this.stats.unique("ip_addresses", req.connection.remoteAddress); - referrer = req.get("Referrer"); - if ((referrer != null) && !referrer.startsWith("http://localhost") && !referrer.startsWith("https://microstudio.io") && !referrer.startsWith("https://microstudio.dev")) { - if (referrer.includes("=")) { - referrer = referrer.substring(0, referrer.indexOf("=")); + app.use((function(_this) { + return function(req, res, next) { + var referrer; + if (_this.rate_limiter.accept("request", "general") && _this.rate_limiter.accept("request_ip", req.connection.remoteAddress)) { + next(); + } else { + res.status(500).send(""); } - if (referrer.length > 120) { - referrer = referrer.substring(0, 120); + _this.stats.inc("http_requests"); + _this.stats.unique("ip_addresses", req.connection.remoteAddress); + referrer = req.get("Referrer"); + if ((referrer != null) && !referrer.startsWith("http://localhost") && !referrer.startsWith("https://microstudio.io") && !referrer.startsWith("https://microstudio.dev")) { + if (referrer.includes("=")) { + referrer = referrer.substring(0, referrer.indexOf("=")); + } + if (referrer.length > 120) { + referrer = referrer.substring(0, 120); + } + return _this.stats.unique("referrer|" + referrer, req.connection.remoteAddress); } - return this.stats.unique("referrer|" + referrer, req.connection.remoteAddress); - } - }); + }; + })(this)); app.use(compression()); app.use(cookieParser()); ref = this.plugins; @@ -95,71 +100,73 @@ this.Server = class Server { plugin = ref[i]; if (plugin.getStaticFolder != null) { folder = plugin.getStaticFolder(); - app.use(express.static(folder)); + app.use(express["static"](folder)); } } - app.use(express.static(static_files)); - app.use("/microstudio.wiki", express.static("../microstudio.wiki", { + app.use(express["static"](static_files)); + app.use("/microstudio.wiki", express["static"]("../microstudio.wiki", { dotfiles: "ignore" })); - app.use("/lib/fontlib/ubuntu", express.static("node_modules/@fontsource/ubuntu")); - app.use("/lib/fontlib/ubuntu-mono", express.static("node_modules/@fontsource/ubuntu-mono")); - app.use("/lib/fontlib/source-sans-pro", express.static("node_modules/@fontsource/source-sans-pro")); - app.use("/lib/fontlib/fontawesome", express.static("node_modules/@fortawesome/fontawesome-free")); - app.use("/lib/ace", express.static("node_modules/ace-builds/src-min")); - app.use("/lib/marked/marked.js", express.static("node_modules/marked/marked.min.js")); - app.use("/lib/dompurify/purify.js", express.static("node_modules/dompurify/dist/purify.min.js")); - app.use("/lib/jquery/jquery.js", express.static("node_modules/jquery/dist/jquery.min.js")); - app.use("/lib/jquery-ui", express.static("node_modules/jquery-ui-dist")); + app.use("/lib/fontlib/ubuntu", express["static"]("node_modules/@fontsource/ubuntu")); + app.use("/lib/fontlib/ubuntu-mono", express["static"]("node_modules/@fontsource/ubuntu-mono")); + app.use("/lib/fontlib/source-sans-pro", express["static"]("node_modules/@fontsource/source-sans-pro")); + app.use("/lib/fontlib/fontawesome", express["static"]("node_modules/@fortawesome/fontawesome-free")); + app.use("/lib/ace", express["static"]("node_modules/ace-builds/src-min")); + app.use("/lib/marked/marked.js", express["static"]("node_modules/marked/marked.min.js")); + app.use("/lib/dompurify/purify.js", express["static"]("node_modules/dompurify/dist/purify.min.js")); + app.use("/lib/jquery/jquery.js", express["static"]("node_modules/jquery/dist/jquery.min.js")); + app.use("/lib/jquery-ui", express["static"]("node_modules/jquery-ui-dist")); if (this.config.brython_path) { - app.use("/lib/brython", express.static(this.config.brython_path)); + app.use("/lib/brython", express["static"](this.config.brython_path)); } else { - app.use("/lib/brython", express.static("node_modules/brython")); + app.use("/lib/brython", express["static"]("node_modules/brython")); } - app.use("/lib/fengari", express.static("node_modules/fengari-web/dist")); - app.use("/lib/qrcode", express.static("node_modules/qrcode/build")); - app.use("/lib/wavefile", express.static("node_modules/wavefile/dist")); - app.use("/lib/lamejs/lame.min.js", express.static("node_modules/lamejs/lame.min.js")); - return this.db = new DB(`${this.app_data}/data`, (db) => { - var j, len1, ref1; - ref1 = this.plugins; - for (j = 0, len1 = ref1.length; j < len1; j++) { - plugin = ref1[j]; - if (plugin.dbLoaded != null) { - plugin.dbLoaded(db); - } - } - if (this.PROD) { - return require('greenlock-express').init({ - packageRoot: __dirname, - configDir: "./greenlock.d", - maintainerEmail: "contact@microstudio.dev", - cluster: false - }).ready((glx) => { - this.httpserver = glx.httpsServer(); - this.use_cache = true; - glx.serveApp(app); - return this.start(app, db); - }); - } else if (this.config.standalone) { - this.use_cache = false; - return this.httpserver = require("http").createServer(app).listen(this.PORT, "127.0.0.1", () => { - this.PORT = this.httpserver.address().port; - this.start(app, db); - console.info(`standalone running on port ${this.PORT}`); - if (this.callback != null) { - return this.callback(); + app.use("/lib/fengari", express["static"]("node_modules/fengari-web/dist")); + app.use("/lib/qrcode", express["static"]("node_modules/qrcode/build")); + app.use("/lib/wavefile", express["static"]("node_modules/wavefile/dist")); + app.use("/lib/lamejs/lame.min.js", express["static"]("node_modules/lamejs/lame.min.js")); + return this.db = new DB(this.app_data + "/data", (function(_this) { + return function(db) { + var j, len1, ref1; + ref1 = _this.plugins; + for (j = 0, len1 = ref1.length; j < len1; j++) { + plugin = ref1[j]; + if (plugin.dbLoaded != null) { + plugin.dbLoaded(db); } - }); - } else { - this.httpserver = require("http").createServer(app).listen(this.PORT); - this.use_cache = false; - return this.start(app, db); - } - }); - } + } + if (_this.PROD) { + return require('greenlock-express').init({ + packageRoot: __dirname, + configDir: "./greenlock.d", + maintainerEmail: "contact@microstudio.dev", + cluster: false + }).ready(function(glx) { + _this.httpserver = glx.httpsServer(); + _this.use_cache = true; + glx.serveApp(app); + return _this.start(app, db); + }); + } else if (_this.config.standalone) { + _this.use_cache = false; + return _this.httpserver = require("http").createServer(app).listen(_this.PORT, "127.0.0.1", function() { + _this.PORT = _this.httpserver.address().port; + _this.start(app, db); + console.info("standalone running on port " + _this.PORT); + if (_this.callback != null) { + return _this.callback(); + } + }); + } else { + _this.httpserver = require("http").createServer(app).listen(_this.PORT); + _this.use_cache = false; + return _this.start(app, db); + } + }; + })(this)); + }; - start(app, db) { + Server.prototype.start = function(app, db) { var i, l, len, ref; this.active_users = 0; this.io = new WebSocket.Server({ @@ -167,16 +174,20 @@ this.Server = class Server { maxPayload: 40000000 }); this.sessions = []; - this.io.on("connection", (socket, request) => { - socket.request = request; - socket.remoteAddress = request.connection.remoteAddress; - return this.sessions.push(new Session(this, socket)); - }); + this.io.on("connection", (function(_this) { + return function(socket, request) { + socket.request = request; + socket.remoteAddress = request.connection.remoteAddress; + return _this.sessions.push(new Session(_this, socket)); + }; + })(this)); console.info("MAX PAYLOAD = " + this.io.options.maxPayload); - this.session_check = setInterval((() => { - return this.sessionCheck(); - }), 10000); - this.content = new Content(this, db, new FileStorage(`${this.app_data}/files`)); + this.session_check = setInterval(((function(_this) { + return function() { + return _this.sessionCheck(); + }; + })(this)), 10000); + this.content = new Content(this, db, new FileStorage(this.app_data + "/files")); this.build_manager = new BuildManager(this); this.webapp = new WebApp(this, app); ref = this.webapp.languages; @@ -184,30 +195,33 @@ this.Server = class Server { l = ref[i]; this.content.translator.createLanguage(l); } - process.on('SIGINT', () => { - console.log("caught INT signal"); - return this.exit(); - }); - process.on('SIGTERM', () => { - console.log("caught TERM signal"); - return this.exit(); - }); - //process.on 'SIGKILL', ()=> - // console.log "caught KILL signal" - // @exit() - return this.exitcheck = setInterval((() => { - if (fs.existsSync("exit")) { - this.exit(); - fs.unlinkSync("exit"); - } - if (fs.existsSync("update")) { - this.webapp.concatenator.refresh(); - return fs.unlinkSync("update"); - } - }), 2000); - } + process.on('SIGINT', (function(_this) { + return function() { + console.log("caught INT signal"); + return _this.exit(); + }; + })(this)); + process.on('SIGTERM', (function(_this) { + return function() { + console.log("caught TERM signal"); + return _this.exit(); + }; + })(this)); + return this.exitcheck = setInterval(((function(_this) { + return function() { + if (fs.existsSync("exit")) { + _this.exit(); + fs.unlinkSync("exit"); + } + if (fs.existsSync("update")) { + _this.webapp.concatenator.refresh(); + return fs.unlinkSync("update"); + } + }; + })(this)), 2000); + }; - exit() { + Server.prototype.exit = function() { if (this.exited) { process.exit(0); } @@ -220,12 +234,14 @@ this.Server = class Server { clearInterval(this.exitcheck); clearInterval(this.session_check); this.exited = true; - return setTimeout((() => { - return this.exit(); - }), 5000); - } + return setTimeout(((function(_this) { + return function() { + return _this.exit(); + }; + })(this)), 5000); + }; - sessionCheck() { + Server.prototype.sessionCheck = function() { var i, len, ref, s; ref = this.sessions; for (i = 0, len = ref.length; i < len; i++) { @@ -234,55 +250,59 @@ this.Server = class Server { s.timeCheck(); } } - } + }; - sessionClosed(session) { + Server.prototype.sessionClosed = function(session) { var index; index = this.sessions.indexOf(session); if (index >= 0) { return this.sessions.splice(index, 1); } - } + }; - loadPlugins(callback) { + Server.prototype.loadPlugins = function(callback) { this.plugins = []; - return fs.readdir("../plugins", (err, files) => { - var funk; - if (files == null) { - files = []; - } - funk = () => { - var f; - if (files.length === 0) { - return callback(); - } else { - f = files.splice(0, 1)[0]; - return this.loadPlugin(`../plugins/${f}`, funk); + return fs.readdir("../plugins", (function(_this) { + return function(err, files) { + var funk; + if (files == null) { + files = []; } + funk = function() { + var f; + if (files.length === 0) { + return callback(); + } else { + f = files.splice(0, 1)[0]; + return _this.loadPlugin("../plugins/" + f, funk); + } + }; + return funk(); }; - return funk(); - }); - } + })(this)); + }; - loadPlugin(folder, callback) { + Server.prototype.loadPlugin = function(folder, callback) { var Plugin, err, p; - if (fs.existsSync(`${folder}/index.js`)) { + if (fs.existsSync(folder + "/index.js")) { try { - Plugin = require(`${folder}/index.js`); + Plugin = require(folder + "/index.js"); p = new Plugin(this); this.plugins.push(p); - console.info(`loaded plugin ${folder}`); + console.info("loaded plugin " + folder); } catch (error) { err = error; console.error(err); } return callback(); } else { - console.info(`plugin ${folder} has no index.js`); + console.info("plugin " + folder + " has no index.js"); return callback(); } - } + }; + + return Server; -}; +})(); module.exports = this.Server; diff --git a/server/session/projectmanager.js b/server/session/projectmanager.js index b05dd75a..26bc7dc5 100644 --- a/server/session/projectmanager.js +++ b/server/session/projectmanager.js @@ -1,11 +1,12 @@ -var FILE_TYPES; +var FILE_TYPES, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; FILE_TYPES = require(__dirname + "/../file_types.js"); -this.ProjectManager = class ProjectManager { - constructor(project1) { - this.importFiles = this.importFiles.bind(this); +this.ProjectManager = (function() { + function ProjectManager(project1) { this.project = project1; + this.importFiles = bind(this.importFiles, this); this.users = []; this.listeners = []; this.files = {}; @@ -13,9 +14,9 @@ this.ProjectManager = class ProjectManager { this.project.manager = this; } - canRead(user) { + ProjectManager.prototype.canRead = function(user) { var i, len, link, ref; - if (user === this.project.owner || this.project.public) { + if (user === this.project.owner || this.project["public"]) { return true; } ref = this.project.users; @@ -26,11 +27,11 @@ this.ProjectManager = class ProjectManager { } } return false; - } + }; - canReadProject(user, project) { + ProjectManager.prototype.canReadProject = function(user, project) { var i, len, link, ref; - if (user === project.owner || project.public) { + if (user === project.owner || project["public"]) { return true; } ref = project.users; @@ -41,9 +42,9 @@ this.ProjectManager = class ProjectManager { } } return false; - } + }; - canWrite(user) { + ProjectManager.prototype.canWrite = function(user) { var i, len, link, ref; if (user === this.project.owner) { return true; @@ -56,26 +57,26 @@ this.ProjectManager = class ProjectManager { } } return false; - } + }; - canWriteOptions(user) { + ProjectManager.prototype.canWriteOptions = function(user) { return this.project.owner === user; - } + }; - addUser(user) { + ProjectManager.prototype.addUser = function(user) { if (this.users.indexOf(user) < 0) { this.users.push(user); } return this.sendCurrentLocks(user); - } + }; - addListener(listener) { + ProjectManager.prototype.addListener = function(listener) { if (this.listeners.indexOf(listener) < 0) { return this.listeners.push(listener); } - } + }; - removeSession(session) { + ProjectManager.prototype.removeSession = function(session) { var file, index, lock, ref; index = this.users.indexOf(session); if (index >= 0) { @@ -88,17 +89,17 @@ this.ProjectManager = class ProjectManager { lock.time = 0; } } - } + }; - removeListener(listener) { + ProjectManager.prototype.removeListener = function(listener) { var index; index = this.listeners.indexOf(listener); if (index >= 0) { return this.listeners.splice(index, 1); } - } + }; - lockFile(user, file) { + ProjectManager.prototype.lockFile = function(user, file) { var lock; lock = this.locks[file]; if (lock != null) { @@ -119,14 +120,14 @@ this.ProjectManager = class ProjectManager { this.propagateLock(user, file); return true; } - } + }; - sendCurrentLocks(user) { + ProjectManager.prototype.sendCurrentLocks = function(user) { var file, lock, ref; ref = this.locks; for (file in ref) { lock = ref[file]; - if (Date.now() < lock.time) { //and lock.user.user != user.user + if (Date.now() < lock.time) { user.send({ name: "project_file_locked", project: this.project.id, @@ -135,9 +136,9 @@ this.ProjectManager = class ProjectManager { }); } } - } + }; - canWrite(user, file) { + ProjectManager.prototype.canWrite = function(user, file) { var lock; lock = this.locks[file]; if (lock != null) { @@ -145,9 +146,9 @@ this.ProjectManager = class ProjectManager { } else { return true; } - } + }; - getFileVersion(file) { + ProjectManager.prototype.getFileVersion = function(file) { var info; info = this.project.getFileInfo(file); if (info.version != null) { @@ -155,13 +156,13 @@ this.ProjectManager = class ProjectManager { } else { return 0; } - } + }; - setFileVersion(file, version) { + ProjectManager.prototype.setFileVersion = function(file, version) { return this.project.setFileInfo(file, "version", version); - } + }; - getFileSize(file) { + ProjectManager.prototype.getFileSize = function(file) { var info; info = this.project.getFileInfo(file); if (info.size != null) { @@ -169,13 +170,13 @@ this.ProjectManager = class ProjectManager { } else { return 0; } - } + }; - setFileSize(file, size) { + ProjectManager.prototype.setFileSize = function(file, size) { return this.project.setFileInfo(file, "size", size); - } + }; - getFileProperties(file) { + ProjectManager.prototype.getFileProperties = function(file) { var info; info = this.project.getFileInfo(file); if (info.properties != null) { @@ -183,13 +184,13 @@ this.ProjectManager = class ProjectManager { } else { return {}; } - } + }; - setFileProperties(file, properties) { + ProjectManager.prototype.setFileProperties = function(file, properties) { return this.project.setFileInfo(file, "properties", properties); - } + }; - propagateUserListChange() { + ProjectManager.prototype.propagateUserListChange = function() { var i, len, ref, user; ref = this.users; for (i = 0, len = ref.length; i < len; i++) { @@ -202,9 +203,9 @@ this.ProjectManager = class ProjectManager { }); } } - } + }; - propagateLock(user, file) { + ProjectManager.prototype.propagateLock = function(user, file) { var i, len, ref, u; ref = this.users; for (i = 0, len = ref.length; i < len; i++) { @@ -218,9 +219,9 @@ this.ProjectManager = class ProjectManager { }); } } - } + }; - propagateFileChange(author, file, version, content, properties) { + ProjectManager.prototype.propagateFileChange = function(author, file, version, content, properties) { var i, j, len, len1, listener, ref, ref1, user; ref = this.users; for (i = 0, len = ref.length; i < len; i++) { @@ -243,9 +244,9 @@ this.ProjectManager = class ProjectManager { listener.sendProjectFileUpdated(file.split("/")[0], file.split("/")[1].split(".")[0], version, content, properties); } } - } + }; - propagateFileDeleted(author, file) { + ProjectManager.prototype.propagateFileDeleted = function(author, file) { var i, j, len, len1, listener, ref, ref1, user; ref = this.users; for (i = 0, len = ref.length; i < len; i++) { @@ -265,9 +266,9 @@ this.ProjectManager = class ProjectManager { listener.sendProjectFileDeleted(file.split("/")[0], file.split("/")[1]); } } - } + }; - propagateOptions(author) { + ProjectManager.prototype.propagateOptions = function(author) { var i, j, len, len1, listener, ref, ref1, user; ref = this.users; for (i = 0, len = ref.length; i < len; i++) { @@ -282,7 +283,7 @@ this.ProjectManager = class ProjectManager { controls: this.project.controls, orientation: this.project.orientation, aspect: this.project.aspect, - public: this.project.public + "public": this.project["public"] }); } } @@ -298,13 +299,13 @@ this.ProjectManager = class ProjectManager { controls: this.project.controls, orientation: this.project.orientation, aspect: this.project.aspect, - public: this.project.public + "public": this.project["public"] }); } } - } + }; - inviteUser(source, user) { + ProjectManager.prototype.inviteUser = function(source, user) { var i, len, li, ref; if (source.user === this.project.owner) { this.project.inviteUser(user); @@ -315,9 +316,9 @@ this.ProjectManager = class ProjectManager { li.getProjectList(); } } - } + }; - acceptInvite(user) { + ProjectManager.prototype.acceptInvite = function(user) { var i, j, len, len1, li, link, ref, ref1; ref = this.project.users; for (i = 0, len = ref.length; i < len; i++) { @@ -332,9 +333,9 @@ this.ProjectManager = class ProjectManager { } } } - } + }; - removeUser(source, user) { + ProjectManager.prototype.removeUser = function(source, user) { var i, j, len, len1, li, link, ref, ref1; if (source.user === this.project.owner || source.user === user) { ref = this.project.users; @@ -351,31 +352,33 @@ this.ProjectManager = class ProjectManager { } } } - } + }; - listFiles(folder, callback) { + ProjectManager.prototype.listFiles = function(folder, callback) { var file; - file = `${this.project.owner.id}/${this.project.id}/${folder}`; - return this.project.content.files.list(file, (files) => { - var f, i, len, res; - res = []; - files = files || []; - for (i = 0, len = files.length; i < len; i++) { - f = files[i]; - if (!f.startsWith(".")) { - res.push({ - file: f, - version: this.getFileVersion(folder + "/" + f), - size: this.getFileSize(folder + "/" + f), - properties: this.getFileProperties(folder + "/" + f) - }); + file = this.project.owner.id + "/" + this.project.id + "/" + folder; + return this.project.content.files.list(file, (function(_this) { + return function(files) { + var f, i, len, res; + res = []; + files = files || []; + for (i = 0, len = files.length; i < len; i++) { + f = files[i]; + if (!f.startsWith(".")) { + res.push({ + file: f, + version: _this.getFileVersion(folder + "/" + f), + size: _this.getFileSize(folder + "/" + f), + properties: _this.getFileProperties(folder + "/" + f) + }); + } } - } - return callback(res); - }); - } + return callback(res); + }; + })(this)); + }; - getFileVersions(callback) { + ProjectManager.prototype.getFileVersions = function(callback) { var folder, funk, jobs, res, t; res = {}; jobs = []; @@ -384,82 +387,87 @@ this.ProjectManager = class ProjectManager { res[t.property] = {}; jobs.push(t); } - funk = () => { - var job; - if (jobs.length > 0) { - job = jobs.splice(0, 1)[0]; - return this.listFiles(job.folder, (files) => { - var ext, f, i, len, name; - for (i = 0, len = files.length; i < len; i++) { - f = files[i]; - name = f.file.split(".")[0]; - ext = f.file.split(".")[1]; - res[job.property][name] = { - version: f.version, - properties: f.properties, - ext: ext - }; - } - return funk(); - }); - } else { - return callback(res); - } - }; + funk = (function(_this) { + return function() { + var job; + if (jobs.length > 0) { + job = jobs.splice(0, 1)[0]; + return _this.listFiles(job.folder, function(files) { + var ext, f, i, len, name; + for (i = 0, len = files.length; i < len; i++) { + f = files[i]; + name = f.file.split(".")[0]; + ext = f.file.split(".")[1]; + res[job.property][name] = { + version: f.version, + properties: f.properties, + ext: ext + }; + } + return funk(); + }); + } else { + return callback(res); + } + }; + })(this); return funk(); - } + }; - listProjectFiles(session, data) { + ProjectManager.prototype.listProjectFiles = function(session, data) { var file; if (!this.canRead(session.user)) { return console.log("unauthorized user"); } - file = `${this.project.owner.id}/${this.project.id}/${data.folder}`; - return this.project.content.files.list(file, (files) => { - var f, i, len, res; - res = []; - files = files || []; - for (i = 0, len = files.length; i < len; i++) { - f = files[i]; - if (!f.startsWith(".")) { - res.push({ - file: f, - version: this.getFileVersion(data.folder + "/" + f), - size: this.getFileSize(data.folder + "/" + f), - properties: this.getFileProperties(data.folder + "/" + f) - }); + file = this.project.owner.id + "/" + this.project.id + "/" + data.folder; + return this.project.content.files.list(file, (function(_this) { + return function(files) { + var f, i, len, res; + res = []; + files = files || []; + for (i = 0, len = files.length; i < len; i++) { + f = files[i]; + if (!f.startsWith(".")) { + res.push({ + file: f, + version: _this.getFileVersion(data.folder + "/" + f), + size: _this.getFileSize(data.folder + "/" + f), + properties: _this.getFileProperties(data.folder + "/" + f) + }); + } } - } - return session.send({ - name: "list_project_files", - files: res, - request_id: data.request_id - }); - }); - } + return session.send({ + name: "list_project_files", + files: res, + request_id: data.request_id + }); + }; + })(this)); + }; - readProjectFile(session, data) { + ProjectManager.prototype.readProjectFile = function(session, data) { var encoding, file; - //console.info "projectmanager.readProjectFile" if (!this.canRead(session.user)) { return; } - file = `${this.project.owner.id}/${this.project.id}/${data.file}`; + file = this.project.owner.id + "/" + this.project.id + "/" + data.file; encoding = data.file.endsWith(".ms") || data.file.endsWith(".json") || data.file.endsWith(".md") ? "text" : "base64"; - return this.project.content.files.read(file, encoding, (content) => { - var out; - out = data.file.endsWith(".ms") || data.file.endsWith(".json") || data.file.endsWith(".md") ? "utf8" : "base64"; - if (content != null) { - return session.send({ - name: "read_project_file", - content: content.toString(out), - request_id: data.request_id - }); - } - }); - } + return this.project.content.files.read(file, encoding, (function(_this) { + return function(content) { + var out; + out = data.file.endsWith(".ms") || data.file.endsWith(".json") || data.file.endsWith(".md") ? "utf8" : "base64"; + if (content != null) { + return session.send({ + name: "read_project_file", + content: content.toString(out), + request_id: data.request_id + }); + } + }; + })(this)); + }; - writeProjectFile(session, data) { + ProjectManager.prototype.writeProjectFile = function(session, data) { var content, f, file, ref, remaining, th, version; if (!this.canWrite(session.user)) { return; @@ -473,11 +481,11 @@ this.ProjectManager = class ProjectManager { if (data.content == null) { return; } - if (data.content.length > 40000000) { // absolute max file size 30 megabytes + if (data.content.length > 40000000) { session.showError("File too large."); return; } - if (data.content.length > 1000000) { // large file, check allowed storage + if (data.content.length > 1000000) { remaining = session.user.max_storage - session.user.getTotalSize(); if (data.content.length / 4 * 3 >= remaining) { if (session.user.flags.guest) { @@ -490,46 +498,48 @@ this.ProjectManager = class ProjectManager { name: "write_project_file", size: data.content.length, request_id: data.request_id - }); // response to trigger the asset list update + }); } return; } } if (!/^(ms|sprites|maps|sounds|music|doc|assets)\/[a-z0-9_]{1,40}(-[a-z0-9_]{1,40}){0,10}.(ms|png|json|wav|mp3|ogg|flac|md|glb|obj|jpg|ttf|txt|csv)$/.test(data.file)) { - console.info(`wrong file name: ${data.file}`); + console.info("wrong file name: " + data.file); return; } version = this.getFileVersion(data.file); - if (version === 0) { // new file + if (version === 0) { if (!session.server.rate_limiter.accept("create_file_user", session.user.id)) { return; } } - file = `${this.project.owner.id}/${this.project.id}/${data.file}`; + file = this.project.owner.id + "/" + this.project.id + "/" + data.file; if (data.content != null) { if ((ref = data.file.split(".")[1]) === "ms" || ref === "json" || ref === "md" || ref === "txt" || ref === "csv") { content = data.content; } else { content = new Buffer(data.content, "base64"); } - this.project.content.files.write(file, content, () => { - version += 1; - this.setFileVersion(data.file, version); - this.setFileSize(data.file, content.length); - if (data.properties != null) { - this.setFileProperties(data.file, data.properties); - } - if (data.request_id != null) { - session.send({ - name: "write_project_file", - version: version, - size: content.length, - request_id: data.request_id - }); - } - this.propagateFileChange(session, data.file, version, data.content, data.properties); - return this.project.touch(); - }); + this.project.content.files.write(file, content, (function(_this) { + return function() { + version += 1; + _this.setFileVersion(data.file, version); + _this.setFileSize(data.file, content.length); + if (data.properties != null) { + _this.setFileProperties(data.file, data.properties); + } + if (data.request_id != null) { + session.send({ + name: "write_project_file", + version: version, + size: content.length, + request_id: data.request_id + }); + } + _this.propagateFileChange(session, data.file, version, data.content, data.properties); + return _this.project.touch(); + }; + })(this)); } if (data.thumbnail != null) { th = new Buffer(data.thumbnail, "base64"); @@ -537,13 +547,15 @@ this.ProjectManager = class ProjectManager { f[2] += "_th"; f[3] = f[3].split(".")[0] + ".png"; f = f.join("/"); - return this.project.content.files.write(f, th, () => { - return console.info("thumbnail saved"); - }); + return this.project.content.files.write(f, th, (function(_this) { + return function() { + return console.info("thumbnail saved"); + }; + })(this)); } - } + }; - renameProjectFile(session, data) { + ProjectManager.prototype.renameProjectFile = function(session, data) { var dest, source; if (!this.canWrite(session.user)) { return; @@ -558,62 +570,64 @@ this.ProjectManager = class ProjectManager { return; } if (!/^(ms|sprites|maps|sounds|music|doc|assets)\/[a-z0-9_]{1,40}(-[a-z0-9_]{1,40}){0,10}.(ms|png|json|wav|mp3|ogg|flac|md|glb|obj|jpg|ttf|txt|csv)$/.test(data.source)) { - console.info(`wrong source name: ${data.source}`); + console.info("wrong source name: " + data.source); return; } if (!/^(ms|sprites|maps|sounds|music|doc|assets)\/[a-z0-9_]{1,40}(-[a-z0-9_]{1,40}){0,10}.(ms|png|json|wav|mp3|ogg|flac|md|glb|obj|jpg|ttf|txt|csv)$/.test(data.dest)) { - console.info(`wrong dest name: ${data.dest}`); + console.info("wrong dest name: " + data.dest); return; } - source = `${this.project.owner.id}/${this.project.id}/${data.source}`; - dest = `${this.project.owner.id}/${this.project.id}/${data.dest}`; - return this.project.content.files.read(source, "binary", (content) => { - if (content != null) { - return this.project.content.files.write(dest, content, () => { - this.setFileProperties(data.dest, this.getFileProperties(data.source)); - this.setFileVersion(data.dest, this.getFileVersion(data.source)); - this.project.deleteFileInfo(data.source); - this.setFileSize(data.dest, content.length); - this.project.touch(); - return this.project.content.files.delete(source, () => { - if (data.thumbnail) { - source = source.split("/"); - source[2] += "_th"; - source[3] = source[3].split(".")[0] + ".png"; - source = source.join("/"); - dest = dest.split("/"); - dest[2] += "_th"; - dest[3] = dest[3].split(".")[0] + ".png"; - dest = dest.join("/"); - return this.project.content.files.read(source, "binary", (thumbnail) => { - if (thumbnail != null) { - return this.project.content.files.write(dest, thumbnail, () => { - return this.project.content.files.delete(source, () => { - session.send({ - name: "rename_project_file", - request_id: data.request_id + source = this.project.owner.id + "/" + this.project.id + "/" + data.source; + dest = this.project.owner.id + "/" + this.project.id + "/" + data.dest; + return this.project.content.files.read(source, "binary", (function(_this) { + return function(content) { + if (content != null) { + return _this.project.content.files.write(dest, content, function() { + _this.setFileProperties(data.dest, _this.getFileProperties(data.source)); + _this.setFileVersion(data.dest, _this.getFileVersion(data.source)); + _this.project.deleteFileInfo(data.source); + _this.setFileSize(data.dest, content.length); + _this.project.touch(); + return _this.project.content.files["delete"](source, function() { + if (data.thumbnail) { + source = source.split("/"); + source[2] += "_th"; + source[3] = source[3].split(".")[0] + ".png"; + source = source.join("/"); + dest = dest.split("/"); + dest[2] += "_th"; + dest[3] = dest[3].split(".")[0] + ".png"; + dest = dest.join("/"); + return _this.project.content.files.read(source, "binary", function(thumbnail) { + if (thumbnail != null) { + return _this.project.content.files.write(dest, thumbnail, function() { + return _this.project.content.files["delete"](source, function() { + session.send({ + name: "rename_project_file", + request_id: data.request_id + }); + _this.propagateFileDeleted(session, data.source); + return _this.propagateFileChange(session, data.dest, 0, null, {}); }); - this.propagateFileDeleted(session, data.source); - return this.propagateFileChange(session, data.dest, 0, null, {}); }); - }); - } - }); - } else { - session.send({ - name: "rename_project_file", - request_id: data.request_id - }); - this.propagateFileDeleted(session, data.source); - return this.propagateFileChange(session, data.dest, 0, null, {}); - } + } + }); + } else { + session.send({ + name: "rename_project_file", + request_id: data.request_id + }); + _this.propagateFileDeleted(session, data.source); + return _this.propagateFileChange(session, data.dest, 0, null, {}); + } + }); }); - }); - } - }); - } + } + }; + })(this)); + }; - deleteProjectFile(session, data) { + ProjectManager.prototype.deleteProjectFile = function(session, data) { var f, file; if (!this.canWrite(session.user)) { return; @@ -621,83 +635,89 @@ this.ProjectManager = class ProjectManager { if (data.file == null) { return; } - file = `${this.project.owner.id}/${this.project.id}/${data.file}`; - this.project.content.files.delete(file, () => { - this.project.deleteFileInfo(data.file); - if (data.request_id != null) { - session.send({ - name: "delete_project_file", - request_id: data.request_id - }); - } - this.propagateFileDeleted(session, data.file); - return this.project.touch(); - }); + file = this.project.owner.id + "/" + this.project.id + "/" + data.file; + this.project.content.files["delete"](file, (function(_this) { + return function() { + _this.project.deleteFileInfo(data.file); + if (data.request_id != null) { + session.send({ + name: "delete_project_file", + request_id: data.request_id + }); + } + _this.propagateFileDeleted(session, data.file); + return _this.project.touch(); + }; + })(this)); if (data.thumbnail) { f = file.split("/"); f[2] += "_th"; f[3] = f[3].split(".")[0] + ".png"; f = f.join("/"); - return this.project.content.files.delete(f, () => {}); + return this.project.content.files["delete"](f, (function(_this) { + return function() {}; + })(this)); } - } + }; - importFiles(contents, callback) { + ProjectManager.prototype.importFiles = function(contents, callback) { var filename, files, funk; files = []; for (filename in contents.files) { files.push(filename); } - funk = () => { - var d, dest, end, err, ref, type, value; - if (files.length > 0) { - filename = files.splice(0, 1)[0]; - value = contents.files[filename]; - if (/^(ms|sprites|maps|sounds|music|doc|assets|sounds_th|music_th|assets_th)\/[a-z0-9_]{1,40}([-\/][a-z0-9_]{1,40}){0,10}.(ms|py|js|lua|png|json|wav|mp3|ogg|flac|md|glb|obj|jpg|ttf|txt|csv)$/.test(filename)) { - dest = filename; - d = dest.split("/"); - while (d.length > 2) { - end = d.splice(d.length - 1, 1)[0]; - d[d.length - 1] += `-${end}`; - dest = d.join("/"); - } - if (dest.endsWith(".js")) { - dest = dest.replace(".js", ".ms"); - } - if (dest.endsWith(".py")) { - dest = dest.replace(".py", ".ms"); - } - if (dest.endsWith(".lua")) { - dest = dest.replace(".lua", ".ms"); - } - type = (ref = dest.split(".")[1]) === "ms" || ref === "json" || ref === "md" || ref === "txt" || ref === "csv" ? "string" : "nodebuffer"; - try { - return contents.file(filename).async(type).then(((fileContent) => { - if (fileContent != null) { - return this.project.content.files.write(`${this.project.owner.id}/${this.project.id}/${dest}`, fileContent, funk); - } else { + funk = (function(_this) { + return function() { + var d, dest, end, err, ref, type, value; + if (files.length > 0) { + filename = files.splice(0, 1)[0]; + value = contents.files[filename]; + if (/^(ms|sprites|maps|sounds|music|doc|assets|sounds_th|music_th|assets_th)\/[a-z0-9_]{1,40}([-\/][a-z0-9_]{1,40}){0,10}.(ms|py|js|lua|png|json|wav|mp3|ogg|flac|md|glb|obj|jpg|ttf|txt|csv)$/.test(filename)) { + dest = filename; + d = dest.split("/"); + while (d.length > 2) { + end = d.splice(d.length - 1, 1)[0]; + d[d.length - 1] += "-" + end; + dest = d.join("/"); + } + if (dest.endsWith(".js")) { + dest = dest.replace(".js", ".ms"); + } + if (dest.endsWith(".py")) { + dest = dest.replace(".py", ".ms"); + } + if (dest.endsWith(".lua")) { + dest = dest.replace(".lua", ".ms"); + } + type = (ref = dest.split(".")[1]) === "ms" || ref === "json" || ref === "md" || ref === "txt" || ref === "csv" ? "string" : "nodebuffer"; + try { + return contents.file(filename).async(type).then((function(fileContent) { + if (fileContent != null) { + return _this.project.content.files.write(_this.project.owner.id + "/" + _this.project.id + "/" + dest, fileContent, funk); + } else { + return funk(); + } + }), function() { return funk(); - } - }), () => { + }); + } catch (error) { + err = error; + console.error(err); + console.log(filename); return funk(); - }); - } catch (error) { - err = error; - console.error(err); - console.log(filename); + } + } else { return funk(); } } else { - return funk(); + return callback(); } - } else { - return callback(); - } - }; + }; + })(this); return funk(); - } + }; - syncFiles(session, data, source) { + ProjectManager.prototype.syncFiles = function(session, data, source) { var funk, ops, syncFile; ops = data.ops; if (!this.canWrite(session.user)) { @@ -706,77 +726,83 @@ this.ProjectManager = class ProjectManager { if (!Array.isArray(ops)) { return; } - syncFile = (f, callback) => { - var file; - file = `${source.owner.id}/${source.id}/${f}`; - return source.content.files.read(file, "binary", (content) => { - var th; - if (content != null) { - file = `${this.project.owner.id}/${this.project.id}/${f}`; - this.project.content.files.write(file, content, () => { + syncFile = (function(_this) { + return function(f, callback) { + var file; + file = source.owner.id + "/" + source.id + "/" + f; + return source.content.files.read(file, "binary", function(content) { + var th; + if (content != null) { + file = _this.project.owner.id + "/" + _this.project.id + "/" + f; + _this.project.content.files.write(file, content, function() { + if (callback != null) { + return callback(); + } + }); + if (f.startsWith("assets/") || f.startsWith("sounds/") || f.startsWith("music/")) { + th = f.split("/"); + th[0] += "_th"; + th[1] = th[1].split(".")[0] + ".png"; + f = th.join("/"); + file = source.owner.id + "/" + source.id + "/" + f; + return source.content.files.read(file, "binary", function(content) { + if (content != null) { + file = _this.project.owner.id + "/" + _this.project.id + "/" + f; + return _this.project.content.files.write(file, content, function() {}); + } + }); + } + } else { if (callback != null) { return callback(); } - }); - if (f.startsWith("assets/") || f.startsWith("sounds/") || f.startsWith("music/")) { - th = f.split("/"); - th[0] += "_th"; - th[1] = th[1].split(".")[0] + ".png"; - f = th.join("/"); - file = `${source.owner.id}/${source.id}/${f}`; - return source.content.files.read(file, "binary", (content) => { - if (content != null) { - file = `${this.project.owner.id}/${this.project.id}/${f}`; - return this.project.content.files.write(file, content, () => {}); + } + }); + }; + })(this); + funk = (function(_this) { + return function() { + var f, file, op; + if (ops.length > 0) { + op = ops.splice(0, 1)[0]; + if (!((op.file != null) && (op.file.path != null) && (op.file.version != null) && (op.file.size != null))) { + return; + } + if (op.op === "sync") { + f = op.file; + return syncFile(f.path, function() { + _this.setFileVersion(f.path, f.version); + _this.setFileSize(f.path, f.size); + if (f.properties != null) { + _this.setFileProperties(f.path, f.properties); } + funk(); + return _this.propagateFileChange(null, f.path, f.version, void 0, f.properties || {}); + }); + } else if (op.op === "delete") { + f = op.file; + file = _this.project.owner.id + "/" + _this.project.id + "/" + f.path; + return _this.project.content.files["delete"](file, function() { + _this.project.deleteFileInfo(f.path); + funk(); + return _this.propagateFileDeleted(null, f.path); }); } } else { - if (callback != null) { - return callback(); - } - } - }); - }; - funk = () => { - var f, file, op; - if (ops.length > 0) { - op = ops.splice(0, 1)[0]; - if (!((op.file != null) && (op.file.path != null) && (op.file.version != null) && (op.file.size != null))) { - return; - } - if (op.op === "sync") { - f = op.file; - return syncFile(f.path, () => { - this.setFileVersion(f.path, f.version); - this.setFileSize(f.path, f.size); - if (f.properties != null) { - this.setFileProperties(f.path, f.properties); - } - funk(); - return this.propagateFileChange(null, f.path, f.version, void 0, f.properties || {}); - }); - } else if (op.op === "delete") { - f = op.file; - file = `${this.project.owner.id}/${this.project.id}/${f.path}`; - return this.project.content.files.delete(file, () => { - this.project.deleteFileInfo(f.path); - funk(); - return this.propagateFileDeleted(null, f.path); + session.send({ + name: "sync_project_files", + status: "done", + request_id: data.request_id }); + return _this.project.touch(); } - } else { - session.send({ - name: "sync_project_files", - status: "done", - request_id: data.request_id - }); - return this.project.touch(); - } - }; + }; + })(this); return funk(); - } + }; + + return ProjectManager; -}; +})(); module.exports = this.ProjectManager; diff --git a/server/session/session.js b/server/session/session.js index f0ddf6c7..33856e6f 100644 --- a/server/session/session.js +++ b/server/session/session.js @@ -1,4 +1,5 @@ -var ForumSession, JSZip, ProjectManager, RegexLib, RelayService, SHA256; +var ForumSession, JSZip, ProjectManager, RegexLib, RelayService, SHA256, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; SHA256 = require("crypto-js/sha256"); @@ -12,14 +13,13 @@ JSZip = require("jszip"); RelayService = require(__dirname + "/../relay/relayservice.js"); -this.Session = class Session { - constructor(server, socket) { +this.Session = (function() { + function Session(server, socket) { var j, len1, plugin, ref; - this.uploadRequest = this.uploadRequest.bind(this); - this.bufferReceived = this.bufferReceived.bind(this); this.server = server; this.socket = socket; - //console.info "new session" + this.bufferReceived = bind(this.bufferReceived, this); + this.uploadRequest = bind(this.uploadRequest, this); this.content = this.server.content; if (this.content == null) { return this.socket.close(); @@ -29,230 +29,367 @@ this.Session = class Session { this.token = null; this.checkCookie(); this.last_active = Date.now(); - this.socket.on("message", (msg) => { - //console.info "received msg: #{msg}" - this.messageReceived(msg); - return this.last_active = Date.now(); - }); - this.socket.on("close", () => { - this.server.sessionClosed(this); - return this.disconnected(); - }); - this.socket.on("error", (err) => { - if (this.user) { - console.error(`WS ERROR for user ${this.user.id} - ${this.user.nick}`); - } else { - console.error("WS ERROR"); - } - return console.error(err); - }); + this.socket.on("message", (function(_this) { + return function(msg) { + _this.messageReceived(msg); + return _this.last_active = Date.now(); + }; + })(this)); + this.socket.on("close", (function(_this) { + return function() { + _this.server.sessionClosed(_this); + return _this.disconnected(); + }; + })(this)); + this.socket.on("error", (function(_this) { + return function(err) { + if (_this.user) { + console.error("WS ERROR for user " + _this.user.id + " - " + _this.user.nick); + } else { + console.error("WS ERROR"); + } + return console.error(err); + }; + })(this)); this.commands = {}; - this.register("ping", (msg) => { - this.send({ - name: "pong" - }); - return this.checkUpdates(); - }); - this.register("create_account", (msg) => { - return this.createAccount(msg); - }); - this.register("create_guest", (msg) => { - return this.createGuestAccount(msg); - }); - this.register("login", (msg) => { - return this.login(msg); - }); - this.register("send_password_recovery", (msg) => { - return this.sendPasswordRecovery(msg); - }); - this.register("token", (msg) => { - return this.checkToken(msg); - }); - this.register("delete_guest", (msg) => { - return this.deleteGuest(msg); - }); - this.register("delete_account", (msg) => { - return this.deleteAccount(msg); - }); - this.register("change_password", (msg) => { - return this.changePassword(msg); - }); - this.register("send_validation_mail", (msg) => { - return this.sendValidationMail(msg); - }); - this.register("change_email", (msg) => { - return this.changeEmail(msg); - }); - this.register("change_nick", (msg) => { - return this.changeNick(msg); - }); - this.register("change_password", (msg) => { - return this.changePassword(msg); - }); - this.register("change_newsletter", (msg) => { - return this.changeNewsletter(msg); - }); - this.register("change_experimental", (msg) => { - return this.changeExperimental(msg); - }); - this.register("set_user_setting", (msg) => { - return this.setUserSetting(msg); - }); - this.register("set_user_profile", (msg) => { - return this.setUserProfile(msg); - }); - this.register("create_project", (msg) => { - return this.createProject(msg); - }); - this.register("import_project", (msg) => { - return this.importProject(msg); - }); - this.register("set_project_option", (msg) => { - return this.setProjectOption(msg); - }); - this.register("set_project_property", (msg) => { - return this.setProjectProperty(msg); - }); - this.register("set_project_public", (msg) => { - return this.setProjectPublic(msg); - }); - this.register("set_project_tags", (msg) => { - return this.setProjectTags(msg); - }); - this.register("delete_project", (msg) => { - return this.deleteProject(msg); - }); - this.register("get_project_list", (msg) => { - return this.getProjectList(msg); - }); - this.register("update_code", (msg) => { - return this.updateCode(msg); - }); - this.register("lock_project_file", (msg) => { - return this.lockProjectFile(msg); - }); - this.register("write_project_file", (msg) => { - return this.writeProjectFile(msg); - }); - this.register("read_project_file", (msg) => { - return this.readProjectFile(msg); - }); - this.register("rename_project_file", (msg) => { - return this.renameProjectFile(msg); - }); - this.register("delete_project_file", (msg) => { - return this.deleteProjectFile(msg); - }); - this.register("list_project_files", (msg) => { - return this.listProjectFiles(msg); - }); - this.register("list_public_project_files", (msg) => { - return this.listPublicProjectFiles(msg); - }); - this.register("read_public_project_file", (msg) => { - return this.readPublicProjectFile(msg); - }); - this.register("listen_to_project", (msg) => { - return this.listenToProject(msg); - }); - this.register("get_file_versions", (msg) => { - return this.getFileVersions(msg); - }); - this.register("sync_project_files", (msg) => { - return this.syncProjectFiles(msg); - }); - this.register("invite_to_project", (msg) => { - return this.inviteToProject(msg); - }); - this.register("accept_invite", (msg) => { - return this.acceptInvite(msg); - }); - this.register("remove_project_user", (msg) => { - return this.removeProjectUser(msg); - }); - this.register("get_public_projects", (msg) => { - return this.getPublicProjects(msg); - }); - this.register("get_public_plugins", (msg) => { - return this.getPublicPlugins(msg); - }); - this.register("get_public_libraries", (msg) => { - return this.getPublicLibraries(msg); - }); - this.register("get_public_project", (msg) => { - return this.getPublicProject(msg); - }); - this.register("clone_project", (msg) => { - return this.cloneProject(msg); - }); - this.register("clone_public_project", (msg) => { - return this.clonePublicProject(msg); - }); - this.register("toggle_like", (msg) => { - return this.toggleLike(msg); - }); - this.register("get_language", (msg) => { - return this.getLanguage(msg); - }); - this.register("get_translation_list", (msg) => { - return this.getTranslationList(msg); - }); - this.register("set_translation", (msg) => { - return this.setTranslation(msg); - }); - this.register("add_translation", (msg) => { - return this.addTranslation(msg); - }); - this.register("get_project_comments", (msg) => { - return this.getProjectComments(msg); - }); - this.register("add_project_comment", (msg) => { - return this.addProjectComment(msg); - }); - this.register("delete_project_comment", (msg) => { - return this.deleteProjectComment(msg); - }); - this.register("edit_project_comment", (msg) => { - return this.editProjectComment(msg); - }); - this.register("build_project", (msg) => { - return this.buildProject(msg); - }); - this.register("get_build_status", (msg) => { - return this.getBuildStatus(msg); - }); - this.register("start_builder", (msg) => { - return this.startBuilder(msg); - }); - this.register("backup_complete", (msg) => { - return this.backupComplete(msg); - }); - this.register("upload_request", (msg) => { - return this.uploadRequest(msg); - }); - this.register("tutorial_completed", (msg) => { - return this.tutorialCompleted(msg); - }); - // moderation - this.register("set_project_approved", (msg) => { - return this.setProjectApproved(msg); - }); - this.register("set_user_approved", (msg) => { - return this.setUserApproved(msg); - }); - // client / server - this.register("relay_server_available", (msg) => { - return this.relayServerAvailable(msg); - }); - this.register("get_relay_server", (msg) => { - return this.getRelayServer(msg); - }); - this.register("get_server_token", (msg) => { - return this.getServerToken(msg); - }); - this.register("check_server_token", (msg) => { - return this.checkServerToken(msg); - }); + this.register("ping", (function(_this) { + return function(msg) { + _this.send({ + name: "pong" + }); + return _this.checkUpdates(); + }; + })(this)); + this.register("create_account", (function(_this) { + return function(msg) { + return _this.createAccount(msg); + }; + })(this)); + this.register("create_guest", (function(_this) { + return function(msg) { + return _this.createGuestAccount(msg); + }; + })(this)); + this.register("login", (function(_this) { + return function(msg) { + return _this.login(msg); + }; + })(this)); + this.register("send_password_recovery", (function(_this) { + return function(msg) { + return _this.sendPasswordRecovery(msg); + }; + })(this)); + this.register("token", (function(_this) { + return function(msg) { + return _this.checkToken(msg); + }; + })(this)); + this.register("delete_guest", (function(_this) { + return function(msg) { + return _this.deleteGuest(msg); + }; + })(this)); + this.register("delete_account", (function(_this) { + return function(msg) { + return _this.deleteAccount(msg); + }; + })(this)); + this.register("change_password", (function(_this) { + return function(msg) { + return _this.changePassword(msg); + }; + })(this)); + this.register("send_validation_mail", (function(_this) { + return function(msg) { + return _this.sendValidationMail(msg); + }; + })(this)); + this.register("change_email", (function(_this) { + return function(msg) { + return _this.changeEmail(msg); + }; + })(this)); + this.register("change_nick", (function(_this) { + return function(msg) { + return _this.changeNick(msg); + }; + })(this)); + this.register("change_password", (function(_this) { + return function(msg) { + return _this.changePassword(msg); + }; + })(this)); + this.register("change_newsletter", (function(_this) { + return function(msg) { + return _this.changeNewsletter(msg); + }; + })(this)); + this.register("change_experimental", (function(_this) { + return function(msg) { + return _this.changeExperimental(msg); + }; + })(this)); + this.register("set_user_setting", (function(_this) { + return function(msg) { + return _this.setUserSetting(msg); + }; + })(this)); + this.register("set_user_profile", (function(_this) { + return function(msg) { + return _this.setUserProfile(msg); + }; + })(this)); + this.register("create_project", (function(_this) { + return function(msg) { + return _this.createProject(msg); + }; + })(this)); + this.register("import_project", (function(_this) { + return function(msg) { + return _this.importProject(msg); + }; + })(this)); + this.register("set_project_option", (function(_this) { + return function(msg) { + return _this.setProjectOption(msg); + }; + })(this)); + this.register("set_project_property", (function(_this) { + return function(msg) { + return _this.setProjectProperty(msg); + }; + })(this)); + this.register("set_project_public", (function(_this) { + return function(msg) { + return _this.setProjectPublic(msg); + }; + })(this)); + this.register("set_project_tags", (function(_this) { + return function(msg) { + return _this.setProjectTags(msg); + }; + })(this)); + this.register("delete_project", (function(_this) { + return function(msg) { + return _this.deleteProject(msg); + }; + })(this)); + this.register("get_project_list", (function(_this) { + return function(msg) { + return _this.getProjectList(msg); + }; + })(this)); + this.register("update_code", (function(_this) { + return function(msg) { + return _this.updateCode(msg); + }; + })(this)); + this.register("lock_project_file", (function(_this) { + return function(msg) { + return _this.lockProjectFile(msg); + }; + })(this)); + this.register("write_project_file", (function(_this) { + return function(msg) { + return _this.writeProjectFile(msg); + }; + })(this)); + this.register("read_project_file", (function(_this) { + return function(msg) { + return _this.readProjectFile(msg); + }; + })(this)); + this.register("rename_project_file", (function(_this) { + return function(msg) { + return _this.renameProjectFile(msg); + }; + })(this)); + this.register("delete_project_file", (function(_this) { + return function(msg) { + return _this.deleteProjectFile(msg); + }; + })(this)); + this.register("list_project_files", (function(_this) { + return function(msg) { + return _this.listProjectFiles(msg); + }; + })(this)); + this.register("list_public_project_files", (function(_this) { + return function(msg) { + return _this.listPublicProjectFiles(msg); + }; + })(this)); + this.register("read_public_project_file", (function(_this) { + return function(msg) { + return _this.readPublicProjectFile(msg); + }; + })(this)); + this.register("listen_to_project", (function(_this) { + return function(msg) { + return _this.listenToProject(msg); + }; + })(this)); + this.register("get_file_versions", (function(_this) { + return function(msg) { + return _this.getFileVersions(msg); + }; + })(this)); + this.register("sync_project_files", (function(_this) { + return function(msg) { + return _this.syncProjectFiles(msg); + }; + })(this)); + this.register("invite_to_project", (function(_this) { + return function(msg) { + return _this.inviteToProject(msg); + }; + })(this)); + this.register("accept_invite", (function(_this) { + return function(msg) { + return _this.acceptInvite(msg); + }; + })(this)); + this.register("remove_project_user", (function(_this) { + return function(msg) { + return _this.removeProjectUser(msg); + }; + })(this)); + this.register("get_public_projects", (function(_this) { + return function(msg) { + return _this.getPublicProjects(msg); + }; + })(this)); + this.register("get_public_plugins", (function(_this) { + return function(msg) { + return _this.getPublicPlugins(msg); + }; + })(this)); + this.register("get_public_libraries", (function(_this) { + return function(msg) { + return _this.getPublicLibraries(msg); + }; + })(this)); + this.register("get_public_project", (function(_this) { + return function(msg) { + return _this.getPublicProject(msg); + }; + })(this)); + this.register("clone_project", (function(_this) { + return function(msg) { + return _this.cloneProject(msg); + }; + })(this)); + this.register("clone_public_project", (function(_this) { + return function(msg) { + return _this.clonePublicProject(msg); + }; + })(this)); + this.register("toggle_like", (function(_this) { + return function(msg) { + return _this.toggleLike(msg); + }; + })(this)); + this.register("get_language", (function(_this) { + return function(msg) { + return _this.getLanguage(msg); + }; + })(this)); + this.register("get_translation_list", (function(_this) { + return function(msg) { + return _this.getTranslationList(msg); + }; + })(this)); + this.register("set_translation", (function(_this) { + return function(msg) { + return _this.setTranslation(msg); + }; + })(this)); + this.register("add_translation", (function(_this) { + return function(msg) { + return _this.addTranslation(msg); + }; + })(this)); + this.register("get_project_comments", (function(_this) { + return function(msg) { + return _this.getProjectComments(msg); + }; + })(this)); + this.register("add_project_comment", (function(_this) { + return function(msg) { + return _this.addProjectComment(msg); + }; + })(this)); + this.register("delete_project_comment", (function(_this) { + return function(msg) { + return _this.deleteProjectComment(msg); + }; + })(this)); + this.register("edit_project_comment", (function(_this) { + return function(msg) { + return _this.editProjectComment(msg); + }; + })(this)); + this.register("build_project", (function(_this) { + return function(msg) { + return _this.buildProject(msg); + }; + })(this)); + this.register("get_build_status", (function(_this) { + return function(msg) { + return _this.getBuildStatus(msg); + }; + })(this)); + this.register("start_builder", (function(_this) { + return function(msg) { + return _this.startBuilder(msg); + }; + })(this)); + this.register("backup_complete", (function(_this) { + return function(msg) { + return _this.backupComplete(msg); + }; + })(this)); + this.register("upload_request", (function(_this) { + return function(msg) { + return _this.uploadRequest(msg); + }; + })(this)); + this.register("tutorial_completed", (function(_this) { + return function(msg) { + return _this.tutorialCompleted(msg); + }; + })(this)); + this.register("set_project_approved", (function(_this) { + return function(msg) { + return _this.setProjectApproved(msg); + }; + })(this)); + this.register("set_user_approved", (function(_this) { + return function(msg) { + return _this.setUserApproved(msg); + }; + })(this)); + this.register("relay_server_available", (function(_this) { + return function(msg) { + return _this.relayServerAvailable(msg); + }; + })(this)); + this.register("get_relay_server", (function(_this) { + return function(msg) { + return _this.getRelayServer(msg); + }; + })(this)); + this.register("get_server_token", (function(_this) { + return function(msg) { + return _this.getServerToken(msg); + }; + })(this)); + this.register("check_server_token", (function(_this) { + return function(msg) { + return _this.checkServerToken(msg); + }; + })(this)); if (!this.server.config.delegate_relay_service) { this.relay_service = new RelayService(this); } @@ -278,7 +415,7 @@ this.Session = class Session { }; } - checkCookie() { + Session.prototype.checkCookie = function() { var cookie, error; try { cookie = this.socket.request.headers.cookie; @@ -308,9 +445,9 @@ this.Session = class Session { error = error1; return console.error(error); } - } + }; - logActiveUser() { + Session.prototype.logActiveUser = function() { if (this.user == null) { return; } @@ -319,13 +456,13 @@ this.Session = class Session { } else { return this.server.stats.unique("active_users", this.user.id); } - } + }; - register(name, callback) { + Session.prototype.register = function(name, callback) { return this.commands[name] = callback; - } + }; - disconnected() { + Session.prototype.disconnected = function() { var err; try { if ((this.project != null) && (this.project.manager != null)) { @@ -339,9 +476,9 @@ this.Session = class Session { err = error1; return console.error(err); } - } + }; - setCurrentProject(project) { + Session.prototype.setCurrentProject = function(project) { if (project !== this.project || (this.project.manager == null)) { if ((this.project != null) && (this.project.manager != null)) { this.project.manager.removeSession(this); @@ -352,15 +489,14 @@ this.Session = class Session { } return this.project.manager.addUser(this); } - } + }; - messageReceived(msg) { + Session.prototype.messageReceived = function(msg) { var c, err; if (typeof msg !== "string") { return this.bufferReceived(msg); } try { - //console.info msg msg = JSON.parse(msg); if (msg.name != null) { c = this.commands[msg.name]; @@ -376,17 +512,17 @@ this.Session = class Session { if (this.user != null) { return this.logActiveUser(); } - } + }; - sendCodeUpdated(file, code) { + Session.prototype.sendCodeUpdated = function(file, code) { this.send({ name: "code_updated", file: file, code: code }); - } + }; - sendProjectFileUpdated(type, file, version, data, properties) { + Session.prototype.sendProjectFileUpdated = function(type, file, version, data, properties) { return this.send({ name: "project_file_updated", type: type, @@ -395,17 +531,17 @@ this.Session = class Session { data: data, properties: properties }); - } + }; - sendProjectFileDeleted(type, file) { + Session.prototype.sendProjectFileDeleted = function(type, file) { return this.send({ name: "project_file_deleted", type: type, file: file }); - } + }; - createGuestAccount(data) { + Session.prototype.createGuestAccount = function(data) { var chars, i, j, nick; if (!this.server.rate_limiter.accept("create_account_ip", this.socket.remoteAddress)) { return; @@ -441,19 +577,19 @@ this.Session = class Session { request_id: data.request_id }); return this.logActiveUser(); - } + }; - deleteGuest(data) { + Session.prototype.deleteGuest = function(data) { if ((this.user != null) && this.user.flags.guest) { - this.user.delete(); + this.user["delete"](); return this.send({ name: "guest_deleted", request_id: data.request_id }); } - } + }; - createAccount(data) { + Session.prototype.createAccount = function(data) { var chars, hash, i, j, salt; if (data.email == null) { return this.sendError(this.translator.get("email not specified"), data.request_id); @@ -527,9 +663,9 @@ this.Session = class Session { }); this.sendValidationMail(); return this.logActiveUser(); - } + }; - login(data) { + Session.prototype.login = function(data) { var h, hash, s, user; if (data.nick == null) { return; @@ -548,9 +684,6 @@ this.Session = class Session { hash = user.hash; s = hash.split("|"); h = SHA256(s[0] + data.password); - //console.info "salt: #{s[0]}" - //console.info "hash: #{h}" - //console.info "recorded hash: #{s[1]}" if (h.toString() === s[1]) { this.user = user; this.user.addListener(this); @@ -573,9 +706,9 @@ this.Session = class Session { } else { return this.sendError("unknown user", data.request_id); } - } + }; - createHashedPassword(password) { + Session.prototype.createHashedPassword = function(password) { var chars, i, j, salt; salt = ""; chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; @@ -583,9 +716,9 @@ this.Session = class Session { salt += chars.charAt(Math.floor(Math.random() * chars.length)); } return salt + "|" + SHA256(salt + password); - } + }; - changePassword(data) { + Session.prototype.changePassword = function(data) { var h, hash, s; if ((this.user == null) || (this.user.hash == null)) { return; @@ -593,14 +726,14 @@ this.Session = class Session { if (data.current == null) { return; } - if (data.new == null) { + if (data["new"] == null) { return; } hash = this.user.hash; s = hash.split("|"); h = SHA256(s[0] + data.current); if (h.toString() === s[1]) { - hash = this.createHashedPassword(data.new); + hash = this.createHashedPassword(data["new"]); this.user.set("hash", hash); return this.send({ request_id: data.request_id, @@ -609,9 +742,9 @@ this.Session = class Session { } else { return this.sendError("wrong password", data.request_id); } - } + }; - getUserInfo() { + Session.prototype.getUserInfo = function() { return { size: this.user.getTotalSize(), early_access: this.user.early_access, @@ -620,9 +753,9 @@ this.Session = class Session { stats: this.user.progress.exportStats(), achievements: this.user.progress.exportAchievements() }; - } + }; - sendPasswordRecovery(data) { + Session.prototype.sendPasswordRecovery = function(data) { var user; if (data.email != null) { user = this.content.findUserByEmail(data.email); @@ -636,9 +769,9 @@ this.Session = class Session { name: "send_password_recovery", request_id: data.request_id }); - } + }; - checkToken(data) { + Session.prototype.checkToken = function(data) { var token; if (this.server.config.standalone && this.content.user_count === 1) { this.user = this.server.content.users[0]; @@ -677,21 +810,21 @@ this.Session = class Session { } else { return this.sendError("invalid token", data.request_id); } - } + }; - send(data) { + Session.prototype.send = function(data) { return this.socket.send(JSON.stringify(data)); - } + }; - sendError(error, request_id) { + Session.prototype.sendError = function(error, request_id) { return this.send({ name: "error", error: error, request_id: request_id }); - } + }; - syncProjectFiles(data) { + Session.prototype.syncProjectFiles = function(data) { var dest, source; if (data.request_id == null) { return this.sendError("Bad request"); @@ -719,9 +852,9 @@ this.Session = class Session { return dest.manager.syncFiles(this, data, source); } } - } + }; - importProject(data) { + Session.prototype.importProject = function(data) { var buffer, projectFileName, zip; if (data.request_id == null) { return this.sendError("Bad request"); @@ -735,68 +868,70 @@ this.Session = class Session { if (!this.server.rate_limiter.accept("import_project_user", this.user.id)) { return this.sendError("Rate limited", data.request_id); } - //return @sendError("wrong data") if not data.zip_data? or typeof data.zip_data != "string" - - //split = data.zip_data.split(",") - //return @sendError("unrecognized data") if not split[1]? - buffer = data.data; //Buffer.from(split[1],'base64') + buffer = data.data; if (buffer.byteLength > this.user.max_storage - this.user.getTotalSize()) { return this.sendError("storage space exceeded", data.request_id); } zip = new JSZip; projectFileName = "project.json"; - return zip.loadAsync(buffer).then(((contents) => { - if (zip.file(projectFileName) == null) { - this.sendError(`[ZIP] Missing ${projectFileName}; import aborted`, data.request_id); - console.log(`[ZIP] Missing ${projectFileName}; import aborted`); - return; - } - return zip.file(projectFileName).async("string").then(((text) => { - var err, projectInfo; - try { - projectInfo = JSON.parse(text); - } catch (error1) { - err = error1; - this.sendError("Incorrect JSON data", data.request_id); - console.error(err); + return zip.loadAsync(buffer).then(((function(_this) { + return function(contents) { + if (zip.file(projectFileName) == null) { + _this.sendError("[ZIP] Missing " + projectFileName + "; import aborted", data.request_id); + console.log("[ZIP] Missing " + projectFileName + "; import aborted"); return; } - return this.content.createProject(this.user, projectInfo, ((project) => { - this.setCurrentProject(project); - return project.manager.importFiles(contents, () => { - project.set("files", projectInfo.files || {}); - return this.send({ - name: "project_imported", - id: project.id, - request_id: data.request_id + return zip.file(projectFileName).async("string").then((function(text) { + var err, projectInfo; + try { + projectInfo = JSON.parse(text); + } catch (error1) { + err = error1; + _this.sendError("Incorrect JSON data", data.request_id); + console.error(err); + return; + } + return _this.content.createProject(_this.user, projectInfo, (function(project) { + _this.setCurrentProject(project); + return project.manager.importFiles(contents, function() { + project.set("files", projectInfo.files || {}); + return _this.send({ + name: "project_imported", + id: project.id, + request_id: data.request_id + }); }); - }); - }), true); - }), () => { - return this.sendError("Malformed ZIP file", data.request_id); - }); - }), () => { - return this.sendError("Malformed ZIP file", data.request_id); - }); - } + }), true); + }), function() { + return _this.sendError("Malformed ZIP file", data.request_id); + }); + }; + })(this)), (function(_this) { + return function() { + return _this.sendError("Malformed ZIP file", data.request_id); + }; + })(this)); + }; - createProject(data) { + Session.prototype.createProject = function(data) { if (this.user == null) { return this.sendError("not connected"); } if (!this.server.rate_limiter.accept("create_project_user", this.user.id)) { return; } - return this.content.createProject(this.user, data, (project) => { - return this.send({ - name: "project_created", - id: project.id, - request_id: data.request_id - }); - }); - } + return this.content.createProject(this.user, data, (function(_this) { + return function(project) { + return _this.send({ + name: "project_created", + id: project.id, + request_id: data.request_id + }); + }; + })(this)); + }; - clonePublicProject(data) { + Session.prototype.clonePublicProject = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -808,82 +943,13 @@ this.Session = class Session { return this.sendError(""); } project = this.server.content.projects[data.project]; - if ((project != null) && project.public) { + if ((project != null) && project["public"]) { return this.content.createProject(this.user, { title: project.title, slug: project.slug, - public: false - }, ((clone) => { - var files, folders, funk, man; - clone.setType(project.type); - clone.setOrientation(project.orientation); - clone.setAspect(project.aspect); - clone.set("language", project.language); - clone.setGraphics(project.graphics); - clone.set("networking", project.networking); - clone.set("libs", project.libs); - clone.set("tabs", project.tabs); - clone.set("plugins", project.plugins); - clone.set("libraries", project.libraries); - clone.set("files", JSON.parse(JSON.stringify(project.files))); - man = this.getProjectManager(project); - folders = ["ms", "sprites", "maps", "sounds", "sounds_th", "music", "music_th", "assets", "assets_th", "doc"]; - files = []; - funk = () => { - var dest, f, folder, src; - if (folders.length > 0) { - folder = folders.splice(0, 1)[0]; - return man.listFiles(folder, (list) => { - var f, j, len1; - for (j = 0, len1 = list.length; j < len1; j++) { - f = list[j]; - files.push({ - file: f.file, - folder: folder - }); - } - return funk(); - }); - } else if (files.length > 0) { - f = files.splice(0, 1)[0]; - src = `${project.owner.id}/${project.id}/${f.folder}/${f.file}`; - dest = `${clone.owner.id}/${clone.id}/${f.folder}/${f.file}`; - return this.server.content.files.copy(src, dest, () => { - return funk(); - }); - } else { - return this.send({ - name: "project_created", - id: clone.id, - request_id: data.request_id - }); - } - }; - return funk(); - }), true); - } - } - - cloneProject(data) { - var manager, project; - if (this.user == null) { - return this.sendError("not connected"); - } - if (!this.server.rate_limiter.accept("create_project_user", this.user.id)) { - return; - } - if (data.project == null) { - return this.sendError(""); - } - project = this.server.content.projects[data.project]; - if (project != null) { - manager = this.getProjectManager(project); - if (manager.canRead(this.user)) { - return this.content.createProject(this.user, { - title: data.title || project.title, - slug: project.slug, - public: false - }, ((clone) => { + "public": false + }, ((function(_this) { + return function(clone) { var files, folders, funk, man; clone.setType(project.type); clone.setOrientation(project.orientation); @@ -896,14 +962,14 @@ this.Session = class Session { clone.set("plugins", project.plugins); clone.set("libraries", project.libraries); clone.set("files", JSON.parse(JSON.stringify(project.files))); - man = this.getProjectManager(project); + man = _this.getProjectManager(project); folders = ["ms", "sprites", "maps", "sounds", "sounds_th", "music", "music_th", "assets", "assets_th", "doc"]; files = []; - funk = () => { + funk = function() { var dest, f, folder, src; if (folders.length > 0) { folder = folders.splice(0, 1)[0]; - return man.listFiles(folder, (list) => { + return man.listFiles(folder, function(list) { var f, j, len1; for (j = 0, len1 = list.length; j < len1; j++) { f = list[j]; @@ -916,13 +982,13 @@ this.Session = class Session { }); } else if (files.length > 0) { f = files.splice(0, 1)[0]; - src = `${project.owner.id}/${project.id}/${f.folder}/${f.file}`; - dest = `${clone.owner.id}/${clone.id}/${f.folder}/${f.file}`; - return this.server.content.files.copy(src, dest, () => { + src = project.owner.id + "/" + project.id + "/" + f.folder + "/" + f.file; + dest = clone.owner.id + "/" + clone.id + "/" + f.folder + "/" + f.file; + return _this.server.content.files.copy(src, dest, function() { return funk(); }); } else { - return this.send({ + return _this.send({ name: "project_created", id: clone.id, request_id: data.request_id @@ -930,35 +996,108 @@ this.Session = class Session { } }; return funk(); - }), true); + }; + })(this)), true); + } + }; + + Session.prototype.cloneProject = function(data) { + var manager, project; + if (this.user == null) { + return this.sendError("not connected"); + } + if (!this.server.rate_limiter.accept("create_project_user", this.user.id)) { + return; + } + if (data.project == null) { + return this.sendError(""); + } + project = this.server.content.projects[data.project]; + if (project != null) { + manager = this.getProjectManager(project); + if (manager.canRead(this.user)) { + return this.content.createProject(this.user, { + title: data.title || project.title, + slug: project.slug, + "public": false + }, ((function(_this) { + return function(clone) { + var files, folders, funk, man; + clone.setType(project.type); + clone.setOrientation(project.orientation); + clone.setAspect(project.aspect); + clone.set("language", project.language); + clone.setGraphics(project.graphics); + clone.set("networking", project.networking); + clone.set("libs", project.libs); + clone.set("tabs", project.tabs); + clone.set("plugins", project.plugins); + clone.set("libraries", project.libraries); + clone.set("files", JSON.parse(JSON.stringify(project.files))); + man = _this.getProjectManager(project); + folders = ["ms", "sprites", "maps", "sounds", "sounds_th", "music", "music_th", "assets", "assets_th", "doc"]; + files = []; + funk = function() { + var dest, f, folder, src; + if (folders.length > 0) { + folder = folders.splice(0, 1)[0]; + return man.listFiles(folder, function(list) { + var f, j, len1; + for (j = 0, len1 = list.length; j < len1; j++) { + f = list[j]; + files.push({ + file: f.file, + folder: folder + }); + } + return funk(); + }); + } else if (files.length > 0) { + f = files.splice(0, 1)[0]; + src = project.owner.id + "/" + project.id + "/" + f.folder + "/" + f.file; + dest = clone.owner.id + "/" + clone.id + "/" + f.folder + "/" + f.file; + return _this.server.content.files.copy(src, dest, function() { + return funk(); + }); + } else { + return _this.send({ + name: "project_created", + id: clone.id, + request_id: data.request_id + }); + } + }; + return funk(); + }; + })(this)), true); } } - } + }; - getProjectManager(project) { + Session.prototype.getProjectManager = function(project) { if (project.manager == null) { new ProjectManager(project); } return project.manager; - } + }; - setProjectPublic(data) { + Session.prototype.setProjectPublic = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); } - if (data.public && !this.user.flags["validated"]) { + if (data["public"] && !this.user.flags["validated"]) { return; } if (data.project == null) { if (this.user.flags.admin && data.id) { project = this.content.projects[data.id]; if (project != null) { - this.content.setProjectPublic(project, data.public); + this.content.setProjectPublic(project, data["public"]); return this.send({ name: "set_project_public", id: project.id, - public: project.public, + "public": project["public"], request_id: data.request_id }); } @@ -966,18 +1105,18 @@ this.Session = class Session { } else { project = this.user.findProject(data.project); if (project != null) { - this.content.setProjectPublic(project, data.public); + this.content.setProjectPublic(project, data["public"]); return this.send({ name: "set_project_public", id: project.id, - public: project.public, + "public": project["public"], request_id: data.request_id }); } } - } + }; - setProjectApproved(data) { + Session.prototype.setProjectApproved = function(data) { var project; if (this.user == null) { return; @@ -997,9 +1136,9 @@ this.Session = class Session { }); } } - } + }; - setUserApproved(data) { + Session.prototype.setUserApproved = function(data) { var user; if (this.user == null) { return; @@ -1019,14 +1158,14 @@ this.Session = class Session { }); } } - } + }; - setProjectTags(data) { + Session.prototype.setProjectTags = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); } - if (data.public && !this.user.flags["validated"]) { + if (data["public"] && !this.user.flags["validated"]) { return; } if (data.project == null) { @@ -1045,9 +1184,9 @@ this.Session = class Session { request_id: data.request_id }); } - } + }; - setProjectOption(data) { + Session.prototype.setProjectOption = function(data) { var j, len1, project, ref, v; if (this.user == null) { return this.sendError("not connected"); @@ -1154,9 +1293,9 @@ this.Session = class Session { } return project.touch(); } - } + }; - setProjectProperty(data) { + Session.prototype.setProjectProperty = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -1171,9 +1310,9 @@ this.Session = class Session { if (project != null) { return project.setProperty(data.property, data.value); } - } + }; - deleteProject(data) { + Session.prototype.deleteProject = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -1187,9 +1326,9 @@ this.Session = class Session { request_id: data.request_id }); } - } + }; - getProjectList(data) { + Session.prototype.getProjectList = function(data) { var j, k, len1, len2, link, list, p, source; if (this.user == null) { return this.sendError("not connected"); @@ -1227,7 +1366,7 @@ this.Session = class Session { properties: p.properties, date_created: p.date_created, last_modified: p.last_modified, - public: p.public, + "public": p["public"], unlisted: p.unlisted, size: p.getSize(), users: p.listUsers() @@ -1267,7 +1406,7 @@ this.Session = class Session { networking: p.networking, date_created: p.date_created, last_modified: p.last_modified, - public: p.public, + "public": p["public"], unlisted: p.unlisted, users: p.listUsers() }); @@ -1278,24 +1417,23 @@ this.Session = class Session { list: list, request_id: data != null ? data.request_id : void 0 }); - } + }; - lockProjectFile(data) { + Session.prototype.lockProjectFile = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); } if (data.project != null) { - //console.info JSON.stringify data project = this.content.projects[data.project]; } if (project != null) { this.setCurrentProject(project); return project.manager.lockFile(this, data.file); } - } + }; - writeProjectFile(data) { + Session.prototype.writeProjectFile = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -1331,9 +1469,9 @@ this.Session = class Session { } } } - } + }; - renameProjectFile(data) { + Session.prototype.renameProjectFile = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -1345,9 +1483,9 @@ this.Session = class Session { this.setCurrentProject(project); return project.manager.renameProjectFile(this, data); } - } + }; - deleteProjectFile(data) { + Session.prototype.deleteProjectFile = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -1359,12 +1497,11 @@ this.Session = class Session { this.setCurrentProject(project); return project.manager.deleteProjectFile(this, data); } - } + }; - readProjectFile(data) { + Session.prototype.readProjectFile = function(data) { var project; if (this.user == null) { - //console.info "session.readProjectFile "+JSON.stringify data return this.sendError("not connected"); } if (data.project != null) { @@ -1374,9 +1511,9 @@ this.Session = class Session { this.setCurrentProject(project); return project.manager.readProjectFile(this, data); } - } + }; - listProjectFiles(data) { + Session.prototype.listProjectFiles = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -1388,9 +1525,9 @@ this.Session = class Session { this.setCurrentProject(project); return project.manager.listProjectFiles(this, data); } - } + }; - listPublicProjectFiles(data) { + Session.prototype.listPublicProjectFiles = function(data) { var manager, project; if (data.project != null) { project = this.content.projects[data.project]; @@ -1399,20 +1536,20 @@ this.Session = class Session { manager = this.getProjectManager(project); return manager.listProjectFiles(this, data); } - } + }; - readPublicProjectFile(data) { + Session.prototype.readPublicProjectFile = function(data) { var manager, project; if (data.project != null) { project = this.content.projects[data.project]; } - if ((project != null) && project.public) { + if ((project != null) && project["public"]) { manager = this.getProjectManager(project); return project.manager.readProjectFile(this, data); } - } + }; - listenToProject(data) { + Session.prototype.listenToProject = function(data) { var project, user; user = data.user; project = data.project; @@ -1432,9 +1569,9 @@ this.Session = class Session { } } } - } + }; - getFileVersions(data) { + Session.prototype.getFileVersions = function(data) { var project, user; user = data.user; project = data.project; @@ -1446,19 +1583,21 @@ this.Session = class Session { if (project.manager == null) { new ProjectManager(project); } - return project.manager.getFileVersions((res) => { - return this.send({ - name: "project_file_versions", - data: res, - request_id: data.request_id - }); - }); + return project.manager.getFileVersions((function(_this) { + return function(res) { + return _this.send({ + name: "project_file_versions", + data: res, + request_id: data.request_id + }); + }; + })(this)); } } } - } + }; - getPublicProjects(data) { + Session.prototype.getPublicProjects = function(data) { var found, i, j, k, l, language, len1, len2, len3, list, m, offset, p, ref, ref1, ref2, ref3, search, source, t, tags, type; switch (data.ranking) { case "new": @@ -1483,7 +1622,7 @@ this.Session = class Session { break; } offset = i + 1; - if (p.public && !p.deleted && !p.owner.flags.censored) { + if (p["public"] && !p.deleted && !p.owner.flags.censored) { if (search) { found = false; found |= p.title.toLowerCase().includes(search); @@ -1564,15 +1703,15 @@ this.Session = class Session { offset: offset, request_id: data.request_id }); - } + }; - getPublicPlugins(data) { + Session.prototype.getPublicPlugins = function(data) { var j, len1, list, p, source; source = this.content.plugin_projects; list = []; for (j = 0, len1 = source.length; j < len1; j++) { p = source[j]; - if (p.public && !p.deleted && !p.owner.flags.censored) { + if (p["public"] && !p.deleted && !p.owner.flags.censored) { list.push({ id: p.id, title: p.title, @@ -1607,15 +1746,15 @@ this.Session = class Session { list: list, request_id: data.request_id }); - } + }; - getPublicLibraries(data) { + Session.prototype.getPublicLibraries = function(data) { var j, len1, list, p, source; source = this.content.library_projects; list = []; for (j = 0, len1 = source.length; j < len1; j++) { p = source[j]; - if (p.public && !p.deleted && !p.owner.flags.censored) { + if (p["public"] && !p.deleted && !p.owner.flags.censored) { list.push({ id: p.id, title: p.title, @@ -1650,9 +1789,9 @@ this.Session = class Session { list: list, request_id: data.request_id }); - } + }; - getPublicProject(msg) { + Session.prototype.getPublicProject = function(msg) { var owner, p, project, res; owner = msg.owner; project = msg.project; @@ -1660,7 +1799,7 @@ this.Session = class Session { owner = this.content.findUserByNick(owner); if (owner != null) { p = owner.findProjectBySlug(project); - if ((p != null) && p.public) { + if ((p != null) && p["public"]) { res = { id: p.id, title: p.title, @@ -1696,9 +1835,9 @@ this.Session = class Session { } } } - } + }; - toggleLike(data) { + Session.prototype.toggleLike = function(data) { var project; if (this.user == null) { return this.sendError("not connected"); @@ -1725,9 +1864,9 @@ this.Session = class Session { request_id: data.request_id }); } - } + }; - inviteToProject(data) { + Session.prototype.inviteToProject = function(data) { var project, user; if (this.user == null) { return this.sendError("not connected", data.request_id); @@ -1742,9 +1881,9 @@ this.Session = class Session { } this.setCurrentProject(project); return project.manager.inviteUser(this, user); - } + }; - acceptInvite(data) { + Session.prototype.acceptInvite = function(data) { var j, k, len1, len2, li, link, ref, ref1; if (this.user == null) { return this.sendError("not connected"); @@ -1765,9 +1904,9 @@ this.Session = class Session { } } } - } + }; - removeProjectUser(data) { + Session.prototype.removeProjectUser = function(data) { var j, k, len1, len2, li, link, nick, project, ref, ref1, user; if (this.user == null) { return this.sendError("not connected"); @@ -1811,9 +1950,9 @@ this.Session = class Session { } } } - } + }; - sendValidationMail(data) { + Session.prototype.sendValidationMail = function(data) { if (this.user == null) { return this.sendError("not connected"); } @@ -1826,9 +1965,9 @@ this.Session = class Session { }); } } - } + }; - changeNick(data) { + Session.prototype.changeNick = function(data) { if (this.user == null) { return; } @@ -1857,9 +1996,9 @@ this.Session = class Session { }); } } - } + }; - changeEmail(data) { + Session.prototype.changeEmail = function(data) { if (this.user == null) { return; } @@ -1891,9 +2030,9 @@ this.Session = class Session { }); } } - } + }; - changeNewsletter(data) { + Session.prototype.changeNewsletter = function(data) { if (this.user == null) { return; } @@ -1903,9 +2042,9 @@ this.Session = class Session { newsletter: data.newsletter, request_id: data.request_id }); - } + }; - changeExperimental(data) { + Session.prototype.changeExperimental = function(data) { if ((this.user == null) || !this.user.flags.validated) { return; } @@ -1915,9 +2054,9 @@ this.Session = class Session { experimental: data.experimental, request_id: data.request_id }); - } + }; - setUserSetting(data) { + Session.prototype.setUserSetting = function(data) { if (this.user == null) { return; } @@ -1925,9 +2064,9 @@ this.Session = class Session { return; } return this.user.setSetting(data.setting, data.value); - } + }; - setUserProfile(data) { + Session.prototype.setUserProfile = function(data) { var content, file; if (this.user == null) { return; @@ -1936,15 +2075,17 @@ this.Session = class Session { if (data.image === 0) { this.user.setFlag("profile_image", false); } else { - file = `${this.user.id}/profile_image.png`; + file = this.user.id + "/profile_image.png"; content = new Buffer(data.image, "base64"); - this.server.content.files.write(file, content, () => { - this.user.setFlag("profile_image", true); - return this.send({ - name: "set_user_profile", - request_id: data.request_id - }); - }); + this.server.content.files.write(file, content, (function(_this) { + return function() { + _this.user.setFlag("profile_image", true); + return _this.send({ + name: "set_user_profile", + request_id: data.request_id + }); + }; + })(this)); return; } } @@ -1955,31 +2096,31 @@ this.Session = class Session { name: "set_user_profile", request_id: data.request_id }); - } + }; - getLanguage(msg) { + Session.prototype.getLanguage = function(msg) { var lang; if (msg.language == null) { return; } lang = this.server.content.translator.languages[msg.language]; - lang = lang != null ? lang.export() : "{}"; + lang = lang != null ? lang["export"]() : "{}"; return this.send({ name: "get_language", language: lang, request_id: msg.request_id }); - } + }; - getTranslationList(msg) { + Session.prototype.getTranslationList = function(msg) { return this.send({ name: "get_translation_list", list: this.server.content.translator.list, request_id: msg.request_id }); - } + }; - setTranslation(msg) { + Session.prototype.setTranslation = function(msg) { var lang, source, translation; if (this.user == null) { return; @@ -1994,19 +2135,18 @@ this.Session = class Session { this.server.content.translator.createLanguage(lang); } return this.server.content.translator.languages[lang].set(this.user.id, source, translation); - } + }; - addTranslation(msg) { + Session.prototype.addTranslation = function(msg) { var source; if (this.user == null) { return; } - //return if not @user.flags.admin source = msg.source; return this.server.content.translator.reference(source); - } + }; - getProjectComments(data) { + Session.prototype.getProjectComments = function(data) { var project; if (data.project == null) { return; @@ -2014,16 +2154,16 @@ this.Session = class Session { if (data.project != null) { project = this.content.projects[data.project]; } - if ((project != null) && project.public) { + if ((project != null) && project["public"]) { return this.send({ name: "project_comments", request_id: data.request_id, comments: project.comments.getAll() }); } - } + }; - addProjectComment(data) { + Session.prototype.addProjectComment = function(data) { var project; if (data.project == null) { return; @@ -2034,7 +2174,7 @@ this.Session = class Session { if (data.project != null) { project = this.content.projects[data.project]; } - if ((project != null) && project.public) { + if ((project != null) && project["public"]) { if ((this.user != null) && this.user.flags.validated && !this.user.flags.banned && !this.user.flags.censored) { if (!this.server.rate_limiter.accept("post_comment_user", this.user.id)) { return; @@ -2046,9 +2186,9 @@ this.Session = class Session { }); } } - } + }; - deleteProjectComment(data) { + Session.prototype.deleteProjectComment = function(data) { var c, project; if (data.project == null) { return; @@ -2059,7 +2199,7 @@ this.Session = class Session { if (data.project != null) { project = this.content.projects[data.project]; } - if ((project != null) && project.public) { + if ((project != null) && project["public"]) { if (this.user != null) { c = project.comments.get(data.id); if ((c != null) && (c.user === this.user || this.user.flags.admin)) { @@ -2071,9 +2211,9 @@ this.Session = class Session { } } } - } + }; - editProjectComment(data) { + Session.prototype.editProjectComment = function(data) { var c, project; if (data.project == null) { return; @@ -2087,7 +2227,7 @@ this.Session = class Session { if (data.project != null) { project = this.content.projects[data.project]; } - if ((project != null) && project.public) { + if ((project != null) && project["public"]) { if (this.user != null) { c = project.comments.get(data.id); if ((c != null) && c.user === this.user) { @@ -2099,9 +2239,9 @@ this.Session = class Session { } } } - } + }; - tutorialCompleted(msg) { + Session.prototype.tutorialCompleted = function(msg) { if (this.user == null) { return; } @@ -2113,9 +2253,9 @@ this.Session = class Session { } this.user.progress.unlockAchievement(msg.id); return this.checkUpdates(); - } + }; - checkUpdates() { + Session.prototype.checkUpdates = function() { if (this.user != null) { if (this.user.progress.achievements_update !== this.achievements_update) { this.achievements_update = this.user.progress.achievements_update; @@ -2126,9 +2266,9 @@ this.Session = class Session { return this.sendUserStats(); } } - } + }; - sendAchievements() { + Session.prototype.sendAchievements = function() { if (this.user == null) { return; } @@ -2136,9 +2276,9 @@ this.Session = class Session { name: "achievements", achievements: this.user.progress.exportAchievements() }); - } + }; - sendUserStats() { + Session.prototype.sendUserStats = function() { if (this.user == null) { return; } @@ -2146,16 +2286,16 @@ this.Session = class Session { name: "user_stats", stats: this.user.progress.exportStats() }); - } + }; - showError(text) { + Session.prototype.showError = function(text) { return this.send({ name: "show_error", error: text }); - } + }; - buildProject(msg) { + Session.prototype.buildProject = function(msg) { var build, project; if (this.user == null) { return this.sendError("not connected"); @@ -2175,12 +2315,12 @@ this.Session = class Session { return this.send({ name: "build_project", request_id: msg.request_id, - build: build != null ? build.export() : null + build: build != null ? build["export"]() : null }); } - } + }; - getBuildStatus(msg) { + Session.prototype.getBuildStatus = function(msg) { var build, project; if (this.user == null) { return this.sendError("not connected"); @@ -2200,14 +2340,14 @@ this.Session = class Session { return this.send({ name: "build_project", request_id: msg.request_id, - build: build != null ? build.export() : null, + build: build != null ? build["export"]() : null, active_target: this.server.build_manager.hasBuilder(msg.target) }); } - } + }; - timeCheck() { - if (Date.now() > this.last_active + 5 * 60000) { // 5 minutes prevents breaking large assets uploads + Session.prototype.timeCheck = function() { + if (Date.now() > this.last_active + 5 * 60000) { this.socket.close(); this.server.sessionClosed(this); this.socket.terminate(); @@ -2216,42 +2356,44 @@ this.Session = class Session { this.upload_request_id = -1; return this.upload_request_buffers = []; } - } + }; - startBuilder(msg) { + Session.prototype.startBuilder = function(msg) { if (msg.target != null) { if (msg.key === this.server.config["builder-key"]) { this.server.sessionClosed(this); return this.server.build_manager.registerBuilder(this, msg.target); } } - } + }; - backupComplete(msg) { + Session.prototype.backupComplete = function(msg) { if (msg.key === this.server.config["backup-key"]) { this.server.sessionClosed(this); return this.server.last_backup_time = Date.now(); } - } + }; - relayServerAvailable(msg) { + Session.prototype.relayServerAvailable = function(msg) { if (msg.key === this.server.config["relay-key"]) { this.server.relay_server = { address: msg.address, session: this, time: Date.now() }; - this.disconnected = () => { - if ((this.server.relay_server != null) && this === this.server.relay_server.session) { - console.info("relay server disconnected: " + this.server.relay_server.address); - return delete this.server.relay_server; - } - }; + this.disconnected = (function(_this) { + return function() { + if ((_this.server.relay_server != null) && _this === _this.server.relay_server.session) { + console.info("relay server disconnected: " + _this.server.relay_server.address); + return delete _this.server.relay_server; + } + }; + })(this); return console.info("relay server available: " + msg.address); } - } + }; - getRelayServer(msg) { + Session.prototype.getRelayServer = function(msg) { if (!this.server.config.delegate_relay_service) { return this.send({ name: "get_relay_server", @@ -2273,9 +2415,9 @@ this.Session = class Session { }); } } - } + }; - getServerToken(msg) { + Session.prototype.getServerToken = function(msg) { var chars, i, id, j, manager, owner, project, token, user, value; if (!msg.user_token) { return; @@ -2322,9 +2464,9 @@ this.Session = class Session { } } } - } + }; - serverTokensCleanup() { + Session.prototype.serverTokensCleanup = function() { var key, ref, value; if (this.server.server_tokens != null) { ref = this.server.server_tokens; @@ -2335,25 +2477,27 @@ this.Session = class Session { } } } - } + }; - checkServerToken(msg) { + Session.prototype.checkServerToken = function(msg) { this.serverTokensCleanup(); if (msg.token == null) { return; } - return this.serverTokenCheck(msg.token, msg.server_id, () => { - return this.send({ - name: "check_server_token", - server_id: msg.server_id, - token: msg.token, - valid: true, - request_id: msg.request_id - }); - }); - } + return this.serverTokenCheck(msg.token, msg.server_id, (function(_this) { + return function() { + return _this.send({ + name: "check_server_token", + server_id: msg.server_id, + token: msg.token, + valid: true, + request_id: msg.request_id + }); + }; + })(this)); + }; - serverTokenCheck(token, server_id, callback) { + Session.prototype.serverTokenCheck = function(token, server_id, callback) { var t; if (this.server.server_tokens != null) { t = this.server.server_tokens[token]; @@ -2362,9 +2506,9 @@ this.Session = class Session { return callback(); } } - } + }; - uploadRequest(msg) { + Session.prototype.uploadRequest = function(msg) { if (this.user == null) { return; } @@ -2380,7 +2524,7 @@ this.Session = class Session { if (!this.server.rate_limiter.accept("file_upload_user", this.user.id)) { return this.sendError("Rate limited", msg.request_id); } - if (msg.size > 100000000) { // 100 Mb max + if (msg.size > 100000000) { return this.sendError("File size limit exceeded"); } this.upload_request_id = msg.request_id; @@ -2393,9 +2537,9 @@ this.Session = class Session { name: "upload_request", request_id: msg.request_id }); - } + }; - bufferReceived(buffer) { + Session.prototype.bufferReceived = function(buffer) { var b, buf, c, count, error, id, j, len, len1, msg, ref; if (buffer.byteLength >= 4) { id = buffer.readInt32LE(0); @@ -2439,9 +2583,9 @@ this.Session = class Session { } } } - } + }; - checkPassword(user, password) { + Session.prototype.checkPassword = function(user, password) { var h, hash, s; if ((user != null) && (user.hash != null)) { hash = user.hash; @@ -2452,9 +2596,9 @@ this.Session = class Session { } } return false; - } + }; - deleteAccount(msg) { + Session.prototype.deleteAccount = function(msg) { if (!this.user) { return; } @@ -2470,10 +2614,9 @@ this.Session = class Session { if (!this.checkPassword(this.user, msg.password)) { return this.sendError("Wrong password", msg.request_id); } - // DELETE USER console.info("DELETING USER: " + this.user.nick); this.server.stats.inc("account_deletion"); - this.user.delete(); + this.user["delete"](); delete this.server.content.users_by_nick[this.user.nick]; delete this.server.content.users_by_email[this.user.email]; this.user.setFlag("validated", false); @@ -2487,8 +2630,10 @@ this.Session = class Session { request_id: msg.request_id }); return this.socket.close(); - } + }; + + return Session; -}; +})(); module.exports = this.Session; diff --git a/server/webapp.coffee b/server/webapp.coffee index ab97bb49..18d2210a 100644 --- a/server/webapp.coffee +++ b/server/webapp.coffee @@ -44,7 +44,7 @@ class @WebApp if i==@languages.length-1 home_exp += "|" - @reserved = ["explore","documentation","projects","about","login","user","tutorials\\/examples",,"tutorials\\/community"] + @reserved = ["explore","documentation","projects","about","login","user","tutorials\\/examples","tutorials\\/community"] @reserved_exact = ["tutorials"] for r in @reserved diff --git a/server/webapp.js b/server/webapp.js index bf7d5c5b..07cb306f 100644 --- a/server/webapp.js +++ b/server/webapp.js @@ -1,5 +1,5 @@ var API, Concatenator, ExportFeatures, Fonts, ForumApp, Jimp, ProjectManager, SHA256, allowedTags, fs, pug, sanitizeHTML, - indexOf = [].indexOf; + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; SHA256 = require("crypto-js/sha256"); @@ -27,19 +27,17 @@ sanitizeHTML = require("sanitize-html"); allowedTags = sanitizeHTML.defaults.allowedTags.concat(["img"]); -this.WebApp = class WebApp { - constructor(server, app) { +this.WebApp = (function() { + function WebApp(server, app) { var home_exp, i, j, k, len, len1, len2, m, n, plugin, r, ref, ref1, ref2, ref3; this.server = server; this.app = app; this.code = ""; - fs.readFile("../templates/play/manifest.json", (err, data) => { - return this.manifest_template = data; - }); - //@app.get /^\/[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*\/[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/,(req,res)=> - // redir = req.protocol+'://' + req.get('host') + req.url+"/" - // console.info "redirecting to: "+redir - // redir = res.redirect(redir) + fs.readFile("../templates/play/manifest.json", (function(_this) { + return function(err, data) { + return _this.manifest_template = data; + }; + })(this)); this.forum_app = new ForumApp(this.server, this); this.api = new API(this.server, this); this.concatenator = new Concatenator(this); @@ -50,115 +48,115 @@ this.WebApp = class WebApp { this.languages = ["en", "fr", "pl", "de", "it", "pt", "ru", "es"]; home_exp = "^(\\/"; for (i = j = 1, ref = this.languages.length - 1; j <= ref; i = j += 1) { - home_exp += `|\\/${this.languages[i]}\\/?`; + home_exp += "|\\/" + this.languages[i] + "\\/?"; if (i === this.languages.length - 1) { home_exp += "|"; } } - this.reserved = ["explore", "documentation", "projects", "about", "login", "user", "tutorials\\/examples", , "tutorials\\/community"]; + this.reserved = ["explore", "documentation", "projects", "about", "login", "user", "tutorials\\/examples", "tutorials\\/community"]; this.reserved_exact = ["tutorials"]; ref1 = this.reserved; for (k = 0, len = ref1.length; k < len; k++) { r = ref1[k]; - home_exp += `\\/${r}|\\/${r}\\/.*|`; + home_exp += "\\/" + r + "|\\/" + r + "\\/.*|"; } ref2 = this.reserved_exact; for (m = 0, len1 = ref2.length; m < len1; m++) { r = ref2[m]; - home_exp += `\\/${r}|\\/${r}\\/|`; + home_exp += "\\/" + r + "|\\/" + r + "\\/|"; } home_exp += "\\/tutorial\\/[^\\/\\|\\?\\&\\.]+\\/[^\\/\\|\\?\\&\\.]+(\\/([^\\/\\|\\?\\&\\.]+\\/?)?)|"; home_exp += "(\\/i\\/.*))$"; - console.info(`home_exp = ${home_exp}`); - this.app.get(new RegExp(home_exp), (req, res) => { - var dev_domain, l, lang, len2, n, page, project, ref3, run_domain, s, translator, user; - if (this.ensureDevArea(req, res)) { - return; - } - dev_domain = this.server.config.dev_domain ? `'${this.server.config.dev_domain}'` : "location.origin"; - run_domain = this.server.config.run_domain ? `'${this.server.config.run_domain}'` : "location.origin.replace('.dev','.io')"; - lang = this.getLanguage(req); - ref3 = this.languages; - for (n = 0, len2 = ref3.length; n < len2; n++) { - l = ref3[n]; - if (req.path === `/${l}` || req.path === `/${l}/`) { - lang = l; + console.info("home_exp = " + home_exp); + this.app.get(new RegExp(home_exp), (function(_this) { + return function(req, res) { + var dev_domain, l, lang, len2, n, page, project, ref3, run_domain, s, translator, user; + if (_this.ensureDevArea(req, res)) { + return; } - } - //console.info "language=#{lang}" - if ((this.home_funk == null) || !this.server.use_cache) { - this.home_funk = pug.compileFile("../templates/home.pug"); - } - if ((this.server.content.translator.languages[lang] != null) && this.server.content.translator.languages[lang].updated) { - this.server.content.translator.languages[lang].updated = false; - delete this.home_page[lang]; - } - s = req.path.split("/"); - if (s[1] === "i") { - user = s[2]; - project = s[3]; - user = this.server.content.findUserByNick(user); - if (user == null) { - this.return404(req, res); - return null; + dev_domain = _this.server.config.dev_domain ? "'" + _this.server.config.dev_domain + "'" : "location.origin"; + run_domain = _this.server.config.run_domain ? "'" + _this.server.config.run_domain + "'" : "location.origin.replace('.dev','.io')"; + lang = _this.getLanguage(req); + ref3 = _this.languages; + for (n = 0, len2 = ref3.length; n < len2; n++) { + l = ref3[n]; + if (req.path === ("/" + l) || req.path === ("/" + l + "/")) { + lang = l; + } } - project = user.findProjectBySlug(project); - if ((project == null) || !project.public) { - this.return404(req, res); - return null; + if ((_this.home_funk == null) || !_this.server.use_cache) { + _this.home_funk = pug.compileFile("../templates/home.pug"); } - translator = this.server.content.translator.getTranslator(lang); - page = this.home_funk({ - name: project.title, - javascript_files: this.concatenator.getHomeJSFiles(), - css_files: this.concatenator.getHomeCSSFiles(), - translator: translator, - language: lang, - standalone: this.server.config.standalone === true, - languages: this.languages, - graphics_options: this.concatenator.alt_players, - optional_libs: this.concatenator.optional_libs, - language_engines: this.concatenator.language_engines, - translation: this.server.content.translator.languages[lang] != null ? this.server.content.translator.languages[lang].export() : "{}", - title: translator.get("%PROJECT% - by %USER%").replace("%PROJECT%", project.title).replace("%USER%", user.nick), - description: project.description, - long_description: project.description, - poster: (project.files != null) && (project.files["sprites/poster.png"] != null) ? `https://microstudio.io/${user.nick}/${project.slug}/sprites/poster.png` : `https://microstudio.io/${user.nick}/${project.slug}/sprites/icon.png`, - project_moderation: this.server.config.project_moderation === true, - dev_domain: dev_domain, - run_domain: run_domain, - default_project_language: this.server.config.default_project_language, - tutorials_root_url: this.server.config.tutorials_root_url - }); - return res.send(page); - } else if ((this.home_page[lang] == null) || !this.server.use_cache) { - //console.info "generating home page #{lang}" - translator = this.server.content.translator.getTranslator(lang); - this.home_page[lang] = this.home_funk({ - name: "microStudio", - javascript_files: this.concatenator.getHomeJSFiles(), - css_files: this.concatenator.getHomeCSSFiles(), - translator: translator, - language: lang, - standalone: this.server.config.standalone === true, - languages: this.languages, - graphics_options: this.concatenator.alt_players, - optional_libs: this.concatenator.optional_libs, - language_engines: this.concatenator.language_engines, - translation: this.server.content.translator.languages[lang] != null ? this.server.content.translator.languages[lang].export() : "{}", - title: "microStudio - " + translator.get("Game Engine"), - description: translator.get("microStudio is a free, open source game engine, code centric, integrated, available in the cloud or offline."), - long_description: translator.get("microStudio is a free, open source game engine, easy to learn and packed with features. It offers 4 programming languages and includes a sprite editor and a map editor."), - poster: "https://microstudio.dev/img/microstudio.jpg", - project_moderation: this.server.config.project_moderation === true, - dev_domain: dev_domain, - run_domain: run_domain, - default_project_language: this.server.config.default_project_language, - tutorials_root_url: this.server.config.tutorials_root_url - }); - } - return res.send(this.home_page[lang]); - }); + if ((_this.server.content.translator.languages[lang] != null) && _this.server.content.translator.languages[lang].updated) { + _this.server.content.translator.languages[lang].updated = false; + delete _this.home_page[lang]; + } + s = req.path.split("/"); + if (s[1] === "i") { + user = s[2]; + project = s[3]; + user = _this.server.content.findUserByNick(user); + if (user == null) { + _this.return404(req, res); + return null; + } + project = user.findProjectBySlug(project); + if ((project == null) || !project["public"]) { + _this.return404(req, res); + return null; + } + translator = _this.server.content.translator.getTranslator(lang); + page = _this.home_funk({ + name: project.title, + javascript_files: _this.concatenator.getHomeJSFiles(), + css_files: _this.concatenator.getHomeCSSFiles(), + translator: translator, + language: lang, + standalone: _this.server.config.standalone === true, + languages: _this.languages, + graphics_options: _this.concatenator.alt_players, + optional_libs: _this.concatenator.optional_libs, + language_engines: _this.concatenator.language_engines, + translation: _this.server.content.translator.languages[lang] != null ? _this.server.content.translator.languages[lang]["export"]() : "{}", + title: translator.get("%PROJECT% - by %USER%").replace("%PROJECT%", project.title).replace("%USER%", user.nick), + description: project.description, + long_description: project.description, + poster: (project.files != null) && (project.files["sprites/poster.png"] != null) ? "https://microstudio.io/" + user.nick + "/" + project.slug + "/sprites/poster.png" : "https://microstudio.io/" + user.nick + "/" + project.slug + "/sprites/icon.png", + project_moderation: _this.server.config.project_moderation === true, + dev_domain: dev_domain, + run_domain: run_domain, + default_project_language: _this.server.config.default_project_language, + tutorials_root_url: _this.server.config.tutorials_root_url + }); + return res.send(page); + } else if ((_this.home_page[lang] == null) || !_this.server.use_cache) { + translator = _this.server.content.translator.getTranslator(lang); + _this.home_page[lang] = _this.home_funk({ + name: "microStudio", + javascript_files: _this.concatenator.getHomeJSFiles(), + css_files: _this.concatenator.getHomeCSSFiles(), + translator: translator, + language: lang, + standalone: _this.server.config.standalone === true, + languages: _this.languages, + graphics_options: _this.concatenator.alt_players, + optional_libs: _this.concatenator.optional_libs, + language_engines: _this.concatenator.language_engines, + translation: _this.server.content.translator.languages[lang] != null ? _this.server.content.translator.languages[lang]["export"]() : "{}", + title: "microStudio - " + translator.get("Game Engine"), + description: translator.get("microStudio is a free, open source game engine, code centric, integrated, available in the cloud or offline."), + long_description: translator.get("microStudio is a free, open source game engine, easy to learn and packed with features. It offers 4 programming languages and includes a sprite editor and a map editor."), + poster: "https://microstudio.dev/img/microstudio.jpg", + project_moderation: _this.server.config.project_moderation === true, + dev_domain: dev_domain, + run_domain: run_domain, + default_project_language: _this.server.config.default_project_language, + tutorials_root_url: _this.server.config.tutorials_root_url + }); + } + return res.send(_this.home_page[lang]); + }; + })(this)); ref3 = this.server.plugins; for (n = 0, len2 = ref3.length; n < len2; n++) { plugin = ref3[n]; @@ -166,550 +164,571 @@ this.WebApp = class WebApp { plugin.addWebHooks(this.app); } } - this.app.get(/^\/discord\/?$/, (req, res) => { - return res.redirect("https://discord.gg/nEMpBU7"); - }); - // email validation - this.app.get(/^\/v\/\d+\/[a-z0-9A-Z]+\/?$/, (req, res, next) => { - var redir, s, token, user, userid; - //console.info "matched email validation" - if (this.ensureDevArea(req, res)) { - return; - } - s = req.path.split("/"); - userid = s[2]; - token = s[3]; - //console.info "userid = #{userid}" - //console.info "token = #{token}" - user = this.server.content.users[userid]; - if (user != null) { - this.server.content.validateEMailAddress(user, token); - redir = req.protocol + '://' + req.get("host"); - //console.info "redirecting to: "+redir - return res.redirect(redir); - } - return this.return404(req, res); - }); - // password recovery 1 - this.app.get(/^\/pw\/\d+\/[a-z0-9A-Z]+\/?$/, (req, res, next) => { - var page, s, token, user, userid; - //console.info "matched email validation" - if (this.ensureDevArea(req, res)) { - return; - } - s = req.path.split("/"); - userid = s[2]; - token = s[3]; - //console.info "userid = #{userid}" - //console.info "token = #{token}" - user = this.server.content.users[userid]; - if ((user != null) && user.getValidationToken() === token) { - page = pug.compileFile("../templates/password/reset1.pug"); - return res.send(page({ - userid: userid, - token: token + this.app.get(/^\/discord\/?$/, (function(_this) { + return function(req, res) { + return res.redirect("https://discord.gg/nEMpBU7"); + }; + })(this)); + this.app.get(/^\/v\/\d+\/[a-z0-9A-Z]+\/?$/, (function(_this) { + return function(req, res, next) { + var redir, s, token, user, userid; + if (_this.ensureDevArea(req, res)) { + return; + } + s = req.path.split("/"); + userid = s[2]; + token = s[3]; + user = _this.server.content.users[userid]; + if (user != null) { + _this.server.content.validateEMailAddress(user, token); + redir = req.protocol + '://' + req.get("host"); + return res.redirect(redir); + } + return _this.return404(req, res); + }; + })(this)); + this.app.get(/^\/pw\/\d+\/[a-z0-9A-Z]+\/?$/, (function(_this) { + return function(req, res, next) { + var page, s, token, user, userid; + if (_this.ensureDevArea(req, res)) { + return; + } + s = req.path.split("/"); + userid = s[2]; + token = s[3]; + user = _this.server.content.users[userid]; + if ((user != null) && user.getValidationToken() === token) { + page = pug.compileFile("../templates/password/reset1.pug"); + return res.send(page({ + userid: userid, + token: token + })); + } else { + return _this.return404(req, res); + } + }; + })(this)); + this.app.get(/^\/pwd\/\d+\/[a-z0-9A-Z]+\/.*\/?$/, (function(_this) { + return function(req, res, next) { + var chars, hash, o, page, pass, s, salt, token, translator, user, userid; + if (_this.ensureDevArea(req, res)) { + return; + } + s = req.path.split("/"); + userid = s[2]; + token = s[3]; + pass = s[4]; + console.info("userid = " + userid); + console.info("token = " + token); + user = _this.server.content.users[userid]; + if ((user != null) && user.getValidationToken() === token) { + salt = ""; + chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + for (i = o = 0; o <= 15; i = o += 1) { + salt += chars.charAt(Math.floor(Math.random() * chars.length)); + } + hash = salt + "|" + SHA256(salt + pass); + user.set("hash", hash); + user.resetValidationToken(); + translator = _this.server.content.translator.getTranslator(user.language); + user.notify(translator.get("Your password was successfully changed")); + page = pug.compileFile("../templates/password/reset2.pug"); + return res.send(page({})); + } else { + return _this.return404(req, res); + } + }; + })(this)); + this.app.get(/^\/lang\/list\/?$/, (function(_this) { + return function(req, res) { + if (_this.ensureDevArea(req, res)) { + return; + } + res.setHeader("Content-Type", "application/json"); + return res.send(JSON.stringify(_this.server.content.translator.list)); + }; + })(this)); + this.app.get(/^\/lang\/[a-z]+\/?$/, (function(_this) { + return function(req, res) { + var lang; + if (_this.ensureDevArea(req, res)) { + return; + } + lang = req.path.split("/")[2]; + lang = _this.server.content.translator.languages[lang]; + res.setHeader("Content-Type", "application/json"); + if (lang != null) { + return res.send(lang["export"]()); + } else { + return res.send("{}"); + } + }; + })(this)); + this.app.get(/^\/box\/?$/, (function(_this) { + return function(req, res) { + if (_this.ensureIOArea(req, res)) { + return; + } + _this.console_funk = pug.compileFile("../templates/console/console.pug"); + return res.send(_this.console_funk({ + gamelist: _this.server.content.getConsoleGameList() })); - } else { - return this.return404(req, res); - } - }); - // password recovery 2 - this.app.get(/^\/pwd\/\d+\/[a-z0-9A-Z]+\/.*\/?$/, (req, res, next) => { - var chars, hash, o, page, pass, s, salt, token, translator, user, userid; - //console.info "matched email validation" - if (this.ensureDevArea(req, res)) { - return; - } - s = req.path.split("/"); - userid = s[2]; - token = s[3]; - pass = s[4]; - console.info(`userid = ${userid}`); - console.info(`token = ${token}`); - user = this.server.content.users[userid]; - if ((user != null) && user.getValidationToken() === token) { - salt = ""; - chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - for (i = o = 0; o <= 15; i = o += 1) { - salt += chars.charAt(Math.floor(Math.random() * chars.length)); - } - hash = salt + "|" + SHA256(salt + pass); - user.set("hash", hash); - user.resetValidationToken(); - translator = this.server.content.translator.getTranslator(user.language); - user.notify(translator.get("Your password was successfully changed")); - page = pug.compileFile("../templates/password/reset2.pug"); - return res.send(page({})); - } else { - return this.return404(req, res); - } - }); - this.app.get(/^\/lang\/list\/?$/, (req, res) => { - if (this.ensureDevArea(req, res)) { - return; - } - res.setHeader("Content-Type", "application/json"); - return res.send(JSON.stringify(this.server.content.translator.list)); - }); - this.app.get(/^\/lang\/[a-z]+\/?$/, (req, res) => { - var lang; - if (this.ensureDevArea(req, res)) { - return; - } - lang = req.path.split("/")[2]; - lang = this.server.content.translator.languages[lang]; - res.setHeader("Content-Type", "application/json"); - if (lang != null) { - return res.send(lang.export()); - } else { - return res.send("{}"); - } - }); - this.app.get(/^\/box\/?$/, (req, res) => { - if (this.ensureIOArea(req, res)) { - return; - } - //if not @console_funk? or not @server.use_cache - this.console_funk = pug.compileFile("../templates/console/console.pug"); - return res.send(this.console_funk({ - gamelist: this.server.content.getConsoleGameList() - })); - }); - // /user/project[/code/] - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+\/?)?)?$/, (req, res) => { - var access, encoding, file, jsfiles, l, len3, lib, manager, o, pathcode, poster, prog_lang, project, redir, ref4, user; - if ((req.query != null) && (req.query.server != null)) { - if (this.ensureDevArea(req, res)) { + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+\/?)?)?$/, (function(_this) { + return function(req, res) { + var access, encoding, file, jsfiles, l, len3, lib, manager, o, pathcode, poster, prog_lang, project, redir, ref4, user; + if ((req.query != null) && (req.query.server != null)) { + if (_this.ensureDevArea(req, res)) { + return; + } + return _this.serverBox(req, res); + } + if (_this.ensureIOArea(req, res)) { return; } - return this.serverBox(req, res); - } - if (this.ensureIOArea(req, res)) { - return; - } - if (req.path.charAt(req.path.length - 1) !== "/") { - redir = req.protocol + '://' + req.get("host") + req.url + "/"; - console.info("redirecting to: " + redir); - return res.redirect(redir); - } - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - file = `${user.id}/${project.id}/ms/main.ms`; - encoding = "text"; - manager = this.getProjectManager(project); - if ((req.query != null) && (req.query.srv != null)) { - jsfiles = this.concatenator.getServerJSFiles(); - } else { - jsfiles = this.concatenator.getPlayerJSFiles(project.graphics); - } - ref4 = project.libs; - for (o = 0, len3 = ref4.length; o < len3; o++) { - lib = ref4[o]; - l = this.concatenator.findOptionalLib(lib); - if (l) { - jsfiles.push(l.lib); + if (req.path.charAt(req.path.length - 1) !== "/") { + redir = req.protocol + '://' + req.get("host") + req.url + "/"; + console.info("redirecting to: " + redir); + return res.redirect(redir); } - } - prog_lang = project.language; - if (this.concatenator.language_engines[prog_lang] != null) { - jsfiles = jsfiles.concat(this.concatenator.language_engines[prog_lang].scripts); - jsfiles = jsfiles.concat(this.concatenator.language_engines[prog_lang].lib); - } - pathcode = project.public ? project.slug : `${project.slug}/${project.code}`; - poster = (project.files != null) && (project.files["sprites/poster.png"] != null) ? `https://microstudio.io/${user.nick}/${pathcode}/sprites/poster.png` : `https://microstudio.io/${user.nick}/${pathcode}/icon512.png`; - if (this.server.config.player_extra_js != null) { - jsfiles = jsfiles.concat(this.server.config.player_extra_js); - } - return manager.listFiles("ms", (sources) => { - return manager.listFiles("sprites", (sprites) => { - return manager.listFiles("maps", (maps) => { - return manager.listFiles("sounds", (sounds) => { - return manager.listFiles("music", (music) => { - return manager.listFiles("assets", (assets) => { - var pf, resources; - resources = JSON.stringify({ - sources: sources, - images: sprites, - maps: maps, - sounds: sounds, - music: music, - assets: assets - }); - resources = `var resources = ${resources};\n`; - if ((req.query != null) && (req.query.srv != null)) { - if ((this.server_funk == null) || !this.server.use_cache) { - this.server_funk = pug.compileFile("../templates/play/server.pug"); - } - pf = this.server_funk; - } else { - if ((this.play_funk == null) || !this.server.use_cache) { - this.play_funk = pug.compileFile("../templates/play/play.pug"); - } - pf = this.play_funk; - } - return res.send(pf({ - user: user, - javascript_files: jsfiles, - fonts: this.fonts.fonts, - debug: (req.query != null) && (req.query.debug != null), - server: (req.query != null) && (req.query.srv != null), - language: project.language, - translator: this.server.content.translator.getTranslator(this.getLanguage(req)), - game: { - name: project.slug, - pathcode: pathcode, - title: project.title, - author: user.nick, - resources: resources, - orientation: project.orientation, - aspect: project.aspect, - graphics: project.graphics, - networking: project.networking || false, - libs: JSON.stringify(project.libs), - description: project.description, - poster: poster + access = _this.getProjectAccess(req, res); + if (access == null) { + return; + } + user = access.user; + project = access.project; + file = user.id + "/" + project.id + "/ms/main.ms"; + encoding = "text"; + manager = _this.getProjectManager(project); + if ((req.query != null) && (req.query.srv != null)) { + jsfiles = _this.concatenator.getServerJSFiles(); + } else { + jsfiles = _this.concatenator.getPlayerJSFiles(project.graphics); + } + ref4 = project.libs; + for (o = 0, len3 = ref4.length; o < len3; o++) { + lib = ref4[o]; + l = _this.concatenator.findOptionalLib(lib); + if (l) { + jsfiles.push(l.lib); + } + } + prog_lang = project.language; + if (_this.concatenator.language_engines[prog_lang] != null) { + jsfiles = jsfiles.concat(_this.concatenator.language_engines[prog_lang].scripts); + jsfiles = jsfiles.concat(_this.concatenator.language_engines[prog_lang].lib); + } + pathcode = project["public"] ? project.slug : project.slug + "/" + project.code; + poster = (project.files != null) && (project.files["sprites/poster.png"] != null) ? "https://microstudio.io/" + user.nick + "/" + pathcode + "/sprites/poster.png" : "https://microstudio.io/" + user.nick + "/" + pathcode + "/icon512.png"; + if (_this.server.config.player_extra_js != null) { + jsfiles = jsfiles.concat(_this.server.config.player_extra_js); + } + return manager.listFiles("ms", function(sources) { + return manager.listFiles("sprites", function(sprites) { + return manager.listFiles("maps", function(maps) { + return manager.listFiles("sounds", function(sounds) { + return manager.listFiles("music", function(music) { + return manager.listFiles("assets", function(assets) { + var pf, resources; + resources = JSON.stringify({ + sources: sources, + images: sprites, + maps: maps, + sounds: sounds, + music: music, + assets: assets + }); + resources = "var resources = " + resources + ";\n"; + if ((req.query != null) && (req.query.srv != null)) { + if ((_this.server_funk == null) || !_this.server.use_cache) { + _this.server_funk = pug.compileFile("../templates/play/server.pug"); + } + pf = _this.server_funk; + } else { + if ((_this.play_funk == null) || !_this.server.use_cache) { + _this.play_funk = pug.compileFile("../templates/play/play.pug"); + } + pf = _this.play_funk; } - })); + return res.send(pf({ + user: user, + javascript_files: jsfiles, + fonts: _this.fonts.fonts, + debug: (req.query != null) && (req.query.debug != null), + server: (req.query != null) && (req.query.srv != null), + language: project.language, + translator: _this.server.content.translator.getTranslator(_this.getLanguage(req)), + game: { + name: project.slug, + pathcode: pathcode, + title: project.title, + author: user.nick, + resources: resources, + orientation: project.orientation, + aspect: project.aspect, + graphics: project.graphics, + networking: project.networking || false, + libs: JSON.stringify(project.libs), + description: project.description, + poster: poster + } + })); + }); }); }); }); }); }); - }); - }); - this.app.get(/^\/[A-Za-z0-9_]+\/?$/, (req, res) => { - if (this.ensureIOArea(req, res)) { - return; - } - return this.getUserPublicPage(req, res); - }); - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/manifest.json$/, (req, res) => { - var access, iconversion, manager, mani, path, project, s, user; - if (this.ensureIOArea(req, res)) { - return; - } - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - manager = this.getProjectManager(project); - iconversion = manager.getFileVersion("sprites/icon.png"); - path = project.public ? `/${user.nick}/${project.slug}/` : `/${user.nick}/${project.slug}/${project.code}/`; - res.setHeader("Content-Type", "application/json"); - s = req.path.split("/"); - mani = this.manifest_template.toString().replace(/SCOPE/g, path); - mani = mani.toString().replace("APPNAME", project.title); - mani = mani.toString().replace("APPSHORTNAME", project.title); - mani = mani.toString().replace("ORIENTATION", project.orientation); - mani = mani.toString().replace(/USER/g, user.nick); - mani = mani.toString().replace(/PROJECT/g, project.slug); - mani = mani.toString().replace(/ICONVERSION/g, iconversion); - mani = mani.replace("START_URL", path); - return res.send(mani); - }); - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/sw.js$/, (req, res) => { - var access, project, user; - if (this.ensureIOArea(req, res)) { - return; - } - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - return fs.readFile("../static/sw.js", (err, data) => { - res.setHeader("Content-Type", "application/javascript"); - return res.send(data); - }); - }); - // User Profile Image - this.app.get(/^\/[^\/\|\?\&\.]+.png$/, (req, res) => { - var path, s, user; - s = req.path.split("/"); - user = s[1].split(".")[0]; - user = this.server.content.findUserByNick(user); - if ((user == null) || !user.flags.profile_image) { - this.return404(req, res); - return null; - } - path = `${user.id}/profile_image.png`; - return this.server.content.files.read(path, "binary", (content) => { - if (content != null) { - res.setHeader("Content-Type", "image/png"); - return res.send(content); - } else { - this.return404(req, res); + }; + })(this)); + this.app.get(/^\/[A-Za-z0-9_]+\/?$/, (function(_this) { + return function(req, res) { + if (_this.ensureIOArea(req, res)) { + return; + } + return _this.getUserPublicPage(req, res); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/manifest.json$/, (function(_this) { + return function(req, res) { + var access, iconversion, manager, mani, path, project, s, user; + if (_this.ensureIOArea(req, res)) { + return; + } + access = _this.getProjectAccess(req, res); + if (access == null) { + return; + } + user = access.user; + project = access.project; + manager = _this.getProjectManager(project); + iconversion = manager.getFileVersion("sprites/icon.png"); + path = project["public"] ? "/" + user.nick + "/" + project.slug + "/" : "/" + user.nick + "/" + project.slug + "/" + project.code + "/"; + res.setHeader("Content-Type", "application/json"); + s = req.path.split("/"); + mani = _this.manifest_template.toString().replace(/SCOPE/g, path); + mani = mani.toString().replace("APPNAME", project.title); + mani = mani.toString().replace("APPSHORTNAME", project.title); + mani = mani.toString().replace("ORIENTATION", project.orientation); + mani = mani.toString().replace(/USER/g, user.nick); + mani = mani.toString().replace(/PROJECT/g, project.slug); + mani = mani.toString().replace(/ICONVERSION/g, iconversion); + mani = mani.replace("START_URL", path); + return res.send(mani); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/sw.js$/, (function(_this) { + return function(req, res) { + var access, project, user; + if (_this.ensureIOArea(req, res)) { + return; + } + access = _this.getProjectAccess(req, res); + if (access == null) { + return; + } + user = access.user; + project = access.project; + return fs.readFile("../static/sw.js", function(err, data) { + res.setHeader("Content-Type", "application/javascript"); + return res.send(data); + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+.png$/, (function(_this) { + return function(req, res) { + var path, s, user; + s = req.path.split("/"); + user = s[1].split(".")[0]; + user = _this.server.content.findUserByNick(user); + if ((user == null) || !user.flags.profile_image) { + _this.return404(req, res); return null; } - }); - }); - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/icon[0-9]+.png$/, (req, res) => { - var access, path, project, size, user; - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - size = req.path.split("icon"); - size = size[size.length - 1]; - size = Math.min(1024, size.split(".")[0] | 0); - path = `${user.id}/${project.id}/sprites/icon.png`; - path = this.server.content.files.folder + "/" + this.server.content.files.sanitize(path); - return Jimp.read(path, (err, img) => { - if (err) { - console.error(err); + path = user.id + "/profile_image.png"; + return _this.server.content.files.read(path, "binary", function(content) { + if (content != null) { + res.setHeader("Content-Type", "image/png"); + return res.send(content); + } else { + _this.return404(req, res); + return null; + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/icon[0-9]+.png$/, (function(_this) { + return function(req, res) { + var access, path, project, size, user; + access = _this.getProjectAccess(req, res); + if (access == null) { return; } - return img.resize(size, size, Jimp.RESIZE_NEAREST_NEIGHBOR).getBuffer(Jimp.MIME_PNG, (err, buffer) => { + user = access.user; + project = access.project; + size = req.path.split("icon"); + size = size[size.length - 1]; + size = Math.min(1024, size.split(".")[0] | 0); + path = user.id + "/" + project.id + "/sprites/icon.png"; + path = _this.server.content.files.folder + "/" + _this.server.content.files.sanitize(path); + return Jimp.read(path, function(err, img) { if (err) { console.error(err); return; } - res.setHeader("Content-Type", "image/png"); - return res.send(buffer); + return img.resize(size, size, Jimp.RESIZE_NEAREST_NEIGHBOR).getBuffer(Jimp.MIME_PNG, function(err, buffer) { + if (err) { + console.error(err); + return; + } + res.setHeader("Content-Type", "image/png"); + return res.send(buffer); + }); }); - }); - }); - // source files for player - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/ms\/[A-Za-z0-9_-]+.ms$/, (req, res) => { - var access, ms, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - ms = s[s.length - 1]; - return this.server.content.files.read(`${user.id}/${project.id}/ms/${ms}`, "text", (content) => { - if (content != null) { - res.setHeader("Content-Type", "application/javascript"); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/ms\/[A-Za-z0-9_-]+.ms$/, (function(_this) { + return function(req, res) { + var access, ms, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // asset thumbnail - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/(assets_th|sounds_th|music_th)\/[A-Za-z0-9_-]+.png$/, (req, res) => { - var access, asset, folder, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - folder = s[s.length - 2]; - asset = s[s.length - 1]; - //console.info "loading #{user.id}/#{project.id}/#{folder}/#{asset}" - return this.server.content.files.read(`${user.id}/${project.id}/${folder}/${asset}`, "binary", (content) => { - if (content != null) { - res.setHeader("Content-Type", "image/png"); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + user = access.user; + project = access.project; + ms = s[s.length - 1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/ms/" + ms, "text", function(content) { + if (content != null) { + res.setHeader("Content-Type", "application/javascript"); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/(assets_th|sounds_th|music_th)\/[A-Za-z0-9_-]+.png$/, (function(_this) { + return function(req, res) { + var access, asset, folder, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // image files for player ; should be deprecated in favor of /sprites/ - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/[A-Za-z0-9_]+.png$/, (req, res) => { - var access, image, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - image = s[s.length - 1]; - return this.server.content.files.read(`${user.id}/${project.id}/sprites/${image}`, "binary", (content) => { - if (content != null) { - res.setHeader("Content-Type", "image/png"); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + user = access.user; + project = access.project; + folder = s[s.length - 2]; + asset = s[s.length - 1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/" + folder + "/" + asset, "binary", function(content) { + if (content != null) { + res.setHeader("Content-Type", "image/png"); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/[A-Za-z0-9_]+.png$/, (function(_this) { + return function(req, res) { + var access, image, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // image files for player and all - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/sprites\/[A-Za-z0-9_-]+.png$/, (req, res) => { - var access, image, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - image = s[s.length - 1]; - return this.server.content.files.read(`${user.id}/${project.id}/sprites/${image}`, "binary", (content) => { - if (content != null) { - res.setHeader("Content-Type", "image/png"); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + user = access.user; + project = access.project; + image = s[s.length - 1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/sprites/" + image, "binary", function(content) { + if (content != null) { + res.setHeader("Content-Type", "image/png"); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/sprites\/[A-Za-z0-9_-]+.png$/, (function(_this) { + return function(req, res) { + var access, image, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // map files for player - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/maps\/[A-Za-z0-9_-]+.json$/, (req, res) => { - var access, map, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - map = s[s.length - 1]; - return this.server.content.files.read(`${user.id}/${project.id}/maps/${map}`, "text", (content) => { - if (content != null) { - res.setHeader("Content-Type", "application/json"); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + user = access.user; + project = access.project; + image = s[s.length - 1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/sprites/" + image, "binary", function(content) { + if (content != null) { + res.setHeader("Content-Type", "image/png"); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/maps\/[A-Za-z0-9_-]+.json$/, (function(_this) { + return function(req, res) { + var access, map, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // sound files for player and all - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/sounds\/[A-Za-z0-9_-]+.(wav|ogg|flac)$/, (req, res) => { - var access, ext, project, s, sound, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - sound = s[s.length - 1]; - ext = sound.split(".")[1]; - return this.server.content.files.read(`${user.id}/${project.id}/sounds/${sound}`, "binary", (content) => { - if (content != null) { - res.setHeader("Content-Type", `audio/${ext}`); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + user = access.user; + project = access.project; + map = s[s.length - 1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/maps/" + map, "text", function(content) { + if (content != null) { + res.setHeader("Content-Type", "application/json"); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/sounds\/[A-Za-z0-9_-]+.(wav|ogg|flac)$/, (function(_this) { + return function(req, res) { + var access, ext, project, s, sound, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // music files for player and all - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/music\/[A-Za-z0-9_-]+.(mp3|ogg|flac)$/, (req, res) => { - var access, ext, music, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - music = s[s.length - 1]; - ext = music.split(".")[1]; - return this.server.content.files.read(`${user.id}/${project.id}/music/${music}`, "binary", (content) => { - if (content != null) { - res.setHeader("Content-Type", `audio/${ext}`); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + user = access.user; + project = access.project; + sound = s[s.length - 1]; + ext = sound.split(".")[1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/sounds/" + sound, "binary", function(content) { + if (content != null) { + res.setHeader("Content-Type", "audio/" + ext); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/music\/[A-Za-z0-9_-]+.(mp3|ogg|flac)$/, (function(_this) { + return function(req, res) { + var access, ext, music, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // asset files - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/assets\/[A-Za-z0-9_-]+.(glb|obj|jpg|png|ttf|txt|csv|json|md)$/, (req, res) => { - var access, asset, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - asset = s[s.length - 1]; - return this.server.content.files.read(`${user.id}/${project.id}/assets/${asset}`, "binary", (content) => { - if (content != null) { - switch (asset.split(".")[1]) { - case "glb": - res.setHeader("Content-Type", "model/gltf-binary"); - break; - case "obj": - res.setHeader("Content-Type", "model/gltf-binary"); - break; - case "jpg": - res.setHeader("Content-Type", "image/jpg"); - break; - case "png": - res.setHeader("Content-Type", "image/png"); - break; - case "ttf": - res.setHeader("Content-Type", "application/font-sfnt"); - break; - case "txt": - res.setHeader("Content-Type", "text/plain"); - break; - case "csv": - res.setHeader("Content-Type", "text/csv"); - break; - case "json": - res.setHeader("Content-Type", "application/json"); + user = access.user; + project = access.project; + music = s[s.length - 1]; + ext = music.split(".")[1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/music/" + music, "binary", function(content) { + if (content != null) { + res.setHeader("Content-Type", "audio/" + ext); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); } - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/assets\/[A-Za-z0-9_-]+.(glb|obj|jpg|png|ttf|txt|csv|json|md)$/, (function(_this) { + return function(req, res) { + var access, asset, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - // doc files - this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/doc\/[A-Za-z0-9_]+.md$/, (req, res) => { - var access, doc, project, s, user; - s = req.path.split("/"); - access = this.getProjectAccess(req, res); - if (access == null) { - return; - } - user = access.user; - project = access.project; - doc = s[s.length - 1]; - return this.server.content.files.read(`${user.id}/${project.id}/doc/${doc}`, "text", (content) => { - if (content != null) { - res.setHeader("Content-Type", "text/markdown"); - return res.send(content); - } else { - console.info(`couldn't read file: ${req.path}`); - return res.status(404).send("Error 404"); + user = access.user; + project = access.project; + asset = s[s.length - 1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/assets/" + asset, "binary", function(content) { + if (content != null) { + switch (asset.split(".")[1]) { + case "glb": + res.setHeader("Content-Type", "model/gltf-binary"); + break; + case "obj": + res.setHeader("Content-Type", "model/gltf-binary"); + break; + case "jpg": + res.setHeader("Content-Type", "image/jpg"); + break; + case "png": + res.setHeader("Content-Type", "image/png"); + break; + case "ttf": + res.setHeader("Content-Type", "application/font-sfnt"); + break; + case "txt": + res.setHeader("Content-Type", "text/plain"); + break; + case "csv": + res.setHeader("Content-Type", "text/csv"); + break; + case "json": + res.setHeader("Content-Type", "application/json"); + } + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.get(/^\/[^\/\|\?\&\.]+\/[^\/\|\?\&\.]+(\/([^\/\|\?\&\.]+)?)?\/doc\/[A-Za-z0-9_]+.md$/, (function(_this) { + return function(req, res) { + var access, doc, project, s, user; + s = req.path.split("/"); + access = _this.getProjectAccess(req, res); + if (access == null) { + return; } - }); - }); - this.app.use((req, res) => { - return this.return404(req, res); - }); + user = access.user; + project = access.project; + doc = s[s.length - 1]; + return _this.server.content.files.read(user.id + "/" + project.id + "/doc/" + doc, "text", function(content) { + if (content != null) { + res.setHeader("Content-Type", "text/markdown"); + return res.send(content); + } else { + console.info("couldn't read file: " + req.path); + return res.status(404).send("Error 404"); + } + }); + }; + })(this)); + this.app.use((function(_this) { + return function(req, res) { + return _this.return404(req, res); + }; + })(this)); } - return404(req, res) { + WebApp.prototype.return404 = function(req, res) { if ((this.err404_funk == null) || !this.server.use_cache) { this.err404_funk = pug.compileFile("../templates/404.pug"); } return res.status(404).send(this.err404_funk({})); - } + }; - ensureDevArea(req, res) { + WebApp.prototype.ensureDevArea = function(req, res) { var host, redir; - //console.info req.get("host") if (req.get("host").indexOf(".io") > 0) { host = req.get("host").replace(".io", ".dev"); redir = req.protocol + '://' + host + req.url; @@ -719,11 +738,10 @@ this.WebApp = class WebApp { } else { return false; } - } + }; - ensureIOArea(req, res) { + WebApp.prototype.ensureIOArea = function(req, res) { var host, redir; - //console.info req.get("host") if (req.get("host").indexOf(".dev") > 0) { host = req.get("host").replace(".dev", ".io"); redir = req.protocol + '://' + host + req.url; @@ -733,9 +751,9 @@ this.WebApp = class WebApp { } else { return false; } - } + }; - serverBox(req, res) { + WebApp.prototype.serverBox = function(req, res) { var access, host, pathcode, project, server_url, user; access = this.getProjectAccess(req, res); if (access == null) { @@ -743,7 +761,7 @@ this.WebApp = class WebApp { } user = access.user; project = access.project; - pathcode = project.public ? project.slug : `${project.slug}/${project.code}`; + pathcode = project["public"] ? project.slug : project.slug + "/" + project.code; if ((this.serverbox_funk == null) || !this.server.use_cache) { this.serverbox_funk = pug.compileFile("../templates/play/serverbox.pug"); } @@ -765,9 +783,9 @@ this.WebApp = class WebApp { description: project.description } })); - } + }; - getUserPublicPage(req, res) { + WebApp.prototype.getUserPublicPage = function(req, res) { var achievements, displayNumber, dxp, funk, j, key, lang, len, level, list, map, percent, projects, s, stat_list, stats, translator, unit, user, value, xp, xp1, xp2; s = req.path.split("/"); user = s[1]; @@ -853,9 +871,9 @@ this.WebApp = class WebApp { translator: this.server.content.translator.getTranslator(lang), language: lang })); - } + }; - getLanguage(request) { + WebApp.prototype.getLanguage = function(request) { var lang; if (request.cookies.language != null) { lang = request.cookies.language; @@ -871,9 +889,9 @@ this.WebApp = class WebApp { lang = "en"; } return lang; - } + }; - getProjectAccess(req, res) { + WebApp.prototype.getProjectAccess = function(req, res) { var code, project, s, user; s = req.path.split("/"); user = s[1]; @@ -889,7 +907,7 @@ this.WebApp = class WebApp { this.return404(req, res); return null; } - if (project.public || project.code === code) { + if (project["public"] || project.code === code) { return { user: user, project: project @@ -897,16 +915,16 @@ this.WebApp = class WebApp { } res.send("Project does not exist"); return null; - } + }; - getProjectManager(project) { + WebApp.prototype.getProjectManager = function(project) { if (project.manager == null) { new ProjectManager(project); } return project.manager; - } + }; - roundRect(context, x, y, w, h, r) { + WebApp.prototype.roundRect = function(context, x, y, w, h, r) { if (w < 2 * r) { r = w / 2; } @@ -920,13 +938,15 @@ this.WebApp = class WebApp { context.arcTo(x, y + h, x, y, r); context.arcTo(x, y, x + w, y, r); return context.closePath(); - } + }; - fillRoundRect(context, x, y, w, h, r) { + WebApp.prototype.fillRoundRect = function(context, x, y, w, h, r) { this.roundRect(context, x, y, w, h, r); return context.fill(); - } + }; + + return WebApp; -}; +})(); module.exports = this.WebApp; diff --git a/static/js/about/about.js b/static/js/about/about.js index 8cae1140..a0759695 100644 --- a/static/js/about/about.js +++ b/static/js/about/about.js @@ -1,5 +1,5 @@ -this.About = class About { - constructor(app) { +this.About = (function() { + function About(app) { this.app = app; this.current = "about"; this.loaded = {}; @@ -7,39 +7,43 @@ this.About = class About { this.init(); } - init() { + About.prototype.init = function() { var i, len, ref, results, s; ref = this.sections; results = []; for (i = 0, len = ref.length; i < len; i++) { s = ref[i]; - results.push(((s) => { - return document.getElementById(`about-menu-${s}`).addEventListener("click", () => { - return this.setSection(s); - }); - })(s)); + results.push((function(_this) { + return function(s) { + return document.getElementById("about-menu-" + s).addEventListener("click", function() { + return _this.setSection(s); + }); + }; + })(this)(s)); } return results; - } + }; - setSection(section) { + About.prototype.setSection = function(section) { var i, len, ref, s; this.current = section; ref = this.sections; for (i = 0, len = ref.length; i < len; i++) { s = ref[i]; if (s === section) { - document.getElementById(`about-menu-${s}`).classList.add("selected"); + document.getElementById("about-menu-" + s).classList.add("selected"); } else { - document.getElementById(`about-menu-${s}`).classList.remove("selected"); + document.getElementById("about-menu-" + s).classList.remove("selected"); } } - return this.load(section, (text) => { - return this.update(text); - }); - } + return this.load(section, (function(_this) { + return function(text) { + return _this.update(text); + }; + })(this)); + }; - load(section, callback) { + About.prototype.load = function(section, callback) { var ref, req; if (this.loaded[section] != null) { if (callback != null) { @@ -48,25 +52,27 @@ this.About = class About { return; } req = new XMLHttpRequest(); - req.onreadystatechange = (event) => { - if (req.readyState === XMLHttpRequest.DONE) { - if (req.status === 200) { - this.loaded[section] = req.responseText; - if (callback != null) { - return callback(this.loaded[section]); + req.onreadystatechange = (function(_this) { + return function(event) { + if (req.readyState === XMLHttpRequest.DONE) { + if (req.status === 200) { + _this.loaded[section] = req.responseText; + if (callback != null) { + return callback(_this.loaded[section]); + } } } - } - }; + }; + })(this); if (((ref = this.app.translator.lang) === "fr" || ref === "it" || ref === "pt") && section !== "changelog") { - req.open("GET", location.origin + `/doc/${this.app.translator.lang}/${section}.md`); + req.open("GET", location.origin + ("/doc/" + this.app.translator.lang + "/" + section + ".md")); } else { - req.open("GET", location.origin + `/doc/en/${section}.md`); + req.open("GET", location.origin + ("/doc/en/" + section + ".md")); } return req.send(); - } + }; - update(doc) { + About.prototype.update = function(doc) { var e, element, i, len, list; element = document.getElementById("about-content"); element.innerHTML = DOMPurify.sanitize(marked(doc)); @@ -75,6 +81,8 @@ this.About = class About { e = list[i]; e.target = "_blank"; } - } + }; + + return About; -}; +})(); diff --git a/static/js/app.js b/static/js/app.js index d2e6e7a3..1cd2e5a3 100644 --- a/static/js/app.js +++ b/static/js/app.js @@ -6,8 +6,8 @@ window.addEventListener("load", function() { return app = new App(); }); -App = class App { - constructor() { +App = (function() { + function App() { this.languages = { microscript2: LANGUAGE_MICROSCRIPT2, microscript: LANGUAGE_MICROSCRIPT, @@ -44,40 +44,42 @@ App = class App { this.client.start(); } - setToken(token, username) { + App.prototype.setToken = function(token, username) { this.token = token; this.username = username; return this.client.setToken(this.token); - } + }; - createGuest() { + App.prototype.createGuest = function() { return this.client.sendRequest({ name: "create_guest", language: window.navigator.language != null ? window.navigator.language.substring(0, 2) : "en" - }, (msg) => { - switch (msg.name) { - case "error": - console.error(msg.error); - if (msg.error != null) { - return alert(this.translator.get(msg.error)); - } - break; - case "guest_created": - this.setToken(msg.token); - this.nick = msg.nick; - this.user = { - nick: msg.nick, - flags: msg.flags, - settings: msg.settings, - info: msg.info - }; - this.connected = true; - return this.userConnected(msg.nick); - } - }); - } + }, (function(_this) { + return function(msg) { + switch (msg.name) { + case "error": + console.error(msg.error); + if (msg.error != null) { + return alert(_this.translator.get(msg.error)); + } + break; + case "guest_created": + _this.setToken(msg.token); + _this.nick = msg.nick; + _this.user = { + nick: msg.nick, + flags: msg.flags, + settings: msg.settings, + info: msg.info + }; + _this.connected = true; + return _this.userConnected(msg.nick); + } + }; + })(this)); + }; - createAccount(nick, email, password, newsletter) { + App.prototype.createAccount = function(nick, email, password, newsletter) { return this.client.sendRequest({ name: "create_account", nick: nick, @@ -85,85 +87,91 @@ App = class App { password: password, newsletter: newsletter, language: window.navigator.language != null ? window.navigator.language.substring(0, 2) : "en" - }, (msg) => { - switch (msg.name) { - case "error": - console.error(msg.error); - if (msg.error != null) { - return alert(this.translator.get(msg.error)); - } - break; - case "account_created": - this.setToken(msg.token); - this.nick = nick; - this.user = { - nick: msg.nick, - email: msg.email, - flags: msg.flags, - settings: msg.settings, - info: msg.info - }; - this.connected = true; - return this.userConnected(nick); - } - }); - } + }, (function(_this) { + return function(msg) { + switch (msg.name) { + case "error": + console.error(msg.error); + if (msg.error != null) { + return alert(_this.translator.get(msg.error)); + } + break; + case "account_created": + _this.setToken(msg.token); + _this.nick = nick; + _this.user = { + nick: msg.nick, + email: msg.email, + flags: msg.flags, + settings: msg.settings, + info: msg.info + }; + _this.connected = true; + return _this.userConnected(nick); + } + }; + })(this)); + }; - login(nick, password) { + App.prototype.login = function(nick, password) { return this.client.sendRequest({ name: "login", nick: nick, password: password - }, (msg) => { - var i, len, n, ref; - switch (msg.name) { - case "error": - console.error(msg.error); - if (msg.error != null) { - return alert(this.translator.get(msg.error)); - } - break; - case "logged_in": - this.setToken(msg.token); - this.nick = msg.nick; - this.user = { - nick: msg.nick, - email: msg.email, - flags: msg.flags, - settings: msg.settings, - info: msg.info - }; - if ((msg.notifications != null) && msg.notifications.length > 0) { - ref = msg.notifications; - for (i = 0, len = ref.length; i < len; i++) { - n = ref[i]; - this.appui.showNotification(n); + }, (function(_this) { + return function(msg) { + var i, len, n, ref; + switch (msg.name) { + case "error": + console.error(msg.error); + if (msg.error != null) { + return alert(_this.translator.get(msg.error)); } - } - this.connected = true; - this.userConnected(msg.nick); - return this.appui.showNotification(this.translator.get("Welcome back!")); - } - }); - } + break; + case "logged_in": + _this.setToken(msg.token); + _this.nick = msg.nick; + _this.user = { + nick: msg.nick, + email: msg.email, + flags: msg.flags, + settings: msg.settings, + info: msg.info + }; + if ((msg.notifications != null) && msg.notifications.length > 0) { + ref = msg.notifications; + for (i = 0, len = ref.length; i < len; i++) { + n = ref[i]; + _this.appui.showNotification(n); + } + } + _this.connected = true; + _this.userConnected(msg.nick); + return _this.appui.showNotification(_this.translator.get("Welcome back!")); + } + }; + })(this)); + }; - sendPasswordRecovery(email) { + App.prototype.sendPasswordRecovery = function(email) { if (!RegexLib.email.test(email)) { return alert(this.translator.get("incorrect email")); } else { return this.client.sendRequest({ name: "send_password_recovery", email: email - }, (msg) => { - document.getElementById("forgot-password-panel").innerHTML = this.translator.get("Thank you. Please check your mail."); - return setTimeout((() => { - return this.appui.hide("login-overlay"); - }), 5000); - }); + }, (function(_this) { + return function(msg) { + document.getElementById("forgot-password-panel").innerHTML = _this.translator.get("Thank you. Please check your mail."); + return setTimeout((function() { + return _this.appui.hide("login-overlay"); + }), 5000); + }; + })(this)); } - } + }; - createProject(title, slug, options, callback) { + App.prototype.createProject = function(title, slug, options, callback) { if ((options != null) && typeof options === "function" && (callback == null)) { callback = options; options = { @@ -179,111 +187,120 @@ App = class App { language: options.language, networking: options.networking, libs: options.libs - }, (msg) => { - switch (msg.name) { - case "error": - console.error(msg.error); - if (msg.error != null) { - alert(this.translator.get(msg.error)); - } - break; - case "project_created": - this.getProjectList((list) => { - var i, len, p, results; - this.projects = list; - this.appui.updateProjects(); - results = []; - for (i = 0, len = list.length; i < len; i++) { - p = list[i]; - if (p.id === msg.id) { - this.openProject(p); - if (callback != null) { - results.push(callback()); + }, (function(_this) { + return function(msg) { + switch (msg.name) { + case "error": + console.error(msg.error); + if (msg.error != null) { + alert(_this.translator.get(msg.error)); + } + break; + case "project_created": + _this.getProjectList(function(list) { + var i, len, p, results; + _this.projects = list; + _this.appui.updateProjects(); + results = []; + for (i = 0, len = list.length; i < len; i++) { + p = list[i]; + if (p.id === msg.id) { + _this.openProject(p); + if (callback != null) { + results.push(callback()); + } else { + results.push(void 0); + } } else { results.push(void 0); } - } else { - results.push(void 0); } - } - return results; - }); - } - }); - } + return results; + }); + } + }; + })(this)); + }; - importProject(file) { + App.prototype.importProject = function(file) { var reader; if (this.importing) { return; } - console.info(`importing ${file.name}`); + console.info("importing " + file.name); reader = new FileReader(); - reader.addEventListener("load", () => { - // return if not reader.result.startsWith("data:application/x-zip-compressed;base64,") - // mime-type returned by browser may vary ; let's just check ZIP extension - if (!file.name.toLowerCase().endsWith(".zip")) { - return; - } - this.importing = true; - return this.client.sendUpload({ - name: "import_project" - }, reader.result, ((msg) => { - console.log(`[ZIP] ${msg.name}`); - switch (msg.name) { - case "error": - this.appui.showNotification(this.translator.get(msg.error)); - this.appui.resetImportButton(); - return this.importing = false; - case "project_imported": - this.updateProjectList(msg.id); - this.appui.showNotification(this.translator.get("Project imported successfully")); - this.appui.resetImportButton(); - this.importing = false; - this.tab_manager.resetPlugins(); - return this.lib_manager.resetLibs(); + reader.addEventListener("load", (function(_this) { + return function() { + if (!file.name.toLowerCase().endsWith(".zip")) { + return; } - }), (progress) => { - return this.appui.setImportProgress(progress); - }); - }); + _this.importing = true; + return _this.client.sendUpload({ + name: "import_project" + }, reader.result, (function(msg) { + console.log("[ZIP] " + msg.name); + switch (msg.name) { + case "error": + _this.appui.showNotification(_this.translator.get(msg.error)); + _this.appui.resetImportButton(); + return _this.importing = false; + case "project_imported": + _this.updateProjectList(msg.id); + _this.appui.showNotification(_this.translator.get("Project imported successfully")); + _this.appui.resetImportButton(); + _this.importing = false; + _this.tab_manager.resetPlugins(); + return _this.lib_manager.resetLibs(); + } + }), function(progress) { + return _this.appui.setImportProgress(progress); + }); + }; + })(this)); return reader.readAsArrayBuffer(file); - } - - updateProjectList(open_when_fetched) { - return this.getProjectList((list) => { - var i, len, p, ref, results; - this.projects = list; - this.appui.updateProjects(); - if (open_when_fetched != null) { - ref = this.projects; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - p = ref[i]; - if (p.id === open_when_fetched) { - this.openProject(p); - break; - } else { - results.push(void 0); + }; + + App.prototype.updateProjectList = function(open_when_fetched) { + return this.getProjectList((function(_this) { + return function(list) { + var i, len, p, ref, results; + _this.projects = list; + _this.appui.updateProjects(); + if (open_when_fetched != null) { + ref = _this.projects; + results = []; + for (i = 0, len = ref.length; i < len; i++) { + p = ref[i]; + if (p.id === open_when_fetched) { + _this.openProject(p); + break; + } else { + results.push(void 0); + } } + return results; } - return results; - } - }); - } + }; + })(this)); + }; - getProjectList(callback) { + App.prototype.getProjectList = function(callback) { return this.client.sendRequest({ name: "get_project_list" - }, (msg) => { - if (callback != null) { - return callback(msg.list); - } - }); - } + }, (function(_this) { + return function(msg) { + if (callback != null) { + return callback(msg.list); + } + }; + })(this)); + }; - openProject(project, useraction = true) { + App.prototype.openProject = function(project, useraction) { var t, tuto; + if (useraction == null) { + useraction = true; + } this.project = new Project(this, project); this.appui.setProject(this.project, useraction); this.editor.setCode(""); @@ -305,21 +322,25 @@ App = class App { tuto = this.getProjectTutorial(project.slug); if (tuto != null) { t = new Tutorial(tuto); - return t.load(() => { - return this.tutorial.start(t); - }); + return t.load((function(_this) { + return function() { + return _this.tutorial.start(t); + }; + })(this)); } } - } + }; - deleteProject(project) { + App.prototype.deleteProject = function(project) { if (project.owner.nick === this.nick) { return this.client.sendRequest({ name: "delete_project", project: project.id - }, (msg) => { - return this.updateProjectList(); - }); + }, (function(_this) { + return function(msg) { + return _this.updateProjectList(); + }; + })(this)); } else { return this.client.sendRequest({ name: "remove_project_user", @@ -327,9 +348,9 @@ App = class App { user: this.nick }); } - } + }; - projectTitleExists(title) { + App.prototype.projectTitleExists = function(title) { var i, len, p, ref; if (!this.projects) { return false; @@ -342,84 +363,87 @@ App = class App { } } return false; - } + }; - cloneProject(project) { + App.prototype.cloneProject = function(project) { var count, title; - title = project.title + ` (${this.translator.get("copy")})`; + title = project.title + (" (" + (this.translator.get("copy")) + ")"); count = 1; while (this.projectTitleExists(title)) { count += 1; - title = project.title + ` (${this.translator.get("copy")} ${count})`; + title = project.title + (" (" + (this.translator.get("copy")) + " " + count + ")"); } return this.client.sendRequest({ name: "clone_project", project: project.id, title: title - }, (msg) => { - this.appui.setMainSection("projects"); - this.appui.backToProjectList(); - this.updateProjectList(); - return this.appui.showNotification(this.translator.get("Project cloned! Here is your copy.")); - }); - } + }, (function(_this) { + return function(msg) { + _this.appui.setMainSection("projects"); + _this.appui.backToProjectList(); + _this.updateProjectList(); + return _this.appui.showNotification(_this.translator.get("Project cloned! Here is your copy.")); + }; + })(this)); + }; - writeProjectFile(project_id, file, content, callback) { + App.prototype.writeProjectFile = function(project_id, file, content, callback) { return this.client.sendRequest({ name: "write_project_file", project: project_id, file: file, content: content - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - readProjectFile(project_id, file, callback) { + App.prototype.readProjectFile = function(project_id, file, callback) { return this.client.sendRequest({ name: "read_project_file", project: project_id, file: file - }, (msg) => { - return callback(msg.content); - }); - } + }, (function(_this) { + return function(msg) { + return callback(msg.content); + }; + })(this)); + }; - //listProjectFiles:(project_id,folder,callback)-> - // @client.sendRequest { - // name:"list_project_files" - // project: project_id - // folder: folder - // },(msg)=> - // callback msg.content - userConnected(nick) { + App.prototype.userConnected = function(nick) { this.appui.userConnected(nick); this.updateProjectList(); this.user_settings.update(); return this.user_progress.init(); - } + }; - disconnect() { + App.prototype.disconnect = function() { if ((this.user.email == null) || this.user.flags.guest) { return this.client.sendRequest({ name: "delete_guest" - }, (msg) => { - this.setToken(null); - return location.reload(); - }); + }, (function(_this) { + return function(msg) { + _this.setToken(null); + return location.reload(); + }; + })(this)); } else { this.setToken(null); return location.reload(); } - } + }; - fetchPublicProjects() { + App.prototype.fetchPublicProjects = function() { return this.client.sendRequest({ name: "get_public_projects", ranking: "hot", tags: [] - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - serverMessage(msg) { + App.prototype.serverMessage = function(msg) { switch (msg.name) { case "project_user_list": return this.updateProjectUserList(msg); @@ -465,24 +489,24 @@ App = class App { case "show_error": return this.appui.showNotification(this.translator.get(msg.error)); } - } + }; - updateProjectUserList(msg) { + App.prototype.updateProjectUserList = function(msg) { if ((this.project != null) && msg.project === this.project.id) { this.project.users = msg.users; return this.options.updateUserList(); } - } + }; - getUserSetting(setting) { + App.prototype.getUserSetting = function(setting) { if ((this.user != null) && (this.user.settings != null)) { return this.user.settings[setting]; } else { return null; } - } + }; - setUserSetting(setting, value) { + App.prototype.setUserSetting = function(setting, value) { if (this.user != null) { if (this.user.settings == null) { this.user.settings = {}; @@ -492,11 +516,13 @@ App = class App { name: "set_user_setting", setting: setting, value: value - }, (msg) => {}); + }, (function(_this) { + return function(msg) {}; + })(this)); } - } + }; - setTutorialProgress(tutorial_id, progress) { + App.prototype.setTutorialProgress = function(tutorial_id, progress) { var tutorial_progress; tutorial_progress = this.getUserSetting("tutorial_progress"); if (tutorial_progress == null) { @@ -504,9 +530,9 @@ App = class App { } tutorial_progress[tutorial_id] = progress; return this.setUserSetting("tutorial_progress", tutorial_progress); - } + }; - getTutorialProgress(tutorial_id) { + App.prototype.getTutorialProgress = function(tutorial_id) { var tutorial_progress; tutorial_progress = this.getUserSetting("tutorial_progress"); if (tutorial_progress == null) { @@ -514,9 +540,9 @@ App = class App { } else { return tutorial_progress[tutorial_id] || 0; } - } + }; - setProjectTutorial(project_slug, tutorial_id) { + App.prototype.setProjectTutorial = function(project_slug, tutorial_id) { var project_tutorial; project_tutorial = this.getUserSetting("project_tutorial"); if (project_tutorial == null) { @@ -524,9 +550,9 @@ App = class App { } project_tutorial[project_slug] = tutorial_id; return this.setUserSetting("project_tutorial", project_tutorial); - } + }; - getProjectTutorial(slug) { + App.prototype.getProjectTutorial = function(slug) { var project_tutorial; project_tutorial = this.getUserSetting("project_tutorial"); if (project_tutorial == null) { @@ -534,19 +560,19 @@ App = class App { } else { return project_tutorial[slug]; } - } + }; - setHomeState() { + App.prototype.setHomeState = function() { if (this.translator.lang !== "en") { - return history.replaceState(null, "microStudio", `/${this.translator.lang}/`); + return history.replaceState(null, "microStudio", "/" + this.translator.lang + "/"); } else { return history.replaceState(null, "microStudio", "/"); } - } + }; - setState(state) {} + App.prototype.setState = function(state) {}; - getTierName(tier) { + App.prototype.getTierName = function(tier) { switch (tier) { case "pixel_master": return "Pixel Master"; @@ -562,34 +588,36 @@ App = class App { return "Standard"; } return ""; - } + }; - openUserSettings() { + App.prototype.openUserSettings = function() { this.appui.setMainSection("usersettings"); this.user_settings.setSection("settings"); return this.app_state.pushState("user.settings", "/user/settings/"); - } + }; - openUserProfile() { + App.prototype.openUserProfile = function() { this.appui.setMainSection("usersettings"); this.user_settings.setSection("profile"); return this.app_state.pushState("user.profile", "/user/profile/"); - } + }; - openUserProgress() { + App.prototype.openUserProgress = function() { this.appui.setMainSection("usersettings"); this.user_settings.setSection("progress"); return this.app_state.pushState("user.progress", "/user/progress/"); - } + }; + + return App; -}; +})(); if (navigator.serviceWorker != null) { navigator.serviceWorker.register("/app_sw.js", { scope: location.pathname }).then(function(reg) { return console.log('Registration succeeded. Scope is' + reg.scope); - }).catch(function(error) { + })["catch"](function(error) { return console.log('Registration failed with' + error); }); } diff --git a/static/js/appstate.js b/static/js/appstate.js index 73d4313c..472deed0 100644 --- a/static/js/appstate.js +++ b/static/js/appstate.js @@ -1,20 +1,25 @@ -this.AppState = class AppState { - constructor(app) { +this.AppState = (function() { + function AppState(app) { this.app = app; - window.addEventListener("popstate", (event) => { - return this.popState(); - }); + window.addEventListener("popstate", (function(_this) { + return function(event) { + return _this.popState(); + }; + })(this)); } - pushState(name, path, obj = {}) { - console.info(`pushing state\nname=${name}\npath=${path}`); + AppState.prototype.pushState = function(name, path, obj) { + if (obj == null) { + obj = {}; + } + console.info("pushing state\nname=" + name + "\npath=" + path); if ((history.state != null) && history.state.name !== name) { obj.name = name; return history.pushState(obj, "", path); } - } + }; - popState() { + AppState.prototype.popState = function() { var i, len, p, project, ref, ref1, s; if (history.state != null) { s = history.state.name.split("."); @@ -105,17 +110,17 @@ this.AppState = class AppState { } } } - } + }; - stateInitialized() { + AppState.prototype.stateInitialized = function() { console.info("state initialized"); return this.app.documentation.stateInitialized(); - } + }; - initState() { + AppState.prototype.initState = function() { var i, len, p, path, project, ref, s, tab; if (location.pathname.startsWith("/login/")) { - path = this.app.translator.lang !== "en" ? `/${this.app.translator.lang}/` : "/"; + path = this.app.translator.lang !== "en" ? "/" + this.app.translator.lang + "/" : "/"; history.replaceState({ name: "home" }, "", path); @@ -132,7 +137,7 @@ this.AppState = class AppState { ref = ["about", "tutorials", "explore", "documentation"]; for (i = 0, len = ref.length; i < len; i++) { p = ref[i]; - if (location.pathname.startsWith(`/${p}/`) || location.pathname === `/${p}`) { + if (location.pathname.startsWith("/" + p + "/") || location.pathname === ("/" + p)) { history.replaceState({ name: p }, "", location.pathname); @@ -151,23 +156,25 @@ this.AppState = class AppState { if (path[2]) { this.app.tutorials.tutorials_page.setSection(path[2], false); history.replaceState({ - name: `tutorials.${path[2]}` + name: "tutorials." + path[2] }, "", location.pathname); if (path[2] === "examples") { if (path[3] && path[4]) { this.app.tutorials.tutorials_page.reloadExample(path[3], path[4]); history.replaceState({ - name: `tutorials.${path[2]}.${path[3]}.${path[4]}` + name: "tutorials." + path[2] + "." + path[3] + "." + path[4] }, "", location.pathname); } } } } - this.app.appui.setMainSection(((p) => { - return { - "documentation": "help" - }[p] || p; - })(p)); + this.app.appui.setMainSection(((function(_this) { + return function(p) { + return { + "documentation": "help" + }[p] || p; + }; + })(this))(p)); this.stateInitialized(); return; } @@ -178,7 +185,7 @@ this.AppState = class AppState { project = s[2]; tab = s[3]; history.replaceState({ - name: `project.${s[2]}.${s[3]}` + name: "project." + s[2] + "." + s[3] }, "", location.pathname); } else if (location.pathname.startsWith("/user/") && s[2]) { switch (s[2]) { @@ -201,7 +208,7 @@ this.AppState = class AppState { }, "", "/projects/"); } } else { - path = this.app.translator.lang !== "en" ? `/${this.app.translator.lang}/` : "/"; + path = this.app.translator.lang !== "en" ? "/" + this.app.translator.lang + "/" : "/"; history.replaceState({ name: "home" }, "", path); @@ -209,9 +216,9 @@ this.AppState = class AppState { } } return this.stateInitialized(); - } + }; - projectsFetched() { + AppState.prototype.projectsFetched = function() { var path, project, tuto, user; if ((history.state != null) && (history.state.name != null)) { if (history.state.name.startsWith("project.")) { @@ -226,24 +233,30 @@ this.AppState = class AppState { path.splice(path.length - 1, 1); } path = path.join("/"); - path = location.origin + `/${path}/doc/doc.md?v=${Date.now()}`; + path = location.origin + ("/" + path + "/doc/doc.md?v=" + (Date.now())); console.info(path); tuto = new Tutorial(path, false); - tuto.load(() => { - return this.app.tutorial.start(tuto); - }, (err) => { - console.info(err); - alert(this.app.translator.get("Tutorial not found")); - return history.replaceState({ - name: "home" - }, "", "/"); - }); - this.app.client.listen("project_file_updated", (msg) => { - if (msg.type === "doc" && msg.file === "doc") { - tuto.update(msg.data); - return this.app.tutorial.update(); - } - }); + tuto.load((function(_this) { + return function() { + return _this.app.tutorial.start(tuto); + }; + })(this), (function(_this) { + return function(err) { + console.info(err); + alert(_this.app.translator.get("Tutorial not found")); + return history.replaceState({ + name: "home" + }, "", "/"); + }; + })(this)); + this.app.client.listen("project_file_updated", (function(_this) { + return function(msg) { + if (msg.type === "doc" && msg.file === "doc") { + tuto.update(msg.data); + return _this.app.tutorial.update(); + } + }; + })(this)); user = location.pathname.split("/")[2]; project = location.pathname.split("/")[3]; return this.app.client.send({ @@ -252,6 +265,8 @@ this.AppState = class AppState { project: project }); } - } + }; + + return AppState; -}; +})(); diff --git a/static/js/appui/appui.js b/static/js/appui/appui.js index bf23c367..b3bf51af 100644 --- a/static/js/appui/appui.js +++ b/static/js/appui/appui.js @@ -1,66 +1,76 @@ var AppUI; -AppUI = class AppUI { - constructor(app1) { - var advanced, j, k, len, len1, ref, ref1, s; +AppUI = (function() { + function AppUI(app1) { + var advanced, fn, fn1, j, k, len, len1, ref, ref1, s; this.app = app1; this.sections = ["code", "sprites", "maps", "assets", "sounds", "music", "doc", "sync", "options", "publish", "tabs"]; this.menuoptions = ["home", "explore", "projects", "help", "tutorials", "about", "usersettings"]; ref = this.sections; - for (j = 0, len = ref.length; j < len; j++) { - s = ref[j]; - ((s) => { - if (document.getElementById(`menuitem-${s}`) != null) { - return document.getElementById(`menuitem-${s}`).addEventListener("click", (event) => { - return this.setSection(s, true); + fn = (function(_this) { + return function(s) { + if (document.getElementById("menuitem-" + s) != null) { + return document.getElementById("menuitem-" + s).addEventListener("click", function(event) { + return _this.setSection(s, true); }); } - })(s); + }; + })(this); + for (j = 0, len = ref.length; j < len; j++) { + s = ref[j]; + fn(s); } this.warning_messages = []; - document.addEventListener("keydown", (e) => { - if ((window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) && e.keyCode === 83) { - e.preventDefault(); - switch (this.current_section) { - case "code": - return this.app.editor.checkSave(true); - case "sprites": - return this.app.sprite_editor.checkSave(true); - case "maps": - return this.app.map_editor.checkSave(true); - case "doc": - return this.app.doc_editor.checkSave(true); - case "assets": - return this.app.assets_manager.text_viewer.checkSave(true); + document.addEventListener("keydown", (function(_this) { + return function(e) { + if ((window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) && e.keyCode === 83) { + e.preventDefault(); + switch (_this.current_section) { + case "code": + return _this.app.editor.checkSave(true); + case "sprites": + return _this.app.sprite_editor.checkSave(true); + case "maps": + return _this.app.map_editor.checkSave(true); + case "doc": + return _this.app.doc_editor.checkSave(true); + case "assets": + return _this.app.assets_manager.text_viewer.checkSave(true); + } } - } - }); + }; + })(this)); ref1 = this.menuoptions; - for (k = 0, len1 = ref1.length; k < len1; k++) { - s = ref1[k]; - ((s) => { + fn1 = (function(_this) { + return function(s) { var e; - e = document.getElementById(`menu-${s}`); + e = document.getElementById("menu-" + s); if (e != null) { - return e.addEventListener("click", (event) => { + return e.addEventListener("click", function(event) { if (window.ms_standalone && s === "explore") { return window.open("https://microstudio.dev/explore/", "_blank"); } else if (window.ms_standalone && s === "home") { return window.open("https://microstudio.dev", "_blank"); } else { - return this.setMainSection(s, true); + return _this.setMainSection(s, true); } }); } - })(s); + }; + })(this); + for (k = 0, len1 = ref1.length; k < len1; k++) { + s = ref1[k]; + fn1(s); } - this.setAction("logo", () => { - if (window.ms_standalone) { - return window.open("https://microstudio.dev", "_blank"); - } else { - return this.setMainSection("home", true); - } - }); + this.setAction("logo", (function(_this) { + return function() { + if (window.ms_standalone) { + return window.open("https://microstudio.dev", "_blank"); + } else { + return _this.setMainSection("home", true); + } + }; + })(this)); if (window.ms_standalone) { document.getElementById("menu-community").parentNode.href = "https://microstudio.dev/community/"; document.getElementById("projectoptions-users-content").style.display = "none"; @@ -71,89 +81,104 @@ AppUI = class AppUI { document.getElementById("usersetting-block-account-type").style.display = "none"; document.body.classList.add("standalone"); } - //@setSection("options") this.createLoginFunctions(); advanced = document.getElementById("advanced-create-project-options-button"); - this.setAction("create-project-button", () => { - this.show("create-project-overlay"); - this.focus("create-project-title"); - document.getElementById("createprojectoption-type").value = "app"; - document.getElementById("createprojectoption-language").value = window.ms_default_project_language || "microscript_v2"; - document.getElementById("createprojectoption-graphics").value = "M1"; - document.getElementById("createprojectoption-networking").checked = false; - document.getElementById("create-project-option-lib-matterjs").checked = false; - document.getElementById("create-project-option-lib-cannonjs").checked = false; - return this.hideAdvanced(); - }); - this.hideAdvanced = () => { - advanced.classList.remove("open"); - document.getElementById("advanced-create-project-options").style.display = "none"; - return advanced.childNodes[1].innerText = this.app.translator.get("Advanced"); - }; - advanced.addEventListener("click", () => { - if (advanced.classList.contains("open")) { - return this.hideAdvanced(); - } else { - advanced.classList.add("open"); - document.getElementById("advanced-create-project-options").style.display = "block"; - return advanced.childNodes[1].innerText = this.app.translator.get("Hide advanced options"); - } - }); - this.setAction("import-project-button", () => { - var input; - input = document.createElement("input"); - input.type = "file"; - input.accept = "application/zip"; - input.addEventListener("change", (event) => { - var f, files; - files = event.target.files; - if (files.length >= 1) { - f = files[0]; - return this.app.importProject(f); + this.setAction("create-project-button", (function(_this) { + return function() { + _this.show("create-project-overlay"); + _this.focus("create-project-title"); + document.getElementById("createprojectoption-type").value = "app"; + document.getElementById("createprojectoption-language").value = window.ms_default_project_language || "microscript_v2"; + document.getElementById("createprojectoption-graphics").value = "M1"; + document.getElementById("createprojectoption-networking").checked = false; + document.getElementById("create-project-option-lib-matterjs").checked = false; + document.getElementById("create-project-option-lib-cannonjs").checked = false; + return _this.hideAdvanced(); + }; + })(this)); + this.hideAdvanced = (function(_this) { + return function() { + advanced.classList.remove("open"); + document.getElementById("advanced-create-project-options").style.display = "none"; + return advanced.childNodes[1].innerText = _this.app.translator.get("Advanced"); + }; + })(this); + advanced.addEventListener("click", (function(_this) { + return function() { + if (advanced.classList.contains("open")) { + return _this.hideAdvanced(); + } else { + advanced.classList.add("open"); + document.getElementById("advanced-create-project-options").style.display = "block"; + return advanced.childNodes[1].innerText = _this.app.translator.get("Hide advanced options"); } - }); - return input.click(); - }); - this.setAction("home-action-explore", () => { - return this.setMainSection("explore"); - }); - this.setAction("home-action-create", () => { - return this.setMainSection("projects"); - }); - document.getElementById("create-project-overlay").addEventListener("mousedown", (event) => { - var b; - if (event.target !== document.getElementById("create-project-overlay")) { - return true; - } - b = document.getElementById("create-project-window").getBoundingClientRect(); - if (event.clientX < b.x || event.clientX > b.x + b.width || event.clientY < b.y || event.clientY > b.y + b.height) { - this.hide("create-project-overlay"); - } - return true; - }); - this.setAction("create-project-submit", () => { - var libs, slug, title; - title = this.get("create-project-title").value; - slug = RegexLib.slugify(title); - if (title.length > 0 && slug.length > 0) { - libs = []; - if (document.getElementById("create-project-option-lib-matterjs").checked) { - libs.push("matterjs"); + }; + })(this)); + this.setAction("import-project-button", (function(_this) { + return function() { + var input; + input = document.createElement("input"); + input.type = "file"; + input.accept = "application/zip"; + input.addEventListener("change", function(event) { + var f, files; + files = event.target.files; + if (files.length >= 1) { + f = files[0]; + return _this.app.importProject(f); + } + }); + return input.click(); + }; + })(this)); + this.setAction("home-action-explore", (function(_this) { + return function() { + return _this.setMainSection("explore"); + }; + })(this)); + this.setAction("home-action-create", (function(_this) { + return function() { + return _this.setMainSection("projects"); + }; + })(this)); + document.getElementById("create-project-overlay").addEventListener("mousedown", (function(_this) { + return function(event) { + var b; + if (event.target !== document.getElementById("create-project-overlay")) { + return true; } - if (document.getElementById("create-project-option-lib-cannonjs").checked) { - libs.push("cannonjs"); + b = document.getElementById("create-project-window").getBoundingClientRect(); + if (event.clientX < b.x || event.clientX > b.x + b.width || event.clientY < b.y || event.clientY > b.y + b.height) { + _this.hide("create-project-overlay"); } - this.app.createProject(title, slug, { - type: document.getElementById("createprojectoption-type").value, - language: document.getElementById("createprojectoption-language").value, - graphics: document.getElementById("createprojectoption-graphics").value, - networking: document.getElementById("createprojectoption-networking").checked, - libs: libs - }); - this.hide("create-project-overlay"); - return this.get("create-project-title").value = ""; - } - }); + return true; + }; + })(this)); + this.setAction("create-project-submit", (function(_this) { + return function() { + var libs, slug, title; + title = _this.get("create-project-title").value; + slug = RegexLib.slugify(title); + if (title.length > 0 && slug.length > 0) { + libs = []; + if (document.getElementById("create-project-option-lib-matterjs").checked) { + libs.push("matterjs"); + } + if (document.getElementById("create-project-option-lib-cannonjs").checked) { + libs.push("cannonjs"); + } + _this.app.createProject(title, slug, { + type: document.getElementById("createprojectoption-type").value, + language: document.getElementById("createprojectoption-language").value, + graphics: document.getElementById("createprojectoption-graphics").value, + networking: document.getElementById("createprojectoption-networking").checked, + libs: libs + }); + _this.hide("create-project-overlay"); + return _this.get("create-project-title").value = ""; + } + }; + })(this)); this.doc_splitbar = new SplitBar("doc-section", "horizontal"); this.doc_splitbar.auto = 1; this.code_splitbar = new SplitBar("code-section", "horizontal"); @@ -167,114 +192,138 @@ AppUI = class AppUI { this.debug_splitbar = new SplitBar("terminal-debug-container", "horizontal"); this.debug_splitbar.closed2 = true; this.debug_splitbar.splitbar_size = 12; - this.setAction("backtoprojects", () => { - if (this.app.project != null) { - return this.app.project.savePendingChanges(() => { - return this.backToProjectList(true); - }); - } else { - return this.backToProjectList(true); - } - }); - this.get("create_nick").addEventListener("input", () => { - var value; - value = this.get("create_nick").value; - if (value !== RegexLib.fixNick(value)) { - return this.get("create_nick").value = RegexLib.fixNick(value); - } - }); + this.setAction("backtoprojects", (function(_this) { + return function() { + if (_this.app.project != null) { + return _this.app.project.savePendingChanges(function() { + return _this.backToProjectList(true); + }); + } else { + return _this.backToProjectList(true); + } + }; + })(this)); + this.get("create_nick").addEventListener("input", (function(_this) { + return function() { + var value; + value = _this.get("create_nick").value; + if (value !== RegexLib.fixNick(value)) { + return _this.get("create_nick").value = RegexLib.fixNick(value); + } + }; + })(this)); this.startSaveStatus(); this.last_activity = Date.now(); - document.addEventListener("mousemove", () => { - return this.last_activity = Date.now(); - }); - document.addEventListener("keydown", () => { - return this.last_activity = Date.now(); - }); - document.querySelector("#projects-search input").addEventListener("input", () => { - var l, len2, len3, list, m, ok, p, results, results1, search; - search = document.querySelector("#projects-search input").value.toLowerCase(); - list = document.getElementById("project-list").childNodes; - if (search.trim().length > 0) { - results = []; - for (l = 0, len2 = list.length; l < len2; l++) { - p = list[l]; - if (p.dataset.title == null) { - continue; + document.addEventListener("mousemove", (function(_this) { + return function() { + return _this.last_activity = Date.now(); + }; + })(this)); + document.addEventListener("keydown", (function(_this) { + return function() { + return _this.last_activity = Date.now(); + }; + })(this)); + document.querySelector("#projects-search input").addEventListener("input", (function(_this) { + return function() { + var l, len2, len3, list, m, ok, p, results, results1, search; + search = document.querySelector("#projects-search input").value.toLowerCase(); + list = document.getElementById("project-list").childNodes; + if (search.trim().length > 0) { + results = []; + for (l = 0, len2 = list.length; l < len2; l++) { + p = list[l]; + if (p.dataset.title == null) { + continue; + } + ok = p.dataset.title.toLowerCase().indexOf(search) >= 0; + ok |= p.dataset.description.toLowerCase().indexOf(search) >= 0; + ok |= p.dataset.tags.toLowerCase().indexOf(search) >= 0; + ok |= p.dataset["public"] && "public".indexOf(search) >= 0; + if (ok) { + results.push(p.style.display = "inline-block"); + } else { + results.push(p.style.display = "none"); + } } - ok = p.dataset.title.toLowerCase().indexOf(search) >= 0; - ok |= p.dataset.description.toLowerCase().indexOf(search) >= 0; - ok |= p.dataset.tags.toLowerCase().indexOf(search) >= 0; - ok |= p.dataset.public && "public".indexOf(search) >= 0; - if (ok) { - results.push(p.style.display = "inline-block"); - } else { - results.push(p.style.display = "none"); + return results; + } else { + results1 = []; + for (m = 0, len3 = list.length; m < len3; m++) { + p = list[m]; + results1.push(p.style.display = "inline-block"); } + return results1; } - return results; - } else { - results1 = []; - for (m = 0, len3 = list.length; m < len3; m++) { - p = list[m]; - results1.push(p.style.display = "inline-block"); + }; + })(this)); + document.querySelector("#home-section").addEventListener("scroll", (function(_this) { + return function() { + var scroll; + scroll = Math.min(60, document.querySelector("#home-section").scrollTop); + return document.querySelector("#home-header-background").style.height = scroll + "px"; + }; + })(this)); + document.getElementById("myprojects").addEventListener("dragover", (function(_this) { + return function(event) { + return event.preventDefault(); + }; + })(this)); + document.getElementById("myprojects").addEventListener("drop", (function(_this) { + return function(event) { + event.preventDefault(); + if (event.dataTransfer.items && (event.dataTransfer.items[0] != null)) { + return _this.app.importProject(event.dataTransfer.items[0].getAsFile()); } - return results1; - } - }); - document.querySelector("#home-section").addEventListener("scroll", () => { - var scroll; - scroll = Math.min(60, document.querySelector("#home-section").scrollTop); - return document.querySelector("#home-header-background").style.height = `${scroll}px`; - }); - //document.querySelector("#home-section .part1").style["padding-top"] = "#{160-scroll}px" - document.getElementById("myprojects").addEventListener("dragover", (event) => { - return event.preventDefault(); - }); - document.getElementById("myprojects").addEventListener("drop", (event) => { - event.preventDefault(); - if (event.dataTransfer.items && (event.dataTransfer.items[0] != null)) { - return this.app.importProject(event.dataTransfer.items[0].getAsFile()); - } - }); + }; + })(this)); this.createFullscreenFeatures(); this.createProjectSideBarCollapse(); - setInterval((() => { - return this.checkActivity(); - }), 10000); + setInterval(((function(_this) { + return function() { + return _this.checkActivity(); + }; + })(this)), 10000); this.reboot_date = 1689163200000; this.checkRebootMessage(); } - checkRebootMessage() { + AppUI.prototype.checkRebootMessage = function() { var div, funk; if (this.reboot_date && Date.now() < this.reboot_date + 1000 * 60 * 2) { document.querySelector(".main-container").style.top = "100px"; div = document.createElement("div"); div.classList.add("meta-message"); - funk = () => { - var hours, minutes; - minutes = Math.max(0, this.reboot_date - Date.now()) / 60000; - if (minutes >= 120) { - hours = Math.floor(minutes / 60); - return div.innerHTML = " " + this.app.translator.get("microStudio will be down for server migration on %DATE% at %TIME%. Downtime will last a few minutes.").replace("%DATE%", new Date(this.reboot_date).toLocaleDateString()).replace("%TIME%", new Date(this.reboot_date).toLocaleTimeString()); - } else if (minutes >= 2) { - minutes = Math.floor(minutes); - return div.innerHTML = " " + this.app.translator.get("Downtime will start in %MINUTES% minutes").replace("%MINUTES%", minutes); - } else { - return div.innerHTML = " " + this.app.translator.get("Downtime will start immediately"); - } - }; + funk = (function(_this) { + return function() { + var hours, minutes; + minutes = Math.max(0, _this.reboot_date - Date.now()) / 60000; + if (minutes >= 120) { + hours = Math.floor(minutes / 60); + return div.innerHTML = " " + _this.app.translator.get("microStudio will be down for server migration on %DATE% at %TIME%. Downtime will last a few minutes.").replace("%DATE%", new Date(_this.reboot_date).toLocaleDateString()).replace("%TIME%", new Date(_this.reboot_date).toLocaleTimeString()); + } else if (minutes >= 2) { + minutes = Math.floor(minutes); + return div.innerHTML = " " + _this.app.translator.get("Downtime will start in %MINUTES% minutes").replace("%MINUTES%", minutes); + } else { + return div.innerHTML = " " + _this.app.translator.get("Downtime will start immediately"); + } + }; + })(this); funk(); - setInterval((() => { - return funk(); - }), 30000); + setInterval(((function(_this) { + return function() { + return funk(); + }; + })(this)), 30000); return document.body.appendChild(div); } - } + }; - addWarningMessage(text, icon = "fa-exclamation-circle", id, dismissable) { + AppUI.prototype.addWarningMessage = function(text, icon, id, dismissable) { var close, div, span; + if (icon == null) { + icon = "fa-exclamation-circle"; + } if (dismissable && (id != null)) { if (localStorage.getItem(id)) { return; @@ -283,49 +332,51 @@ AppUI = class AppUI { div = document.createElement("div"); div.classList.add("meta-message"); span = document.createElement("span"); - span.innerHTML = ` ${text}`; + span.innerHTML = " " + text; if (dismissable) { close = document.createElement("i"); close.classList.add("fa"); close.classList.add("fa-times"); - close.addEventListener("click", () => { - this.removeWarningMessage(div); - return localStorage.setItem(id, true); - }); + close.addEventListener("click", (function(_this) { + return function() { + _this.removeWarningMessage(div); + return localStorage.setItem(id, true); + }; + })(this)); div.appendChild(close); } div.appendChild(span); this.warning_messages.push(div); - document.querySelector(".main-container").style.top = `${60 + 40 * this.warning_messages.length}px`; + document.querySelector(".main-container").style.top = (60 + 40 * this.warning_messages.length) + "px"; document.body.appendChild(div); return this.layoutWarningMessages(); - } + }; - layoutWarningMessages() { + AppUI.prototype.layoutWarningMessages = function() { var i, j, len, ref, results, w; ref = this.warning_messages; results = []; for (i = j = 0, len = ref.length; j < len; i = ++j) { w = ref[i]; - results.push(w.style.top = `${60 + i * 40}px`); + results.push(w.style.top = (60 + i * 40) + "px"); } return results; - } + }; - removeWarningMessage(div) { + AppUI.prototype.removeWarningMessage = function(div) { var index; if (document.body.contains(div)) { document.body.removeChild(div); index = this.warning_messages.indexOf(div); if (index >= 0) { this.warning_messages.splice(index, 1); - document.querySelector(".main-container").style.top = `${60 + 40 * this.warning_messages.length}px`; + document.querySelector(".main-container").style.top = (60 + 40 * this.warning_messages.length) + "px"; return this.layoutWarningMessages(); } } - } + }; - checkActivity() { + AppUI.prototype.checkActivity = function() { var t; t = Date.now() - this.last_activity; if (this.app.project != null) { @@ -337,9 +388,9 @@ AppUI = class AppUI { }); } } - } + }; - backToProjectList(useraction) { + AppUI.prototype.backToProjectList = function(useraction) { this.hide("projectview"); this.show("myprojects"); this.app.runwindow.projectClosed(); @@ -355,21 +406,20 @@ AppUI = class AppUI { if (document.fullscreenElement) { return document.exitFullscreen(); } - } + }; - setSection(section, useraction) { - var item, j, k, len, len1, list, menuitem, ref, s; + AppUI.prototype.setSection = function(section, useraction) { + var fn, item, j, k, len, len1, list, menuitem, ref, s; if (this.makeProjectSideBarVisible != null) { this.makeProjectSideBarVisible(); } this.current_section = section; ref = this.sections; - for (j = 0, len = ref.length; j < len; j++) { - s = ref[j]; - ((s) => { + fn = (function(_this) { + return function(s) { var element, menuitem; - element = document.getElementById(`${s}-section`); - menuitem = document.getElementById(`menuitem-${s}`); + element = document.getElementById(s + "-section"); + menuitem = document.getElementById("menuitem-" + s); if ((element == null) || (menuitem == null)) { return; } @@ -380,16 +430,20 @@ AppUI = class AppUI { element.style.display = "none"; menuitem.classList.remove("selected"); } - })(s); + }; + })(this); + for (j = 0, len = ref.length; j < len; j++) { + s = ref[j]; + fn(s); } - menuitem = document.getElementById(`menuitem-${section}`); + menuitem = document.getElementById("menuitem-" + section); if (menuitem != null) { menuitem.classList.add("selected"); } list = document.querySelectorAll(".menuitem-plugin"); for (k = 0, len1 = list.length; k < len1; k++) { item = list[k]; - if (item.id !== `menuitem-${section}`) { + if (item.id !== ("menuitem-" + section)) { item.classList.remove("selected"); } } @@ -435,22 +489,25 @@ AppUI = class AppUI { app.editor.editor.setReadOnly(section !== "code"); app.doc_editor.editor.setReadOnly(section !== "doc"); if (useraction && (this.app.project != null)) { - this.app.app_state.pushState(`project.${this.app.project.slug}.${section}`, `/projects/${this.app.project.slug}/${section}/`); + this.app.app_state.pushState("project." + this.app.project.slug + "." + section, "/projects/" + this.app.project.slug + "/" + section + "/"); } return this.app.runwindow.hideAll(); - } + }; - accountRequired(callback) { + AppUI.prototype.accountRequired = function(callback) { this.logged_callback = callback; this.setDisplay("login-overlay", "block"); this.hide("login-panel"); this.hide("create-account-panel"); this.hide("forgot-password-panel"); return this.show("guest-panel"); - } + }; - setMainSection(section, useraction = false) { - var j, len, name, p, ref, s; + AppUI.prototype.setMainSection = function(section, useraction) { + var fn, j, len, name, p, ref, s; + if (useraction == null) { + useraction = false; + } if (section === "projects" && (this.app.user == null)) { this.accountRequired(); return; @@ -459,10 +516,10 @@ AppUI = class AppUI { if (section === "home") { this.app.app_state.pushState("home", this.app.translator.lang === "fr" ? "/fr" : "/"); } else if (section === "projects" && (this.project != null) && (this.current_section != null)) { - this.app.app_state.pushState(`project.${this.project.slug}.${this.current_section}`, `/projects/${this.project.slug}/${this.current_section}/`); + this.app.app_state.pushState("project." + this.project.slug + "." + this.current_section, "/projects/" + this.project.slug + "/" + this.current_section + "/"); } else if (section === "explore" && this.app.explore.project) { p = this.app.explore.project; - this.app.app_state.pushState("project_details", `/i/${p.owner}/${p.slug}/`, { + this.app.app_state.pushState("project_details", "/i/" + p.owner + "/" + p.slug + "/", { project: p }); } else { @@ -474,17 +531,16 @@ AppUI = class AppUI { } else if (name === "tutorials") { this.app.tutorials.tutorials_page.pushState(); } else { - this.app.app_state.pushState(name, `/${name}/`); + this.app.app_state.pushState(name, "/" + name + "/"); } } } ref = this.menuoptions; - for (j = 0, len = ref.length; j < len; j++) { - s = ref[j]; - ((s) => { + fn = (function(_this) { + return function(s) { var element, menuitem; - element = document.getElementById(`${s}-section`); - menuitem = document.getElementById(`menu-${s}`); + element = document.getElementById(s + "-section"); + menuitem = document.getElementById("menu-" + s); if (s === section) { element.style.display = "block"; if (menuitem != null) { @@ -496,7 +552,11 @@ AppUI = class AppUI { return menuitem.classList.remove("selected"); } } - })(s); + }; + })(this); + for (j = 0, len = ref.length; j < len; j++) { + s = ref[j]; + fn(s); } if (section === "projects" && (this.app.project == null)) { this.hide("projectview"); @@ -523,209 +583,267 @@ AppUI = class AppUI { if (section === "tutorials") { this.app.tutorials.load(); } - //@app.explore.closeDetails() if section != "explore" this.app.runwindow.hideAll(); - } + }; - setDisplay(element, value) { + AppUI.prototype.setDisplay = function(element, value) { return document.getElementById(element).style.display = value; - } + }; - focus(element) { + AppUI.prototype.focus = function(element) { return document.getElementById(element).focus(); - } + }; - get(id) { + AppUI.prototype.get = function(id) { return document.getElementById(id); - } + }; - setAction(id, callback) { - return this.get(id).addEventListener("click", (event) => { - event.preventDefault(); - return callback(event); - }); - } + AppUI.prototype.setAction = function(id, callback) { + return this.get(id).addEventListener("click", (function(_this) { + return function(event) { + event.preventDefault(); + return callback(event); + }; + })(this)); + }; - show(element) { + AppUI.prototype.show = function(element) { return this.setDisplay(element, "block"); - } + }; - hide(element) { + AppUI.prototype.hide = function(element) { return this.setDisplay(element, "none"); - } + }; - createLoginFunctions() { - var j, lang, len, ref, s1, s2, s3, s4; + AppUI.prototype.createLoginFunctions = function() { + var fn, j, lang, len, ref, s1, s2, s3, s4; s1 = document.getElementById("switch_to_create_account"); s2 = document.getElementById("switch_to_log_in"); s3 = document.getElementById("switch_from_forgot_to_login"); s4 = document.getElementById("forgot-password-link"); - s1.addEventListener("click", () => { - this.setDisplay("create-account-panel", "block"); - return document.getElementById("login-panel").style.display = "none"; - }); - s2.addEventListener("click", () => { - document.getElementById("create-account-panel").style.display = "none"; - return document.getElementById("login-panel").style.display = "block"; - }); - s3.addEventListener("click", () => { - document.getElementById("forgot-password-panel").style.display = "none"; - return document.getElementById("login-panel").style.display = "block"; - }); - s4.addEventListener("click", () => { - document.getElementById("forgot-password-panel").style.display = "block"; - return document.getElementById("login-panel").style.display = "none"; - }); - document.getElementById("login-window").addEventListener("click", (event) => { - return event.stopPropagation(); - }); - document.getElementById("login-overlay").addEventListener("mousedown", (event) => { - return document.getElementById("login-overlay").style.display = "none"; - }); - document.getElementById("login-window").addEventListener("mousedown", (event) => { - return event.stopPropagation(); - }); - this.setAction("login-button", () => { - return this.showLoginPanel(); - }); - this.setAction("guest-action-login", () => { - return this.showLoginPanel(); - }); - this.setAction("guest-action-create", () => { - return this.showCreateAccountPanel(); - }); - this.setAction("create-account-button", () => { - return this.showCreateAccountPanel(); - }); - this.setAction("create-account-toggle-terms", () => { - return this.toggleTerms(); - }); - this.setAction("guest-action-guest", () => { - this.app.createGuest(); - return document.getElementById("login-overlay").style.display = "none"; - }); - document.querySelector(".username").addEventListener("mouseup", (event) => { - return event.stopPropagation(); - }); - document.querySelector(".username").addEventListener("click", (event) => { - var c, e, j, len, num, ref; - e = document.querySelector(".usermenu"); - if (window.ms_standalone) { - e.classList.add("standalone"); - e.classList.remove("regular"); - } else if (this.app.user.flags.guest || (this.app.user.email == null)) { - e.classList.add("guest"); - e.classList.remove("regular"); - } else { - e.classList.add("regular"); - e.classList.remove("guest"); - } - if (e.style.height === "0px") { - num = 0; - ref = e.childNodes; - for (j = 0, len = ref.length; j < len; j++) { - c = ref[j]; - if (c.offsetParent != null) { - num += 1; - } + s1.addEventListener("click", (function(_this) { + return function() { + _this.setDisplay("create-account-panel", "block"); + return document.getElementById("login-panel").style.display = "none"; + }; + })(this)); + s2.addEventListener("click", (function(_this) { + return function() { + document.getElementById("create-account-panel").style.display = "none"; + return document.getElementById("login-panel").style.display = "block"; + }; + })(this)); + s3.addEventListener("click", (function(_this) { + return function() { + document.getElementById("forgot-password-panel").style.display = "none"; + return document.getElementById("login-panel").style.display = "block"; + }; + })(this)); + s4.addEventListener("click", (function(_this) { + return function() { + document.getElementById("forgot-password-panel").style.display = "block"; + return document.getElementById("login-panel").style.display = "none"; + }; + })(this)); + document.getElementById("login-window").addEventListener("click", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); + document.getElementById("login-overlay").addEventListener("mousedown", (function(_this) { + return function(event) { + return document.getElementById("login-overlay").style.display = "none"; + }; + })(this)); + document.getElementById("login-window").addEventListener("mousedown", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); + this.setAction("login-button", (function(_this) { + return function() { + return _this.showLoginPanel(); + }; + })(this)); + this.setAction("guest-action-login", (function(_this) { + return function() { + return _this.showLoginPanel(); + }; + })(this)); + this.setAction("guest-action-create", (function(_this) { + return function() { + return _this.showCreateAccountPanel(); + }; + })(this)); + this.setAction("create-account-button", (function(_this) { + return function() { + return _this.showCreateAccountPanel(); + }; + })(this)); + this.setAction("create-account-toggle-terms", (function(_this) { + return function() { + return _this.toggleTerms(); + }; + })(this)); + this.setAction("guest-action-guest", (function(_this) { + return function() { + _this.app.createGuest(); + return document.getElementById("login-overlay").style.display = "none"; + }; + })(this)); + document.querySelector(".username").addEventListener("mouseup", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); + document.querySelector(".username").addEventListener("click", (function(_this) { + return function(event) { + var c, e, j, len, num, ref; + e = document.querySelector(".usermenu"); + if (window.ms_standalone) { + e.classList.add("standalone"); + e.classList.remove("regular"); + } else if (_this.app.user.flags.guest || (_this.app.user.email == null)) { + e.classList.add("guest"); + e.classList.remove("regular"); + } else { + e.classList.add("regular"); + e.classList.remove("guest"); } - e.style.height = `${42 * num}px`; - if (!this.usermenuclose) { - return this.usermenuclose = document.body.addEventListener("mouseup", (event) => { - return e.style.height = "0px"; - }); + if (e.style.height === "0px") { + num = 0; + ref = e.childNodes; + for (j = 0, len = ref.length; j < len; j++) { + c = ref[j]; + if (c.offsetParent != null) { + num += 1; + } + } + e.style.height = (42 * num) + "px"; + if (!_this.usermenuclose) { + return _this.usermenuclose = document.body.addEventListener("mouseup", function(event) { + return e.style.height = "0px"; + }); + } + } else { + return e.style.height = "0px"; } - } else { - return e.style.height = "0px"; - } - }); - document.querySelector(".usermenu .logout").addEventListener("click", (event) => { - return this.app.disconnect(); - }); - document.querySelector(".usermenu .settings").addEventListener("click", (event) => { - return this.app.openUserSettings(); - }); - document.querySelector(".usermenu .profile").addEventListener("click", (event) => { - return this.app.openUserProfile(); - }); - document.querySelector(".usermenu .progress").addEventListener("click", (event) => { - return this.app.openUserProgress(); - }); - document.querySelector("#header-progress-summary").addEventListener("click", (event) => { - return this.app.openUserProgress(); - }); - document.querySelector(".usermenu .create-account").addEventListener("click", (event) => { - return this.showCreateAccountPanel(); - }); - document.querySelector(".usermenu .discard-account").addEventListener("click", (event) => { - return this.app.disconnect(); - }); - document.querySelector("#language-setting").addEventListener("mouseup", (event) => { - return event.stopPropagation(); - }); + }; + })(this)); + document.querySelector(".usermenu .logout").addEventListener("click", (function(_this) { + return function(event) { + return _this.app.disconnect(); + }; + })(this)); + document.querySelector(".usermenu .settings").addEventListener("click", (function(_this) { + return function(event) { + return _this.app.openUserSettings(); + }; + })(this)); + document.querySelector(".usermenu .profile").addEventListener("click", (function(_this) { + return function(event) { + return _this.app.openUserProfile(); + }; + })(this)); + document.querySelector(".usermenu .progress").addEventListener("click", (function(_this) { + return function(event) { + return _this.app.openUserProgress(); + }; + })(this)); + document.querySelector("#header-progress-summary").addEventListener("click", (function(_this) { + return function(event) { + return _this.app.openUserProgress(); + }; + })(this)); + document.querySelector(".usermenu .create-account").addEventListener("click", (function(_this) { + return function(event) { + return _this.showCreateAccountPanel(); + }; + })(this)); + document.querySelector(".usermenu .discard-account").addEventListener("click", (function(_this) { + return function(event) { + return _this.app.disconnect(); + }; + })(this)); + document.querySelector("#language-setting").addEventListener("mouseup", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); this.createMainMenuFunction(); - document.querySelector("#language-setting").addEventListener("click", (event) => { - var e; - e = document.querySelector("#language-menu"); - if (!e.classList.contains("language-menu-open")) { - e.classList.add("language-menu-open"); - if (!this.languagemenuclose) { - return this.languagemenuclose = document.body.addEventListener("mouseup", (event) => { - return e.classList.remove("language-menu-open"); - }); + document.querySelector("#language-setting").addEventListener("click", (function(_this) { + return function(event) { + var e; + e = document.querySelector("#language-menu"); + if (!e.classList.contains("language-menu-open")) { + e.classList.add("language-menu-open"); + if (!_this.languagemenuclose) { + return _this.languagemenuclose = document.body.addEventListener("mouseup", function(event) { + return e.classList.remove("language-menu-open"); + }); + } + } else { + return e.classList.remove("language-menu-open"); } - } else { - return e.classList.remove("language-menu-open"); - } - }); + }; + })(this)); ref = window.ms_languages; - for (j = 0, len = ref.length; j < len; j++) { - lang = ref[j]; - ((lang) => { - if (document.querySelector(`#language-choice-${lang}`) != null) { - document.querySelector(`#language-choice-${lang}`).addEventListener("click", (event) => { - return this.setLanguage(lang); + fn = (function(_this) { + return function(lang) { + if (document.querySelector("#language-choice-" + lang) != null) { + document.querySelector("#language-choice-" + lang).addEventListener("click", function(event) { + return _this.setLanguage(lang); }); } - if (document.querySelector(`#switch-to-${lang}`) != null) { - return document.querySelector(`#switch-to-${lang}`).addEventListener("click", (event) => { + if (document.querySelector("#switch-to-" + lang) != null) { + return document.querySelector("#switch-to-" + lang).addEventListener("click", function(event) { event.preventDefault(); - return this.setLanguage(lang); + return _this.setLanguage(lang); }); } - })(lang); + }; + })(this); + for (j = 0, len = ref.length; j < len; j++) { + lang = ref[j]; + fn(lang); } - this.setAction("login-submit", () => { - return this.app.login(this.get("login_nick").value, this.get("login_password").value); - }); - this.setAction("create-account-submit", () => { - if (!this.get("create-account-tos").checked) { - return alert(this.app.translator.get("You must accept the terms of use in order to create an account.")); - } - return this.app.createAccount(this.get("create_nick").value, this.get("create_email").value, this.get("create_password").value, this.get("create-account-newsletter").checked); - }); - return this.setAction("forgot-submit", () => { - return this.app.sendPasswordRecovery(document.getElementById("forgot_email").value); - }); - } + this.setAction("login-submit", (function(_this) { + return function() { + return _this.app.login(_this.get("login_nick").value, _this.get("login_password").value); + }; + })(this)); + this.setAction("create-account-submit", (function(_this) { + return function() { + if (!_this.get("create-account-tos").checked) { + return alert(_this.app.translator.get("You must accept the terms of use in order to create an account.")); + } + return _this.app.createAccount(_this.get("create_nick").value, _this.get("create_email").value, _this.get("create_password").value, _this.get("create-account-newsletter").checked); + }; + })(this)); + return this.setAction("forgot-submit", (function(_this) { + return function() { + return _this.app.sendPasswordRecovery(document.getElementById("forgot_email").value); + }; + })(this)); + }; - showLoginPanel() { + AppUI.prototype.showLoginPanel = function() { this.setDisplay("login-overlay", "block"); this.show("login-panel"); this.hide("create-account-panel"); this.hide("forgot-password-panel"); return this.hide("guest-panel"); - } + }; - showCreateAccountPanel() { + AppUI.prototype.showCreateAccountPanel = function() { this.setDisplay("login-overlay", "block"); this.hide("login-panel"); this.show("create-account-panel"); this.hide("forgot-password-panel"); return this.hide("guest-panel"); - } + }; - userConnected(nick) { + AppUI.prototype.userConnected = function(nick) { var text; if (this.nick === nick) { return; @@ -745,59 +863,49 @@ AppUI = class AppUI { this.get("user-nick").innerHTML = nick; if (this.project != null) { this.updateProjectTitle(); - this.get("project-icon").src = location.origin + `/${this.project.owner.nick}/${this.project.slug}/${this.project.code}/icon.png`; + this.get("project-icon").src = location.origin + ("/" + this.project.owner.nick + "/" + this.project.slug + "/" + this.project.code + "/icon.png"); } } this.get("user-nick").style.display = "inline-block"; - //@show "user-info" this.show("login-info"); this.hide("login-overlay"); - this.setMainSection("projects", location.pathname.length < 4); // home page with language variation => record jump to /projects/ - - // @addWarningMessage """Join microStudio mini-jam #2! From October 24/25. More info in the Community Forum and Discord""","fa-info-circle","mini_jam_2_#{Math.floor(Date.now()/1000/3600/12)}",true + this.setMainSection("projects", location.pathname.length < 4); if (this.app.user.info.size > this.app.user.info.max_storage) { text = this.app.translator.get("Your account is out of space!"); text += " " + this.app.translator.get("You are using %USED% of the %ALLOWED% you are allowed.").replace("%USED%", this.displayByteSize(this.app.user.info.size)).replace("%ALLOWED%", this.displayByteSize(this.app.user.info.max_storage)); - text += ` ${this.app.translator.get("More info...")}`; + text += " " + (this.app.translator.get("More info...")) + ""; return this.addWarningMessage(text, void 0, "out_of_storage", false); } - } + }; - //if not @project? - // @show "myprojects" - // @hide "projectview" - //@get("menu-projects").style.display = "inline-block" - //@setMainSection "projects" - userDisconnected() { + AppUI.prototype.userDisconnected = function() { this.get("login-button").style.display = "block"; this.get("user-nick").innerHTML = "nick"; - //@hide "menu-projects" this.hide("login-info"); this.nick = null; return this.project = null; - } + }; - //@get("user-info").style.display = "none" - showLoginButton() { + AppUI.prototype.showLoginButton = function() { this.get("login-button").style.display = "block"; return this.get("create-account-button").style.display = "block"; - } + }; - popMenu() { + AppUI.prototype.popMenu = function() { return document.querySelector("header").style.transform = "translateY(0%)"; - } + }; - createProjectBox(p) { + AppUI.prototype.createProjectBox = function(p) { var buttons, clone_button, delete_button, element, export_button, export_href, icon, pill, size, sizepill, title; element = document.createElement("a"); element.classList.add("project-box"); - element.id = `project-box-${p.slug}`; - element.href = `/projects/${p.slug}/code/`; + element.id = "project-box-" + p.slug; + element.href = "/projects/" + p.slug + "/code/"; element.dataset.title = p.title; element.dataset.description = p.description; element.dataset.tags = p.tags.join(","); - if (p.public) { - element.dataset.public = p.public; + if (p["public"]) { + element.dataset["public"] = p["public"]; } buttons = document.createElement("div"); buttons.classList.add("buttons"); @@ -809,63 +917,69 @@ AppUI = class AppUI { sizepill.classList.add("pill", "bg-blue", "shadow5", 'marginbottom10', 'marginright10'); buttons.appendChild(sizepill); } - if (p.public) { + if (p["public"]) { pill = document.createElement("div"); pill.innerHTML = " " + this.app.translator.get("public"); pill.classList.add("pill", "bg-purple", "shadow5", 'marginbottom10'); buttons.appendChild(pill); } - export_href = `/${p.owner.nick}/${p.slug}/${p.code}/export/project/`; + export_href = "/" + p.owner.nick + "/" + p.slug + "/" + p.code + "/export/project/"; export_button = document.createElement("div"); export_button.classList.add("button", "export", "shadow5"); - export_button.innerHTML = ` ${this.app.translator.get("Export")}`; + export_button.innerHTML = " " + (this.app.translator.get("Export")) + ""; buttons.appendChild(export_button); - export_button.addEventListener("click", (event) => { - event.stopPropagation(); - return event.stopImmediatePropagation(); - }); + export_button.addEventListener("click", (function(_this) { + return function(event) { + event.stopPropagation(); + return event.stopImmediatePropagation(); + }; + })(this)); clone_button = document.createElement("div"); clone_button.classList.add("button", "clone", "shadow5"); - clone_button.innerHTML = ` ${this.app.translator.get("Clone")}`; + clone_button.innerHTML = " " + (this.app.translator.get("Clone")); buttons.appendChild(clone_button); - clone_button.addEventListener("click", (event) => { - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - return ConfirmDialog.confirm(this.app.translator.get("Do you want to clone this project?"), this.app.translator.get("Clone"), this.app.translator.get("Cancel"), () => { - return this.app.cloneProject(p); - }); - }); + clone_button.addEventListener("click", (function(_this) { + return function(event) { + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + return ConfirmDialog.confirm(_this.app.translator.get("Do you want to clone this project?"), _this.app.translator.get("Clone"), _this.app.translator.get("Cancel"), function() { + return _this.app.cloneProject(p); + }); + }; + })(this)); delete_button = document.createElement("div"); delete_button.classList.add("button", "delete", "shadow5"); if (p.owner.nick === this.app.nick) { - delete_button.innerHTML = ` ${this.app.translator.get("Delete")}`; + delete_button.innerHTML = " " + (this.app.translator.get("Delete")); } else { - delete_button.innerHTML = ` ${this.app.translator.get("Quit")}`; + delete_button.innerHTML = " " + (this.app.translator.get("Quit")); } buttons.appendChild(delete_button); - delete_button.addEventListener("click", (event) => { - var msg, ok; - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - msg = p.owner.nick === this.app.nick ? this.app.translator.get("Really delete this project?") : this.app.translator.get("Really quit this project?"); - ok = p.owner.nick === this.app.nick ? this.app.translator.get("Delete") : this.app.translator.get("Quit"); - return ConfirmDialog.confirm(msg, ok, this.app.translator.get("Cancel"), () => { - return this.app.deleteProject(p); - }); - }); + delete_button.addEventListener("click", (function(_this) { + return function(event) { + var msg, ok; + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + msg = p.owner.nick === _this.app.nick ? _this.app.translator.get("Really delete this project?") : _this.app.translator.get("Really quit this project?"); + ok = p.owner.nick === _this.app.nick ? _this.app.translator.get("Delete") : _this.app.translator.get("Quit"); + return ConfirmDialog.confirm(msg, ok, _this.app.translator.get("Cancel"), function() { + return _this.app.deleteProject(p); + }); + }; + })(this)); title = document.createElement("div"); title.classList.add("project-title"); title.innerText = p.title; element.appendChild(title); element.appendChild(document.createElement("br")); icon = new Image; - icon.src = location.origin + `/${p.owner.nick}/${p.slug}/${p.code}/icon.png`; + icon.src = location.origin + ("/" + p.owner.nick + "/" + p.slug + "/" + p.code + "/icon.png"); icon.classList.add("pixelated"); element.appendChild(icon); if (p.poster) { - element.style.background = `linear-gradient(to bottom, hsla(200,20%,20%,0.6), hsla(200,20%,20%,0.9)),url(/${p.owner.nick}/${p.slug}/${p.code}/poster.png)`; + element.style.background = "linear-gradient(to bottom, hsla(200,20%,20%,0.6), hsla(200,20%,20%,0.9)),url(/" + p.owner.nick + "/" + p.slug + "/" + p.code + "/poster.png)"; element.style["background-size"] = "cover"; element.style["background-opacity"] = .5; icon.style.width = "104px"; @@ -873,16 +987,18 @@ AppUI = class AppUI { icon.style["margin-top"] = "40px"; icon.style["box-shadow"] = "0 0 10px 1px #000"; } - element.addEventListener("click", (event) => { - if (!event.ctrlKey && !event.metaKey) { - event.preventDefault(); - return this.app.openProject(p); - } - }); + element.addEventListener("click", (function(_this) { + return function(event) { + if (!event.ctrlKey && !event.metaKey) { + event.preventDefault(); + return _this.app.openProject(p); + } + }; + })(this)); return element; - } + }; - updateProjects() { + AppUI.prototype.updateProjects = function() { var c, count, div, e, element, h2, j, k, len, len1, list, p, pending, ref; list = this.get("project-list"); list.innerHTML = ""; @@ -919,12 +1035,11 @@ AppUI = class AppUI { p = pending[k]; e = document.createElement("div"); e.classList.add("invite"); - e.innerHTML = `
\n
\n
\n ${p.title} by ${p.owner.nick}`; + e.innerHTML = "
\n
\n
\n " + p.title + " by " + p.owner.nick; div.appendChild(e); } list.insertBefore(div, list.firstChild); } - //# create list of projects to accept or reject if (this.logged_callback != null) { c = this.logged_callback; this.logged_callback = null; @@ -932,9 +1047,9 @@ AppUI = class AppUI { } else { this.app.app_state.projectsFetched(); } - } + }; - acceptInvite(projectid) { + AppUI.prototype.acceptInvite = function(projectid) { var j, len, p, ref; ref = this.app.projects; for (j = 0, len = ref.length; j < len; j++) { @@ -946,9 +1061,9 @@ AppUI = class AppUI { }); } } - } + }; - rejectInvite(projectid) { + AppUI.prototype.rejectInvite = function(projectid) { var j, len, p, ref; ref = this.app.projects; for (j = 0, len = ref.length; j < len; j++) { @@ -961,13 +1076,16 @@ AppUI = class AppUI { }); } } - } + }; - setProject(project1, useraction = true) { + AppUI.prototype.setProject = function(project1, useraction) { var j, len, ref, t, tab; this.project = project1; + if (useraction == null) { + useraction = true; + } this.updateProjectTitle(); - this.get("project-icon").src = location.origin + `/${this.project.owner.nick}/${this.project.slug}/${this.project.code}/icon.png`; + this.get("project-icon").src = location.origin + ("/" + this.project.owner.nick + "/" + this.project.slug + "/" + this.project.code + "/icon.png"); tab = "code"; if ((this.project.tabs != null) && !this.app.tab_manager.isTabActive("code")) { tab = "options"; @@ -992,26 +1110,26 @@ AppUI = class AppUI { this.app.runwindow.terminal.start(); this.updateActiveUsers(); return this.doc_splitbar.initPosition(50); - } + }; - updateProjectTitle() { + AppUI.prototype.updateProjectTitle = function() { var html; if (this.project != null) { html = this.project.title; - if (this.project.public) { - html += `
${this.app.translator.get("public")}
`; + if (this.project["public"]) { + html += "
" + (this.app.translator.get("public")) + "
"; } return this.get("project-name").innerHTML = html; } - } + }; - projectUpdate(change) { + AppUI.prototype.projectUpdate = function(change) { var icon, img; if (change === "spritelist") { icon = this.project.getSprite("icon"); if (icon != null) { icon.addImage(this.get("project-icon"), 32); - img = document.querySelector(`#project-box-${this.project.slug} img`); + img = document.querySelector("#project-box-" + this.project.slug + " img"); if (img != null) { return icon.addImage(img, 144); } @@ -1021,9 +1139,9 @@ AppUI = class AppUI { } else if (change === "locks") { return this.updateActiveUsers(); } - } + }; - updateActiveUsers() { + AppUI.prototype.updateActiveUsers = function() { var div, e, element, i, j, key, list, name, names, ref, span; element = document.querySelector(".projectheader #active-project-users"); list = element.childNodes; @@ -1040,8 +1158,8 @@ AppUI = class AppUI { for (key in this.project.friends) { if (!names[key]) { div = document.createElement("div"); - div.style = `background:${this.createFriendColor(key)}`; - div.id = `active-user-${key}`; + div.style = "background:" + (this.createFriendColor(key)); + div.id = "active-user-" + key; i = document.createElement("i"); i.classList.add("fa"); i.classList.add("fa-user"); @@ -1052,25 +1170,27 @@ AppUI = class AppUI { element.appendChild(div); } } - } + }; - createFriendColor(friend) { + AppUI.prototype.createFriendColor = function(friend) { var i, j, ref, seed; seed = 137; for (i = j = 0, ref = friend.length - 1; j <= ref; i = j += 1) { seed = (seed + friend.charCodeAt(i) * 31 + 97) % 360; } - return `hsl(${seed},50%,50%)`; - } + return "hsl(" + seed + ",50%,50%)"; + }; - startSaveStatus() { + AppUI.prototype.startSaveStatus = function() { this.savetick = 0; - return setInterval((() => { - return this.checkSaveStatus(); - }), 500); - } + return setInterval(((function(_this) { + return function() { + return _this.checkSaveStatus(); + }; + })(this)), 500); + }; - checkSaveStatus() { + AppUI.prototype.checkSaveStatus = function() { var e, t; if (this.project == null) { return; @@ -1088,7 +1208,7 @@ AppUI = class AppUI { } else { this.savetick = (this.savetick + 1) % 2; t = .9 + this.savetick * .2; - return e.style.transform = `scale(${t})`; + return e.style.transform = "scale(" + t + ")"; } break; case "saved": @@ -1105,58 +1225,65 @@ AppUI = class AppUI { return e.style.transform = "scale(1)"; } } - } + }; - toggleTerms() { + AppUI.prototype.toggleTerms = function() { if (this.terms_shown) { this.terms_shown = false; return this.get("create-account-terms").style.display = "none"; } else { this.terms_shown = true; this.get("create-account-terms").style.display = "block"; - return this.app.about.load("terms", (text) => { - return this.get("create-account-terms").innerHTML = DOMPurify.sanitize(marked(text)); - }); + return this.app.about.load("terms", (function(_this) { + return function(text) { + return _this.get("create-account-terms").innerHTML = DOMPurify.sanitize(marked(text)); + }; + })(this)); } - } + }; - showNotification(text) { + AppUI.prototype.showNotification = function(text) { document.querySelector("#notification-bubble span").innerText = text; document.getElementById("notification-container").style.transform = "translateY(0px)"; - return setTimeout((() => { - return document.getElementById("notification-container").style.transform = "translateY(-150px)"; - }), 5000); - } + return setTimeout(((function(_this) { + return function() { + return document.getElementById("notification-container").style.transform = "translateY(-150px)"; + }; + })(this)), 5000); + }; - setLanguage(lang) { + AppUI.prototype.setLanguage = function(lang) { var date; - if ((document.cookie != null) && document.cookie.indexOf(`language=${lang}`) >= 0) { + if ((document.cookie != null) && document.cookie.indexOf("language=" + lang) >= 0) { return; } date = new Date(); date.setTime(date.getTime() + 1000 * 3600 * 24 * 60); - document.cookie = `language=${lang};expires=${date.toUTCString()};path=/`; - return window.location = location.origin + (lang !== "en" ? `/${lang}/` : ""); //+"?t=#{Date.now()}" - } + document.cookie = "language=" + lang + ";expires=" + (date.toUTCString()) + ";path=/"; + return window.location = location.origin + (lang !== "en" ? "/" + lang + "/" : ""); + }; - displayByteSize(size) { + AppUI.prototype.displayByteSize = function(size) { if (size < 1000) { - return `${size} ${this.app.translator.get("Bytes")}`; + return size + " " + (this.app.translator.get("Bytes")); } else if (size < 10000) { - return `${(size / 1000).toFixed(1)} ${this.app.translator.get("Kb")}`; + return ((size / 1000).toFixed(1)) + " " + (this.app.translator.get("Kb")); } else if (size < 1000000) { - return `${Math.floor(size / 1000)} ${this.app.translator.get("Kb")}`; + return (Math.floor(size / 1000)) + " " + (this.app.translator.get("Kb")); } else if (size < 10000000) { - return `${(size / 1000000).toFixed(1)} ${this.app.translator.get("Mb")}`; + return ((size / 1000000).toFixed(1)) + " " + (this.app.translator.get("Mb")); } else if (size < 1000000000) { - return `${Math.floor(size / 1000000)} ${this.app.translator.get("Mb")}`; + return (Math.floor(size / 1000000)) + " " + (this.app.translator.get("Mb")); } else { - return `${(size / 1000000000).toFixed(1)} ${this.app.translator.get("Gb")}`; + return ((size / 1000000000).toFixed(1)) + " " + (this.app.translator.get("Gb")); } - } + }; - createUserTag(nick, tier, pic = false, picmargin) { + AppUI.prototype.createUserTag = function(nick, tier, pic, picmargin) { var div, i, icon, span; + if (pic == null) { + pic = false; + } div = document.createElement("a"); div.classList.add("usertag"); if (tier) { @@ -1171,41 +1298,41 @@ AppUI = class AppUI { div.appendChild(span); if (tier) { icon = new Image; - icon.src = location.origin + `/microstudio/patreon/badges/sprites/${tier}.png`; + icon.src = location.origin + ("/microstudio/patreon/badges/sprites/" + tier + ".png"); icon.classList.add("pixelated"); icon.style = "width: 32px; height: 32px;"; icon.alt = icon.title = this.app.getTierName(tier); div.appendChild(icon); } - div.href = `/${nick}/`; + div.href = "/" + nick + "/"; div.target = "_blank"; div.addEventListener("click", function(event) { return event.stopPropagation(); }); if (pic) { pic = document.createElement("img"); - pic.src = `/${nick}.png`; + pic.src = "/" + nick + ".png"; pic.classList.add("profile"); div.appendChild(pic); if (picmargin) { - div.style["margin-left"] = `${picmargin}px`; + div.style["margin-left"] = picmargin + "px"; } } return div; - } + }; - setImportProgress(progress) { + AppUI.prototype.setImportProgress = function(progress) { document.getElementById("import-project-button").innerHTML = " Uploading... "; progress = Math.round(progress); - return document.getElementById("import-project-button").style.background = `linear-gradient(90deg,hsl(200,50%,40%) 0%,hsl(200,50%,40%) ${progress}%,hsl(200,20%,20%) ${progress}%)`; - } + return document.getElementById("import-project-button").style.background = "linear-gradient(90deg,hsl(200,50%,40%) 0%,hsl(200,50%,40%) " + progress + "%,hsl(200,20%,20%) " + progress + "%)"; + }; - resetImportButton() { - document.getElementById("import-project-button").innerHTML = ` ${this.app.translator.get("Import Project")}`; + AppUI.prototype.resetImportButton = function() { + document.getElementById("import-project-button").innerHTML = " " + (this.app.translator.get("Import Project")); return document.getElementById("import-project-button").style.removeProperty("background"); - } + }; - bumpElement(select) { + AppUI.prototype.bumpElement = function(select) { var element, interval, start; element = document.querySelector(select); if (element != null) { @@ -1220,129 +1347,147 @@ AppUI = class AppUI { t = Math.pow(t, .8); s = 1 + .5 * Math.sin(t * Math.PI); d = -.5 * Math.sin(t * Math.PI) * 20; - return element.style.transform = `scale(${s}) rotateZ(${d}deg)`; + return element.style.transform = "scale(" + s + ") rotateZ(" + d + "deg)"; } }), 16); } - } + }; - createFullscreenFeatures() { + AppUI.prototype.createFullscreenFeatures = function() { var button; button = document.getElementById("project-fullscreen"); - button.addEventListener("click", () => { - if (document.fullscreenElement) { - return document.exitFullscreen(); - } else { - document.getElementById("projectview").requestFullscreen(); - return document.getElementById("projectview").style.background = "hsl(200,20%,15%)"; - } - }); - return window.addEventListener("fullscreenchange", () => { - if (document.fullscreenElement) { - button.classList.remove("fa-expand"); - return button.classList.add("fa-compress"); - } else { - button.classList.add("fa-expand"); - button.classList.remove("fa-compress"); - return document.getElementById("projectview").style.background = "none"; - } - }); - } + button.addEventListener("click", (function(_this) { + return function() { + if (document.fullscreenElement) { + return document.exitFullscreen(); + } else { + document.getElementById("projectview").requestFullscreen(); + return document.getElementById("projectview").style.background = "hsl(200,20%,15%)"; + } + }; + })(this)); + return window.addEventListener("fullscreenchange", (function(_this) { + return function() { + if (document.fullscreenElement) { + button.classList.remove("fa-expand"); + return button.classList.add("fa-compress"); + } else { + button.classList.add("fa-expand"); + button.classList.remove("fa-compress"); + return document.getElementById("projectview").style.background = "none"; + } + }; + })(this)); + }; - createMainMenuFunction() { + AppUI.prototype.createMainMenuFunction = function() { var bump, button, closing, displayed, menu, resize; button = document.getElementById("main-menu-button"); menu = document.querySelector(".titlemenu"); closing = false; displayed = false; - bump = () => { - var f, t; - t = Date.now(); - f = () => { - var rr, tt; - tt = Date.now() - t; - if (tt < 250) { - tt = 1 - tt / 250; - tt = Math.pow(tt, 2); - rr = tt; - tt = 1 + tt * .5; - button.style.transform = `scale(${tt},${tt}) rotate(${-rr * 10}deg)`; - return setTimeout(f, 16); + bump = (function(_this) { + return function() { + var f, t; + t = Date.now(); + f = function() { + var rr, tt; + tt = Date.now() - t; + if (tt < 250) { + tt = 1 - tt / 250; + tt = Math.pow(tt, 2); + rr = tt; + tt = 1 + tt * .5; + button.style.transform = "scale(" + tt + "," + tt + ") rotate(" + (-rr * 10) + "deg)"; + return setTimeout(f, 16); + } else { + return button.style.transform = "none"; + } + }; + return f(); + }; + })(this); + button.addEventListener("click", (function(_this) { + return function(event) { + if (menu.style.left !== "0%" && !closing) { + menu.style.left = "0%"; + return bump(); } else { - return button.style.transform = "none"; + menu.style.left = "-100%"; + return bump(); } }; - return f(); - }; - button.addEventListener("click", (event) => { - if (menu.style.left !== "0%" && !closing) { - menu.style.left = "0%"; - return bump(); - } else { - menu.style.left = "-100%"; - return bump(); - } - }); - document.addEventListener("mouseup", () => { - if ((button.offsetParent != null) && menu.style.left !== "-100%") { - menu.style.left = "-100%"; - closing = true; - return bump(); - } else { - return closing = false; - } - }); - resize = () => { - if (button.offsetParent == null) { - menu.style.left = "0px"; - return displayed = false; - } else if (menu.style.left !== "0%") { - menu.style.left = "-100%"; - if (!displayed) { - displayed = true; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function() { + if ((button.offsetParent != null) && menu.style.left !== "-100%") { + menu.style.left = "-100%"; + closing = true; return bump(); + } else { + return closing = false; } - } - }; + }; + })(this)); + resize = (function(_this) { + return function() { + if (button.offsetParent == null) { + menu.style.left = "0px"; + return displayed = false; + } else if (menu.style.left !== "0%") { + menu.style.left = "-100%"; + if (!displayed) { + displayed = true; + return bump(); + } + } + }; + })(this); window.addEventListener("resize", resize); return resize(); - } + }; - createProjectSideBarCollapse() { + AppUI.prototype.createProjectSideBarCollapse = function() { var collapse_time, resize_until; collapse_time = 0; resize_until = Date.now(); - this.makeProjectSideBarVisible = () => { - if (document.getElementById("projectview").classList.contains("sidebar-collapsed")) { - document.getElementById("projectview").classList.remove("sidebar-collapsed"); - window.dispatchEvent(new Event('resize')); - } - if (window.innerWidth < 600) { - return collapse_time = Date.now() + 3000; - } - }; - window.addEventListener("resize", () => { - if (!document.getElementById("projectview").classList.contains("sidebar-collapsed") && window.innerWidth < 600) { - return collapse_time = Date.now() + 3000; - } else if (document.getElementById("projectview").classList.contains("sidebar-collapsed") && window.innerWidth >= 600) { - return this.makeProjectSideBarVisible(); - } - }); - return setInterval((() => { - if (Date.now() < resize_until) { - window.dispatchEvent(new Event('resize')); - } - if (collapse_time && Date.now() > collapse_time) { - collapse_time = 0; + this.makeProjectSideBarVisible = (function(_this) { + return function() { + if (document.getElementById("projectview").classList.contains("sidebar-collapsed")) { + document.getElementById("projectview").classList.remove("sidebar-collapsed"); + window.dispatchEvent(new Event('resize')); + } if (window.innerWidth < 600) { - document.getElementById("projectview").classList.add("sidebar-collapsed"); - return window.dispatchEvent(new Event('resize')); + return collapse_time = Date.now() + 3000; } - } - }), 500); - } + }; + })(this); + window.addEventListener("resize", (function(_this) { + return function() { + if (!document.getElementById("projectview").classList.contains("sidebar-collapsed") && window.innerWidth < 600) { + return collapse_time = Date.now() + 3000; + } else if (document.getElementById("projectview").classList.contains("sidebar-collapsed") && window.innerWidth >= 600) { + return _this.makeProjectSideBarVisible(); + } + }; + })(this)); + return setInterval(((function(_this) { + return function() { + if (Date.now() < resize_until) { + window.dispatchEvent(new Event('resize')); + } + if (collapse_time && Date.now() > collapse_time) { + collapse_time = 0; + if (window.innerWidth < 600) { + document.getElementById("projectview").classList.add("sidebar-collapsed"); + return window.dispatchEvent(new Event('resize')); + } + } + }; + })(this)), 500); + }; - createProjectLikesButton(element, project) { + AppUI.prototype.createProjectLikesButton = function(element, project) { var e, likes; e = element.querySelector(".likes-button"); if (e) { @@ -1355,22 +1500,26 @@ AppUI = class AppUI { likes.classList.add("liked"); } element.appendChild(likes); - return likes.addEventListener("click", () => { - event.stopImmediatePropagation(); - if (!this.app.user.flags.validated) { - return alert(this.app.translator.get("Validate your e-mail address to enable votes.")); - } - return this.app.client.sendRequest({ - name: "toggle_like", - project: project.id - }, (msg) => { - if (msg.name === "project_likes") { - project.likes = msg.likes; - project.liked = msg.liked; - return this.createProjectLikesButton(element, project); + return likes.addEventListener("click", (function(_this) { + return function() { + event.stopImmediatePropagation(); + if (!_this.app.user.flags.validated) { + return alert(_this.app.translator.get("Validate your e-mail address to enable votes.")); } - }); - }); - } + return _this.app.client.sendRequest({ + name: "toggle_like", + project: project.id + }, function(msg) { + if (msg.name === "project_likes") { + project.likes = msg.likes; + project.liked = msg.liked; + return _this.createProjectLikesButton(element, project); + } + }); + }; + })(this)); + }; + + return AppUI; -}; +})(); diff --git a/static/js/appui/floatingwindow.js b/static/js/appui/floatingwindow.js index 82774db8..5774a389 100644 --- a/static/js/appui/floatingwindow.js +++ b/static/js/appui/floatingwindow.js @@ -1,39 +1,53 @@ -this.FloatingWindow = class FloatingWindow { - constructor(app, elementid, listener, options = {}) { +this.FloatingWindow = (function() { + function FloatingWindow(app, elementid, listener, options) { this.app = app; this.elementid = elementid; this.listener = listener; - this.options = options; + this.options = options != null ? options : {}; this.window = document.getElementById(this.elementid); - document.querySelector(`#${this.elementid}`).addEventListener("mousedown", (event) => { - return this.moveToFront(); - }); - document.querySelector(`#${this.elementid} .titlebar`).addEventListener("mousedown", (event) => { - return this.startMove(event); - }); + document.querySelector("#" + this.elementid).addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.moveToFront(); + }; + })(this)); + document.querySelector("#" + this.elementid + " .titlebar").addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.startMove(event); + }; + })(this)); if (!this.options.fixed_size) { - document.querySelector(`#${this.elementid} .navigation .resize`).addEventListener("mousedown", (event) => { - return this.startResize(event); - }); + document.querySelector("#" + this.elementid + " .navigation .resize").addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.startResize(event); + }; + })(this)); } - document.addEventListener("mousemove", (event) => { - return this.mouseMove(event); - }); - document.addEventListener("mouseup", (event) => { - return this.mouseUp(event); - }); - window.addEventListener("resize", () => { - var b; - b = this.window.getBoundingClientRect(); - return this.setPosition(b.x - this.getParentX(), b.y - this.getParentY()); - }); - document.querySelector(`#${this.elementid} .titlebar .minify`).addEventListener("click", () => { - return this.close(); - }); + document.addEventListener("mousemove", (function(_this) { + return function(event) { + return _this.mouseMove(event); + }; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function(event) { + return _this.mouseUp(event); + }; + })(this)); + window.addEventListener("resize", (function(_this) { + return function() { + var b; + b = _this.window.getBoundingClientRect(); + return _this.setPosition(b.x - _this.getParentX(), b.y - _this.getParentY()); + }; + })(this)); + document.querySelector("#" + this.elementid + " .titlebar .minify").addEventListener("click", (function(_this) { + return function() { + return _this.close(); + }; + })(this)); this.max_ratio = .75; } - moveToFront() { + FloatingWindow.prototype.moveToFront = function() { var e, i, len, list; list = document.getElementsByClassName("floating-window"); for (i = 0, len = list.length; i < len; i++) { @@ -44,23 +58,23 @@ this.FloatingWindow = class FloatingWindow { e.style["z-index"] = 10; } } - } + }; - close() { + FloatingWindow.prototype.close = function() { this.shown = false; - document.getElementById(`${this.elementid}`).style.display = "none"; + document.getElementById("" + this.elementid).style.display = "none"; if ((this.listener != null) && (this.listener.floatingWindowClosed != null)) { return this.listener.floatingWindowClosed(); } - } + }; - show() { + FloatingWindow.prototype.show = function() { this.shown = true; - document.getElementById(`${this.elementid}`).style.display = "block"; + document.getElementById("" + this.elementid).style.display = "block"; return this.moveToFront(); - } + }; - startMove(event) { + FloatingWindow.prototype.startMove = function(event) { var e, i, len, list; this.moving = true; this.drag_start_x = event.clientX; @@ -72,9 +86,9 @@ this.FloatingWindow = class FloatingWindow { e = list[i]; e.classList.add("ignoreMouseEvents"); } - } + }; - startResize(event) { + FloatingWindow.prototype.startResize = function(event) { var e, i, len, list; this.resizing = true; this.drag_start_x = event.clientX; @@ -86,41 +100,41 @@ this.FloatingWindow = class FloatingWindow { e = list[i]; e.classList.add("ignoreMouseEvents"); } - } + }; - getParentX() { + FloatingWindow.prototype.getParentX = function() { if (this.window.parentNode != null) { return this.window.parentNode.getBoundingClientRect().x; } else { return 0; } - } + }; - getParentY() { + FloatingWindow.prototype.getParentY = function() { if (this.window.parentNode != null) { return this.window.parentNode.getBoundingClientRect().y; } else { return 0; } - } + }; - getParentWidth() { + FloatingWindow.prototype.getParentWidth = function() { if ((this.window.parentNode != null) && this.window.parentNode !== document.body) { return this.window.parentNode.clientWidth; } else { return window.innerWidth; } - } + }; - getParentHeight() { + FloatingWindow.prototype.getParentHeight = function() { if ((this.window.parentNode != null) && this.window.parentNode !== document.body) { return this.window.parentNode.clientHeight; } else { return window.innerHeight; } - } + }; - mouseMove(event) { + FloatingWindow.prototype.mouseMove = function(event) { var b, dx, dy, h, w; if (this.moving) { dx = event.clientX - this.drag_start_x; @@ -133,8 +147,8 @@ this.FloatingWindow = class FloatingWindow { w = Math.floor(Math.max(200, Math.min(this.getParentWidth() * this.max_ratio, this.drag_size_w + dx))); h = Math.floor(Math.max(200, Math.min(this.getParentHeight() * this.max_ratio, this.drag_size_h + dy))); if (!this.options.fixed_size) { - this.window.style.width = `${w}px`; - this.window.style.height = `${h}px`; + this.window.style.width = w + "px"; + this.window.style.height = h + "px"; } b = this.window.getBoundingClientRect(); if (w > this.getParentWidth() - b.x || h > this.getParentHeight() - b.y) { @@ -144,9 +158,9 @@ this.FloatingWindow = class FloatingWindow { return this.listener.floatingWindowResized(); } } - } + }; - mouseUp(event) { + FloatingWindow.prototype.mouseUp = function(event) { var e, i, len, list; this.moving = false; this.resizing = false; @@ -155,23 +169,25 @@ this.FloatingWindow = class FloatingWindow { e = list[i]; e.classList.remove("ignoreMouseEvents"); } - } + }; - setPosition(x, y) { + FloatingWindow.prototype.setPosition = function(x, y) { var b; b = this.window.getBoundingClientRect(); x = Math.max(4 - b.width / 2, Math.min(this.getParentWidth() - b.width / 2 - 4, x)); y = Math.max(4, Math.min(this.getParentHeight() - b.height / 2 - 4, y)); this.window.style.top = y + "px"; return this.window.style.left = x + "px"; - } + }; - resize(x, y, w, h) { + FloatingWindow.prototype.resize = function(x, y, w, h) { if (!this.options.fixed_size) { - this.window.style.width = `${w}px`; - this.window.style.height = `${h}px`; + this.window.style.width = w + "px"; + this.window.style.height = h + "px"; } return this.setPosition(x, y); - } + }; + + return FloatingWindow; -}; +})(); diff --git a/static/js/assets/assetsmanager.js b/static/js/assets/assetsmanager.js index 6782e695..a8bbb010 100644 --- a/static/js/assets/assetsmanager.js +++ b/static/js/assets/assetsmanager.js @@ -1,8 +1,12 @@ -var indexOf = [].indexOf; +var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; -this.AssetsManager = class AssetsManager extends Manager { - constructor(app) { - super(app); +this.AssetsManager = (function(superClass) { + extend(AssetsManager, superClass); + + function AssetsManager(app) { + AssetsManager.__super__.constructor.call(this, app); this.folder = "assets"; this.item = "asset"; this.list_change_event = "assetlist"; @@ -15,56 +19,60 @@ this.AssetsManager = class AssetsManager extends Manager { this.image_viewer = new ImageViewer(this); this.text_viewer = new TextViewer(this); this.init(); - document.querySelector("#capture-asset").addEventListener("click", () => { - if (this.asset != null) { - switch (this.asset.ext) { - case "glb": - case "obj": - return this.model_viewer.updateThumbnail(); + document.querySelector("#capture-asset").addEventListener("click", (function(_this) { + return function() { + if (_this.asset != null) { + switch (_this.asset.ext) { + case "glb": + case "obj": + return _this.model_viewer.updateThumbnail(); + } } - } - }); + }; + })(this)); this.code_snippet = new CodeSnippet(this.app); } - init() { - super.init(); + AssetsManager.prototype.init = function() { + AssetsManager.__super__.init.call(this); return this.splitbar.initPosition(30); - } + }; - update() { - return super.update(); - } + AssetsManager.prototype.update = function() { + return AssetsManager.__super__.update.call(this); + }; - checkThumbnail(asset, callback) { + AssetsManager.prototype.checkThumbnail = function(asset, callback) { var img, url; url = asset.getThumbnailURL(); img = new Image; img.src = url; - return img.onload = () => { - var canvas, ctx, data; - if (img.width > 0 && img.height > 0) { - canvas = document.createElement("canvas"); - canvas.width = 1; - canvas.height = 1; - ctx = canvas.getContext("2d"); - ctx.drawImage(img, -31, -31); - data = ctx.getImageData(0, 0, 1, 1); - if (data.data[3] > 128) { - return; + return img.onload = (function(_this) { + return function() { + var canvas, ctx, data; + if (img.width > 0 && img.height > 0) { + canvas = document.createElement("canvas"); + canvas.width = 1; + canvas.height = 1; + ctx = canvas.getContext("2d"); + ctx.drawImage(img, -31, -31); + data = ctx.getImageData(0, 0, 1, 1); + if (data.data[3] > 128) { + return; + } } - } - return callback(); - }; - } + return callback(); + }; + })(this); + }; - selectedItemRenamed() { + AssetsManager.prototype.selectedItemRenamed = function() { if ((this.selected_item != null) && (this.viewer != null)) { return this.viewer.updateSnippet(); } - } + }; - selectedItemDeleted() { + AssetsManager.prototype.selectedItemDeleted = function() { var e, j, len, parent, ref; parent = document.getElementById("asset-viewer"); ref = parent.childNodes; @@ -75,11 +83,11 @@ this.AssetsManager = class AssetsManager extends Manager { this.viewer = null; this.asset = null; this.code_snippet.clear(); - } + }; - openItem(name) { + AssetsManager.prototype.openItem = function(name) { var e, j, len, parent, ref; - super.openItem(name); + AssetsManager.__super__.openItem.call(this, name); this.asset = this.app.project.getAsset(name); console.info(this.asset); parent = document.getElementById("asset-viewer"); @@ -109,29 +117,30 @@ this.AssetsManager = class AssetsManager extends Manager { return this.viewer = this.image_viewer; } } - } + }; - createAsset(folder) { + AssetsManager.prototype.createAsset = function(folder) { var input; input = document.createElement("input"); input.type = "file"; - //input.accept = ".glb" - input.addEventListener("change", (event) => { - var f, files, j, len; - files = event.target.files; - if (files.length >= 1) { - for (j = 0, len = files.length; j < len; j++) { - f = files[j]; - this.fileDropped(f, folder); + input.addEventListener("change", (function(_this) { + return function(event) { + var f, files, j, len; + files = event.target.files; + if (files.length >= 1) { + for (j = 0, len = files.length; j < len; j++) { + f = files[j]; + _this.fileDropped(f, folder); + } } - } - }); + }; + })(this)); return input.click(); - } + }; - fileDropped(file, folder) { + AssetsManager.prototype.fileDropped = function(file, folder) { var ext, name, reader, ref, split; - console.info(`processing ${file.name}`); + console.info("processing " + file.name); console.info("folder: " + folder); reader = new FileReader(); split = file.name.split("."); @@ -140,60 +149,62 @@ this.AssetsManager = class AssetsManager extends Manager { if (ref = !ext, indexOf.call(this.extensions, ref) >= 0) { return; } - reader.addEventListener("load", () => { - var asset, canvas, data; - console.info("file read, size = " + reader.result.length); - if (reader.result.length > 30000000) { // client-side file size limit 30 Mb - return; - } - name = this.findNewFilename(name, "getAsset", folder); - if (folder != null) { - name = folder.getFullDashPath() + "-" + name; - } - if (folder != null) { - folder.setOpen(true); - } - canvas = document.createElement("canvas"); - canvas.width = canvas.height = 64; - asset = this.app.project.createAsset(name, canvas.toDataURL(), reader.result.length, ext); - asset.uploading = true; - if (ext === "json" || ext === "csv" || ext === "txt" || ext === "md") { - asset.local_text = reader.result; - } else { - asset.local_url = reader.result; - } - this.setSelectedItem(name); - this.openItem(name); - if (ext === "json" || ext === "csv" || ext === "txt" || ext === "md") { - data = reader.result; - } else { - data = reader.result.split(",")[1]; - } - this.app.project.addPendingChange(this); - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: `assets/${name}.${ext}`, - properties: {}, - content: data, - thumbnail: canvas.toDataURL().split(",")[1] - }, (msg) => { - console.info(msg); - this.app.project.removePendingChange(this); - asset.uploading = false; - delete asset.local_url; - this.app.project.updateAssetList(); - return this.checkNameFieldActivation(); - }); - }); + reader.addEventListener("load", (function(_this) { + return function() { + var asset, canvas, data; + console.info("file read, size = " + reader.result.length); + if (reader.result.length > 30000000) { + return; + } + name = _this.findNewFilename(name, "getAsset", folder); + if (folder != null) { + name = folder.getFullDashPath() + "-" + name; + } + if (folder != null) { + folder.setOpen(true); + } + canvas = document.createElement("canvas"); + canvas.width = canvas.height = 64; + asset = _this.app.project.createAsset(name, canvas.toDataURL(), reader.result.length, ext); + asset.uploading = true; + if (ext === "json" || ext === "csv" || ext === "txt" || ext === "md") { + asset.local_text = reader.result; + } else { + asset.local_url = reader.result; + } + _this.setSelectedItem(name); + _this.openItem(name); + if (ext === "json" || ext === "csv" || ext === "txt" || ext === "md") { + data = reader.result; + } else { + data = reader.result.split(",")[1]; + } + _this.app.project.addPendingChange(_this); + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "assets/" + name + "." + ext, + properties: {}, + content: data, + thumbnail: canvas.toDataURL().split(",")[1] + }, function(msg) { + console.info(msg); + _this.app.project.removePendingChange(_this); + asset.uploading = false; + delete asset.local_url; + _this.app.project.updateAssetList(); + return _this.checkNameFieldActivation(); + }); + }; + })(this)); if (ext === "json" || ext === "csv" || ext === "txt" || ext === "md") { return reader.readAsText(file); } else { return reader.readAsDataURL(file); } - } + }; - updateAssetIcon(asset, canvas) { + AssetsManager.prototype.updateAssetIcon = function(asset, canvas) { var color, context, h, w; context = canvas.getContext("2d"); color = (function() { @@ -223,63 +234,71 @@ this.AssetsManager = class AssetsManager extends Manager { context.fillStyle = color; context.fillRect(0, h - 2, w, 2); context.font = "7pt sans-serif"; - context.fillText(`${asset.ext.toUpperCase()}`, w - 26, h - 5); + context.fillText("" + (asset.ext.toUpperCase()), w - 26, h - 5); asset.thumbnail_url = canvas.toDataURL(); this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `assets/${asset.name}.${asset.ext}`, + file: "assets/" + asset.name + "." + asset.ext, thumbnail: canvas.toDataURL().split(",")[1] - }, (msg) => { - return console.info(msg); - }); + }, (function(_this) { + return function(msg) { + return console.info(msg); + }; + })(this)); if (asset.element != null) { return asset.element.querySelector("img").src = canvas.toDataURL(); } - } + }; + + return AssetsManager; -}; +})(Manager); -this.CodeSnippet = class CodeSnippet { - constructor(app1) { +this.CodeSnippet = (function() { + function CodeSnippet(app1) { var copyable; this.app = app1; copyable = true; this.container = document.querySelector("#asset-load-code"); this.input = document.querySelector("#asset-load-code input"); this.select = document.querySelector("#asset-load-code select"); - this.select.addEventListener("change", () => { - return this.setIndex(this.select.selectedIndex); - }); - document.querySelector("#asset-load-code i").addEventListener("click", () => { - var code, copy, input; - if (!copyable) { - return; - } - input = document.querySelector("#asset-load-code input"); - copy = document.querySelector("#asset-load-code i"); - code = input.value; - navigator.clipboard.writeText(code); - input.value = this.app.translator.get("Copied!"); - copyable = false; - copy.classList.remove("fa-copy"); - copy.classList.add("fa-check"); - return setTimeout((() => { - copy.classList.remove("fa-check"); - copy.classList.add("fa-copy"); - input.value = code; - return copyable = true; - }), 1000); - }); + this.select.addEventListener("change", (function(_this) { + return function() { + return _this.setIndex(_this.select.selectedIndex); + }; + })(this)); + document.querySelector("#asset-load-code i").addEventListener("click", (function(_this) { + return function() { + var code, copy, input; + if (!copyable) { + return; + } + input = document.querySelector("#asset-load-code input"); + copy = document.querySelector("#asset-load-code i"); + code = input.value; + navigator.clipboard.writeText(code); + input.value = _this.app.translator.get("Copied!"); + copyable = false; + copy.classList.remove("fa-copy"); + copy.classList.add("fa-check"); + return setTimeout((function() { + copy.classList.remove("fa-check"); + copy.classList.add("fa-copy"); + input.value = code; + return copyable = true; + }), 1000); + }; + })(this)); } - clear() { + CodeSnippet.prototype.clear = function() { this.select.innerHTML = ""; this.input.value = ""; return this.container.style.display = "none"; - } + }; - set(list) { + CodeSnippet.prototype.set = function(list) { var i, j, len, name, option, ref, snippet, value; this.list = list; this.clear(); @@ -297,47 +316,53 @@ this.CodeSnippet = class CodeSnippet { } } return this.container.style.display = "block"; - } + }; - setIndex(index) { + CodeSnippet.prototype.setIndex = function(index) { if ((this.list != null) && index < this.list.length) { return this.input.value = this.list[index].value; } - } + }; + + return CodeSnippet; -}; +})(); -this.CodeSnippetField = class CodeSnippetField { - constructor(app1, query) { +this.CodeSnippetField = (function() { + function CodeSnippetField(app1, query) { var copyable; this.app = app1; this.element = document.querySelector(query); this.input = this.element.querySelector("input"); this.i = this.element.querySelector("i"); copyable = true; - this.i.addEventListener("click", () => { - var code; - if (!copyable) { - return; - } - code = this.input.value; - navigator.clipboard.writeText(code); - this.input.value = this.app.translator.get("Copied!"); - copyable = false; - this.i.classList.remove("fa-copy"); - this.i.classList.add("fa-check"); - return setTimeout((() => { - this.i.classList.remove("fa-check"); - this.i.classList.add("fa-copy"); - this.input.value = this.code; - return copyable = true; - }), 1000); - }); + this.i.addEventListener("click", (function(_this) { + return function() { + var code; + if (!copyable) { + return; + } + code = _this.input.value; + navigator.clipboard.writeText(code); + _this.input.value = _this.app.translator.get("Copied!"); + copyable = false; + _this.i.classList.remove("fa-copy"); + _this.i.classList.add("fa-check"); + return setTimeout((function() { + _this.i.classList.remove("fa-check"); + _this.i.classList.add("fa-copy"); + _this.input.value = _this.code; + return copyable = true; + }), 1000); + }; + })(this)); } - set(code1) { + CodeSnippetField.prototype.set = function(code1) { this.code = code1; return this.input.value = this.code; - } + }; + + return CodeSnippetField; -}; +})(); diff --git a/static/js/assets/modelviewer.js b/static/js/assets/modelviewer.js index d3d1b480..ad3a3a2c 100644 --- a/static/js/assets/modelviewer.js +++ b/static/js/assets/modelviewer.js @@ -1,20 +1,19 @@ -this.ModelViewer = class ModelViewer { - constructor(manager) { +this.ModelViewer = (function() { + function ModelViewer(manager) { this.manager = manager; this.element = document.getElementById("model-asset-viewer"); } - updateSnippet() { + ModelViewer.prototype.updateSnippet = function() { return this.manager.code_snippet.set([ { name: "Load Model", - value: `loader = asset_manager.loadModel("${this.asset.name.replace(/-/g, - "/")}", callback)` + value: "loader = asset_manager.loadModel(\"" + (this.asset.name.replace(/-/g, "/")) + "\", callback)" } ]); - } + }; - view(asset) { + ModelViewer.prototype.view = function(asset) { var err, light, light2, s, scene, url; this.asset = asset; this.element.style.display = "block"; @@ -24,14 +23,16 @@ this.ModelViewer = class ModelViewer { s = document.createElement("script"); s.src = location.origin + "/lib/babylonjs/v4/babylon.js"; document.head.appendChild(s); - s.onload = () => { - s = document.createElement("script"); - s.src = location.origin + "/lib/babylonjs/v4/babylonjs.loaders.min.js"; - document.head.appendChild(s); - return s.onload = () => { - return this.view(asset); + s.onload = (function(_this) { + return function() { + s = document.createElement("script"); + s.src = location.origin + "/lib/babylonjs/v4/babylonjs.loaders.min.js"; + document.head.appendChild(s); + return s.onload = function() { + return _this.view(asset); + }; }; - }; + })(this); return; } if (this.engine == null) { @@ -42,9 +43,11 @@ this.ModelViewer = class ModelViewer { preserveDrawingBuffer: true }); this.element.appendChild(this.canvas); - window.addEventListener("resize", () => { - return this.resize(); - }); + window.addEventListener("resize", (function(_this) { + return function() { + return _this.resize(); + }; + })(this)); } scene = new BABYLON.Scene(this.engine); scene.clearColor = new BABYLON.Color3(.1, .2, .3); @@ -55,89 +58,91 @@ this.ModelViewer = class ModelViewer { light2 = new BABYLON.DirectionalLight("light2", new BABYLON.Vector3(1, -1, 1), scene); light2.specular = light2.diffuse = new BABYLON.Color3(1, .9, .7); light2.intensity = .5; - // box = BABYLON.MeshBuilder.CreateBox("box", {}, scene) this.createEnvironment(scene); url = asset.getURL(); if (url.startsWith("data:")) { url = "data:;base64," + url.split(",")[1]; } try { - // BABYLON.OBJFileLoader.COMPUTE_NORMALS = true - BABYLON.SceneLoader.LoadAssetContainer("", url, scene, ((container) => { - var boundingInfo, bs, center, i, j, len, len1, m, max, mesh, min, radius, ref, ref1, size; - console.info("model loaded"); - console.info(container); - container.addAllToScene(); - ref = container.meshes; - for (i = 0, len = ref.length; i < len; i++) { - m = ref[i]; - bs = m.getBoundingInfo().boundingBox; - if (typeof min === "undefined" || min === null) { - min = new BABYLON.Vector3(); - min.copyFrom(bs.minimum); - } - if (typeof max === "undefined" || max === null) { - max = new BABYLON.Vector3(); - max.copyFrom(bs.maximum); + BABYLON.SceneLoader.LoadAssetContainer("", url, scene, ((function(_this) { + return function(container) { + var boundingInfo, bs, center, i, j, len, len1, m, max, mesh, min, radius, ref, ref1, size; + console.info("model loaded"); + console.info(container); + container.addAllToScene(); + ref = container.meshes; + for (i = 0, len = ref.length; i < len; i++) { + m = ref[i]; + bs = m.getBoundingInfo().boundingBox; + if (typeof min === "undefined" || min === null) { + min = new BABYLON.Vector3(); + min.copyFrom(bs.minimum); + } + if (typeof max === "undefined" || max === null) { + max = new BABYLON.Vector3(); + max.copyFrom(bs.maximum); + } + min = BABYLON.Vector3.Minimize(min, bs.minimum); + max = BABYLON.Vector3.Maximize(max, bs.maximum); } - min = BABYLON.Vector3.Minimize(min, bs.minimum); - max = BABYLON.Vector3.Maximize(max, bs.maximum); - } - size = max.subtract(min); - boundingInfo = new BABYLON.BoundingInfo(min, max); - center = boundingInfo.boundingBox.centerWorld; - // m = BABYLON.MeshBuilder.CreateBox("bounds", {size:1}, scene) - // m.scaling.copyFrom(size) - // m.position.copyFrom(center) - // m.visibility = 0.1 - console.log("Width: ", size.x); - console.log("Height: ", size.y); - console.log("Depth: ", size.z); - console.log("Position: ", center); - radius = max.subtract(min).length(); - console.info("RADIUS = " + radius); - this.camera = new BABYLON.ArcRotateCamera("camera", Math.PI / 2, Math.PI / 2.5, radius, new BABYLON.Vector3(0, 0, 0), scene); - this.camera.attachControl(this.canvas, true); - this.camera.lowerRadiusLimit = radius / 10; - this.camera.upperRadiusLimit = radius * 10; - this.camera.maxZ = radius * 100; - this.camera.minZ = radius / 100; - this.camera.wheelDeltaPercentage = .01; - window.camera = this.camera; - this.camera.setTarget(center); - window.container = container; - if (asset.ext === "obj") { - ref1 = container.meshes; - for (j = 0, len1 = ref1.length; j < len1; j++) { - mesh = ref1[j]; - mesh.material = new BABYLON.StandardMaterial("pbrmat", scene); - mesh.material.diffuseColor = new BABYLON.Color3(1, 1, 1); - mesh.material.specularColor = new BABYLON.Color3(0, 0, 0); - mesh.material.emissiveColor = new BABYLON.Color3(0, 0, 0); - mesh.material.ambientColor = new BABYLON.Color3(.1, .1, .1); + size = max.subtract(min); + boundingInfo = new BABYLON.BoundingInfo(min, max); + center = boundingInfo.boundingBox.centerWorld; + console.log("Width: ", size.x); + console.log("Height: ", size.y); + console.log("Depth: ", size.z); + console.log("Position: ", center); + radius = max.subtract(min).length(); + console.info("RADIUS = " + radius); + _this.camera = new BABYLON.ArcRotateCamera("camera", Math.PI / 2, Math.PI / 2.5, radius, new BABYLON.Vector3(0, 0, 0), scene); + _this.camera.attachControl(_this.canvas, true); + _this.camera.lowerRadiusLimit = radius / 10; + _this.camera.upperRadiusLimit = radius * 10; + _this.camera.maxZ = radius * 100; + _this.camera.minZ = radius / 100; + _this.camera.wheelDeltaPercentage = .01; + window.camera = _this.camera; + _this.camera.setTarget(center); + window.container = container; + if (asset.ext === "obj") { + ref1 = container.meshes; + for (j = 0, len1 = ref1.length; j < len1; j++) { + mesh = ref1[j]; + mesh.material = new BABYLON.StandardMaterial("pbrmat", scene); + mesh.material.diffuseColor = new BABYLON.Color3(1, 1, 1); + mesh.material.specularColor = new BABYLON.Color3(0, 0, 0); + mesh.material.emissiveColor = new BABYLON.Color3(0, 0, 0); + mesh.material.ambientColor = new BABYLON.Color3(.1, .1, .1); + } } - } - return this.engine.runRenderLoop(() => { - return scene.render(); - }); - }), ((progress) => { - return console.info(progress); - }), ((error) => { - return console.info(error); - }), `.${asset.ext}`); + return _this.engine.runRenderLoop(function() { + return scene.render(); + }); + }; + })(this)), ((function(_this) { + return function(progress) { + return console.info(progress); + }; + })(this)), ((function(_this) { + return function(error) { + return console.info(error); + }; + })(this)), "." + asset.ext); } catch (error1) { err = error1; } this.resize(); this.asset = asset; - return setTimeout((() => { - return this.manager.checkThumbnail(asset, () => { - return this.updateThumbnail(); - }); - }), 2000); - } + return setTimeout(((function(_this) { + return function() { + return _this.manager.checkThumbnail(asset, function() { + return _this.updateThumbnail(); + }); + }; + })(this)), 2000); + }; - updateThumbnail() { + ModelViewer.prototype.updateThumbnail = function() { var canvas, context, h, m, w; canvas = document.createElement("canvas"); canvas.width = 128; @@ -151,19 +156,21 @@ this.ModelViewer = class ModelViewer { return BABYLON.Tools.CreateScreenshot(this.engine, this.camera, { width: w, height: h - }, (data) => { - var image; - image = new Image; - image.src = data; - return image.onload = () => { - context.drawImage(image, -image.width / 2, -image.height / 2); - context.restore(); - return this.manager.updateAssetIcon(this.asset, canvas); + }, (function(_this) { + return function(data) { + var image; + image = new Image; + image.src = data; + return image.onload = function() { + context.drawImage(image, -image.width / 2, -image.height / 2); + context.restore(); + return _this.manager.updateAssetIcon(_this.asset, canvas); + }; }; - }); - } + })(this)); + }; - resize() { + ModelViewer.prototype.resize = function() { var h, w; if (this.canvas) { w = this.canvas.parentNode.getBoundingClientRect().width; @@ -174,9 +181,9 @@ this.ModelViewer = class ModelViewer { if (this.engine != null) { return this.engine.resize(); } - } + }; - createEnvironment(scene) { + ModelViewer.prototype.createEnvironment = function(scene) { var createFace, files, texture; createFace = function(c1, c2) { var c, canvas, grd; @@ -184,10 +191,6 @@ this.ModelViewer = class ModelViewer { canvas.width = canvas.height = 256; c = canvas.getContext("2d"); if (c2 != null) { - // c.fillStyle = c1 - // c.fillRect 0,0,canvas.width,canvas.height/2 - // c.fillStyle = c2 - // c.fillRect 0,canvas.height/2,canvas.width,canvas.height/2 c.fillStyle = grd = c.createLinearGradient(0, 0, 0, canvas.height); grd.addColorStop(0, c1); grd.addColorStop(.48, c1); @@ -203,8 +206,8 @@ this.ModelViewer = class ModelViewer { files = [createFace("#ACE", "#864"), createFace("#BDF"), createFace("#ACE", "#864"), createFace("#ACE", "#864"), createFace("#201818"), createFace("#ACE", "#864")]; texture = BABYLON.CubeTexture.CreateFromImages(files, scene); return scene.environmentTexture = texture; - } + }; -}; + return ModelViewer; -//console.info scene.createDefaultSkybox(texture, true, 1000) +})(); diff --git a/static/js/assets/textviewer.js b/static/js/assets/textviewer.js index 5c082aac..94d1b72f 100644 --- a/static/js/assets/textviewer.js +++ b/static/js/assets/textviewer.js @@ -1,45 +1,44 @@ -this.TextViewer = class TextViewer { - constructor(manager) { +this.TextViewer = (function() { + function TextViewer(manager) { this.manager = manager; this.element = document.getElementById("text-asset-viewer"); this.app = this.manager.app; this.save_delay = 3000; this.save_time = 0; - setInterval((() => { - return this.checkSave(); - }), this.save_delay / 2); + setInterval(((function(_this) { + return function() { + return _this.checkSave(); + }; + })(this)), this.save_delay / 2); } - updateSnippet() { + TextViewer.prototype.updateSnippet = function() { switch (this.asset.ext) { case "json": return this.manager.code_snippet.set([ { name: "Load JSON as object", - value: `loader = asset_manager.loadJSON("${this.asset.name.replace(/-/g, - "/")}", callback)` + value: "loader = asset_manager.loadJSON(\"" + (this.asset.name.replace(/-/g, "/")) + "\", callback)" } ]); case "csv": return this.manager.code_snippet.set([ { name: "Load CSV file as text", - value: `loader = asset_manager.loadCSV("${this.asset.name.replace(/-/g, - "/")}", callback)` + value: "loader = asset_manager.loadCSV(\"" + (this.asset.name.replace(/-/g, "/")) + "\", callback)" } ]); case "txt": return this.manager.code_snippet.set([ { name: "Load text file", - value: `loader = asset_manager.loadText("${this.asset.name.replace(/-/g, - "/")}", callback)` + value: "loader = asset_manager.loadText(\"" + (this.asset.name.replace(/-/g, "/")) + "\", callback)" } ]); } - } + }; - view(asset) { + TextViewer.prototype.view = function(asset) { this.checkSave(true); this.element.style.display = "block"; this.asset = asset; @@ -51,9 +50,11 @@ this.TextViewer = class TextViewer { this.editor.setTheme("ace/theme/tomorrow_night_bright"); this.editor.setFontSize("12px"); this.editor.setReadOnly(false); - this.editor.getSession().on("change", () => { - return this.editorContentsChanged(); - }); + this.editor.getSession().on("change", (function(_this) { + return function() { + return _this.editorContentsChanged(); + }; + })(this)); } switch (asset.ext) { case "json": @@ -68,18 +69,19 @@ this.TextViewer = class TextViewer { if (asset.local_text != null) { return this.setText(asset, asset.local_text, asset.ext); } else { - return fetch(asset.getURL()).then((result) => { - return result.text().then((text) => { - return this.setText(asset, text, asset.ext); - }); - }); + return fetch(asset.getURL()).then((function(_this) { + return function(result) { + return result.text().then(function(text) { + return _this.setText(asset, text, asset.ext); + }); + }; + })(this)); } - } + }; - setText(asset, text, ext) { + TextViewer.prototype.setText = function(asset, text, ext) { var err; this.ignore_changes = true; - //@updateCurrentFileLock() if (ext === "json") { try { text = JSON.stringify(JSON.parse(text), null, '\t'); @@ -90,19 +92,21 @@ this.TextViewer = class TextViewer { } this.editor.setValue(text, -1); this.editor.getSession().setUndoManager(new ace.UndoManager()); - this.manager.checkThumbnail(asset, () => { - var canvas; - console.info("Must create thumbnail"); - canvas = this.createThumbnail(text, ext); - if (asset.element != null) { - asset.element.querySelector("img").src = canvas.toDataURL(); - } - return this.manager.updateAssetIcon(asset, canvas); - }); + this.manager.checkThumbnail(asset, (function(_this) { + return function() { + var canvas; + console.info("Must create thumbnail"); + canvas = _this.createThumbnail(text, ext); + if (asset.element != null) { + asset.element.querySelector("img").src = canvas.toDataURL(); + } + return _this.manager.updateAssetIcon(asset, canvas); + }; + })(this)); return this.ignore_changes = false; - } + }; - createThumbnail(text, ext) { + TextViewer.prototype.createThumbnail = function(text, ext) { var canvas, color, context, grd, i, lines; canvas = document.createElement("canvas"); canvas.width = 128; @@ -136,9 +140,9 @@ this.TextViewer = class TextViewer { } context.restore(); return canvas; - } + }; - editorContentsChanged() { + TextViewer.prototype.editorContentsChanged = function() { document.getElementById("text-asset-viewer").style.removeProperty("background"); if (this.ignore_changes) { return; @@ -147,23 +151,26 @@ this.TextViewer = class TextViewer { this.save_time = Date.now(); this.app.project.addPendingChange(this); if (this.asset != null) { - this.app.project.lockFile(`assets/${this.asset.filename}`); + this.app.project.lockFile("assets/" + this.asset.filename); return this.asset.content = this.editor.getValue(); } - } + }; - checkSave(immediate = false, callback) { + TextViewer.prototype.checkSave = function(immediate, callback) { + if (immediate == null) { + immediate = false; + } if (this.save_time > 0 && (immediate || Date.now() > this.save_time + this.save_delay)) { this.saveFile(callback); return this.save_time = 0; } - } + }; - forceSave(callback) { + TextViewer.prototype.forceSave = function(callback) { return this.checkSave(true, callback); - } + }; - saveFile(callback) { + TextViewer.prototype.saveFile = function(callback) { var err, json, saved; saved = false; if (this.asset.ext === "json") { @@ -179,24 +186,30 @@ this.TextViewer = class TextViewer { this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `assets/${this.asset.filename}`, + file: "assets/" + this.asset.filename, content: this.asset.content - }, (msg) => { - saved = true; - if (this.save_time === 0) { - this.app.project.removePendingChange(this); - } - this.asset.size = msg.size; - if (callback != null) { - return callback(); - } - }); - return setTimeout((() => { - if (!saved) { - this.save_time = Date.now(); - return console.info("retrying code save..."); - } - }), 10000); - } + }, (function(_this) { + return function(msg) { + saved = true; + if (_this.save_time === 0) { + _this.app.project.removePendingChange(_this); + } + _this.asset.size = msg.size; + if (callback != null) { + return callback(); + } + }; + })(this)); + return setTimeout(((function(_this) { + return function() { + if (!saved) { + _this.save_time = Date.now(); + return console.info("retrying code save..."); + } + }; + })(this)), 10000); + }; + + return TextViewer; -}; +})(); diff --git a/static/js/doc/documentation.js b/static/js/doc/documentation.js index 30b541e5..646054b4 100644 --- a/static/js/doc/documentation.js +++ b/static/js/doc/documentation.js @@ -1,6 +1,6 @@ -this.Documentation = class Documentation { - constructor(app) { - var e, j, k, len1, len2, list; +this.Documentation = (function() { + function Documentation(app) { + var e, fn, fn1, j, k, len1, len2, list; this.app = app; this.doc = ""; this.help = {}; @@ -8,93 +8,120 @@ this.Documentation = class Documentation { this.title_elements = []; this.sections = {}; list = document.getElementsByClassName("help-section-category"); - for (j = 0, len1 = list.length; j < len1; j++) { - e = list[j]; - ((e) => { + fn = (function(_this) { + return function(e) { var title; title = e.getElementsByClassName("help-section-title")[0]; - return title.addEventListener("click", () => { + return title.addEventListener("click", function() { if (e.classList.contains("collapsed")) { e.classList.remove("collapsed"); } else { e.classList.add("collapsed"); } - return this.updateViewPos(); + return _this.updateViewPos(); }); - })(e); + }; + })(this); + for (j = 0, len1 = list.length; j < len1; j++) { + e = list[j]; + fn(e); } list = document.getElementsByClassName("help-section-button"); - for (k = 0, len2 = list.length; k < len2; k++) { - e = list[k]; - ((e) => { - return e.addEventListener("click", () => { + fn1 = (function(_this) { + return function(e) { + return e.addEventListener("click", function() { var id, split; split = e.id.split("-"); split.splice(0, 1); id = split.join("-"); - return this.setSection(id); + return _this.setSection(id); }); - })(e); + }; + })(this); + for (k = 0, len2 = list.length; k < len2; k++) { + e = list[k]; + fn1(e); } - window.addEventListener("resize", () => { - return this.updateViewPos(); - }); + window.addEventListener("resize", (function(_this) { + return function() { + return _this.updateViewPos(); + }; + })(this)); } - stateInitialized() { - return this.load("API", (src) => { - this.buildLiveHelp(src, "API"); - if (!this.current_section) { - return setTimeout((() => { - return this.setSection("Quickstart", (() => { - return this.buildLiveHelp(this.doc, "Quickstart"); - }), null, false); - }), 100); - } else { - return this.load("Quickstart", (src) => { - return this.buildLiveHelp(src, "Quickstart"); - }); - } - }); - } + Documentation.prototype.stateInitialized = function() { + return this.load("API", (function(_this) { + return function(src) { + _this.buildLiveHelp(src, "API"); + if (!_this.current_section) { + return setTimeout((function() { + return _this.setSection("Quickstart", (function() { + return _this.buildLiveHelp(_this.doc, "Quickstart"); + }), null, false); + }), 100); + } else { + return _this.load("Quickstart", function(src) { + return _this.buildLiveHelp(src, "Quickstart"); + }); + } + }; + })(this)); + }; - pushState() { + Documentation.prototype.pushState = function() { if (this.current_section) { - return this.app.app_state.pushState(`documentation.${this.current_section}`, `/documentation/${this.current_section}/`); + return this.app.app_state.pushState("documentation." + this.current_section, "/documentation/" + this.current_section + "/"); } else { return this.app.app_state.pushState("documentation", "/documentation/"); } - } + }; - setSection(id, callback, url, push_state = true) { - var e, j, len1, list; + Documentation.prototype.setSection = function(id, callback, url, push_state) { + var e, fn, j, len1, list; + if (push_state == null) { + push_state = true; + } this.current_section = id; if (push_state) { this.pushState(); } - this.load((url != null ? url : id), (doc1) => { - this.doc = doc1; - this.update(); - if (callback != null) { - return callback(); - } - }); + this.load((url != null ? url : id), (function(_this) { + return function(doc1) { + _this.doc = doc1; + _this.update(); + if (callback != null) { + return callback(); + } + }; + })(this)); list = document.getElementsByClassName("help-section-button"); - for (j = 0, len1 = list.length; j < len1; j++) { - e = list[j]; - ((e) => { - if (e.id === `documentation-${id}`) { + fn = (function(_this) { + return function(e) { + if (e.id === ("documentation-" + id)) { e.classList.add("selected"); return e.parentNode.parentNode.classList.remove("collapsed"); } else { return e.classList.remove("selected"); } - })(e); + }; + })(this); + for (j = 0, len1 = list.length; j < len1; j++) { + e = list[j]; + fn(e); } - } + }; - load(id = "Quickstart", callback = (function() {}), lang = this.app.translator.lang) { + Documentation.prototype.load = function(id, callback, lang) { var ref1, req, url; + if (id == null) { + id = "Quickstart"; + } + if (callback == null) { + callback = (function() {}); + } + if (lang == null) { + lang = this.app.translator.lang; + } if (this.sections[id] != null) { return callback(this.sections[id]); } @@ -102,33 +129,35 @@ this.Documentation = class Documentation { lang = "en"; } req = new XMLHttpRequest(); - req.onreadystatechange = (event) => { - if (req.readyState === XMLHttpRequest.DONE) { - if (req.status === 200) { - this.sections[id] = req.responseText; - return callback(this.sections[id]); - } else if (lang !== "en") { - return this.load(id, callback, "en"); + req.onreadystatechange = (function(_this) { + return function(event) { + if (req.readyState === XMLHttpRequest.DONE) { + if (req.status === 200) { + _this.sections[id] = req.responseText; + return callback(_this.sections[id]); + } else if (lang !== "en") { + return _this.load(id, callback, "en"); + } } - } - }; + }; + })(this); if (id.startsWith("http")) { url = id; } else { - url = `/microstudio.wiki/${lang}/${lang}-${id}.md`; + url = "/microstudio.wiki/" + lang + "/" + lang + "-" + id + ".md"; } req.open("GET", url); return req.send(); - } + }; - updateViewPos() { + Documentation.prototype.updateViewPos = function() { var doc, sections; sections = document.getElementById("help-sections"); doc = document.getElementById("help-document"); - return doc.style.top = `${sections.offsetHeight}px`; - } + return doc.style.top = sections.offsetHeight + "px"; + }; - update() { + Documentation.prototype.update = function() { var e, element, j, len1, list; if (this.doc == null) { return; @@ -144,27 +173,24 @@ this.Documentation = class Documentation { e = list[j]; e.target = "_blank"; } - //lexer = new marked.Lexer({}) - //console.info lexer.lex @doc this.buildToc(); return this.updateViewPos(); - } + }; - buildToc() { - var e, element, j, len1, ref1, toc; + Documentation.prototype.buildToc = function() { + var e, element, fn, j, len1, ref1, toc; element = document.getElementById("documentation"); toc = document.getElementById("help-list"); toc.innerHTML = ""; ref1 = element.childNodes; - for (j = 0, len1 = ref1.length; j < len1; j++) { - e = ref1[j]; - ((e) => { + fn = (function(_this) { + return function(e) { var h; switch (e.tagName) { case "H1": h = document.createElement("h1"); h.innerText = e.innerText; - h.addEventListener("click", () => { + h.addEventListener("click", function() { return e.scrollIntoView(true, { behavior: "smooth" }); @@ -173,7 +199,7 @@ this.Documentation = class Documentation { case "H2": h = document.createElement("h2"); h.innerText = e.innerText; - h.addEventListener("click", () => { + h.addEventListener("click", function() { return e.scrollIntoView(true, { behavior: "smooth" }); @@ -182,18 +208,22 @@ this.Documentation = class Documentation { case "H3": h = document.createElement("h3"); h.innerText = e.innerText; - h.addEventListener("click", () => { + h.addEventListener("click", function() { return e.scrollIntoView(true, { behavior: "smooth" }); }); return toc.appendChild(h); } - })(e); + }; + })(this); + for (j = 0, len1 = ref1.length; j < len1; j++) { + e = ref1[j]; + fn(e); } - } + }; - buildLiveHelp(src, section) { + Documentation.prototype.buildLiveHelp = function(src, section) { var content, current_section, index, line, lines, ref, slugger, tline; lines = src.split("\n"); index = 0; @@ -255,10 +285,13 @@ this.Documentation = class Documentation { } index++; } - } + }; - findSuggestMatch(line, position = 0) { + Documentation.prototype.findSuggestMatch = function(line, position) { var best, err, i, index, j, k, key, known_prefixes, l, len, len1, len2, len3, len4, m, n, o, p, prefixes, q, r, ref1, ref2, ref3, ref4, ref5, res, s, split, table, v, value, within; + if (position == null) { + position = 0; + } res = []; best = 0; ref1 = this.suggest; @@ -320,7 +353,7 @@ this.Documentation = class Documentation { for (q = 0, len4 = known_prefixes.length; q < len4; q++) { p = known_prefixes[q]; if ((split[1] != null) && split[1].startsWith(p)) { - v.ref = `${split[0]}.${p}...`; + v.ref = split[0] + "." + p + "..."; } } } @@ -339,9 +372,9 @@ this.Documentation = class Documentation { } } return res; - } + }; - findHelpMatch(line) { + Documentation.prototype.findHelpMatch = function(line) { var key, ref1, res, value; res = []; ref1 = this.help; @@ -352,35 +385,36 @@ this.Documentation = class Documentation { } } return res; - } + }; - getPluginsSection() { + Documentation.prototype.getPluginsSection = function() { var help_sections, plugins_section; help_sections = document.getElementById("help-sections"); plugins_section = document.getElementById("help-plugins"); if (plugins_section == null) { plugins_section = document.createElement("div"); plugins_section.classList.add("help-section-category"); - //plugins_section.classList.add "collapsed" plugins_section.classList.add("bg-green"); plugins_section.id = "help-plugins"; help_sections.appendChild(plugins_section); - plugins_section.innerHTML = `
\n ${this.app.translator.get("Plug-ins")}\n
\n
`; - plugins_section.querySelector(".help-section-title").addEventListener("click", () => { - if (plugins_section.classList.contains("collapsed")) { - plugins_section.classList.remove("collapsed"); - } else { - plugins_section.classList.add("collapsed"); - } - return this.updateViewPos(); - }); + plugins_section.innerHTML = "
\n " + (this.app.translator.get("Plug-ins")) + "\n
\n
"; + plugins_section.querySelector(".help-section-title").addEventListener("click", (function(_this) { + return function() { + if (plugins_section.classList.contains("collapsed")) { + plugins_section.classList.remove("collapsed"); + } else { + plugins_section.classList.add("collapsed"); + } + return _this.updateViewPos(); + }; + })(this)); } return plugins_section; - } + }; - addPlugin(id, title, link) { + Documentation.prototype.addPlugin = function(id, title, link) { var doc, plugins_section; - id = `documentation-${id}`; + id = "documentation-" + id; if (!document.getElementById(id)) { plugins_section = this.getPluginsSection(); doc = document.createElement("div"); @@ -388,16 +422,18 @@ this.Documentation = class Documentation { doc.classList.add("help-section-button"); doc.innerText = title; plugins_section.querySelector(".help-section-content").appendChild(doc); - doc.addEventListener("click", () => { - return this.setSection(link); - }); + doc.addEventListener("click", (function(_this) { + return function() { + return _this.setSection(link); + }; + })(this)); return this.updateViewPos(); } - } + }; - removePlugin(id) { + Documentation.prototype.removePlugin = function(id) { var element, parent; - id = `documentation-${id}`; + id = "documentation-" + id; element = document.getElementById(id); if (element != null) { parent = element.parentNode; @@ -407,44 +443,45 @@ this.Documentation = class Documentation { } return this.updateViewPos(); } - } + }; - removeAllPlugins() { + Documentation.prototype.removeAllPlugins = function() { var plugins_section; plugins_section = document.getElementById("help-plugins"); if (plugins_section != null) { plugins_section.parentNode.removeChild(plugins_section); return this.updateViewPos(); } - } + }; - getLibsSection() { + Documentation.prototype.getLibsSection = function() { var help_sections, libs_section; help_sections = document.getElementById("help-sections"); libs_section = document.getElementById("help-libraries"); if (libs_section == null) { libs_section = document.createElement("div"); libs_section.classList.add("help-section-category"); - //libs_section.classList.add "collapsed" libs_section.classList.add("bg-purple"); libs_section.id = "help-libraries"; help_sections.appendChild(libs_section); - libs_section.innerHTML = `
\n ${this.app.translator.get("Libraries in use")}\n
\n
`; - libs_section.querySelector(".help-section-title").addEventListener("click", () => { - if (libs_section.classList.contains("collapsed")) { - libs_section.classList.remove("collapsed"); - } else { - libs_section.classList.add("collapsed"); - } - return this.updateViewPos(); - }); + libs_section.innerHTML = "
\n " + (this.app.translator.get("Libraries in use")) + "\n
\n
"; + libs_section.querySelector(".help-section-title").addEventListener("click", (function(_this) { + return function() { + if (libs_section.classList.contains("collapsed")) { + libs_section.classList.remove("collapsed"); + } else { + libs_section.classList.add("collapsed"); + } + return _this.updateViewPos(); + }; + })(this)); } return libs_section; - } + }; - addLib(id, title, link) { + Documentation.prototype.addLib = function(id, title, link) { var doc, libs_section; - id = `documentation-${id}`; + id = "documentation-" + id; if (!document.getElementById(id)) { libs_section = this.getLibsSection(); doc = document.createElement("div"); @@ -452,16 +489,18 @@ this.Documentation = class Documentation { doc.classList.add("help-section-button"); doc.innerText = title; libs_section.querySelector(".help-section-content").appendChild(doc); - doc.addEventListener("click", () => { - return this.setSection(link); - }); + doc.addEventListener("click", (function(_this) { + return function() { + return _this.setSection(link); + }; + })(this)); return this.updateViewPos(); } - } + }; - removeLib(id) { + Documentation.prototype.removeLib = function(id) { var element, parent; - id = `documentation-${id}`; + id = "documentation-" + id; element = document.getElementById(id); if (element != null) { parent = element.parentNode; @@ -471,15 +510,17 @@ this.Documentation = class Documentation { } return this.updateViewPos(); } - } + }; - removeAllLibs() { + Documentation.prototype.removeAllLibs = function() { var libs_section; libs_section = document.getElementById("help-libraries"); if (libs_section != null) { libs_section.parentNode.removeChild(libs_section); return this.updateViewPos(); } - } + }; + + return Documentation; -}; +})(); diff --git a/static/js/editor/editor.js b/static/js/editor/editor.js index ad9eb40a..fa558c0c 100644 --- a/static/js/editor/editor.js +++ b/static/js/editor/editor.js @@ -1,9 +1,13 @@ -var indexOf = [].indexOf; +var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; -this.Editor = class Editor extends Manager { - constructor(app) { +this.Editor = (function(superClass) { + extend(Editor, superClass); + + function Editor(app) { var f; - super(app); + Editor.__super__.constructor.call(this, app); this.language = this.app.languages.microscript; this.folder = "ms"; this.item = "source"; @@ -23,114 +27,135 @@ this.Editor = class Editor extends Manager { this.editor.getSession().setOptions({ tabSize: 2, useSoftTabs: true, - useWorker: false // disables lua autocorrection ; preserves syntax coloring + useWorker: false }); - //enableBasicAutocompletion: true - //enableSnippets: true - //enableLiveAutocompletion: true this.update_delay = 50; this.update_time = 0; - setInterval((() => { - return this.check(); - }), this.update_delay / 2); + setInterval(((function(_this) { + return function() { + return _this.check(); + }; + })(this)), this.update_delay / 2); this.save_delay = 3000; this.save_time = 0; - setInterval((() => { - return this.checkSave(); - }), this.save_delay / 2); + setInterval(((function(_this) { + return function() { + return _this.checkSave(); + }; + })(this)), this.save_delay / 2); this.keydown_count = 0; this.lines_of_code = 0; - this.editor.getSession().on("change", () => { - return this.editorContentsChanged(); - }); - this.editor.on("blur", () => { - this.app.runwindow.rulercanvas.hide(); - return document.getElementById("help-window").classList.add("disabled"); - }); - this.editor.on("focus", () => { - this.checkValueToolButtons(); - this.cancelValueTool(); - if (this.show_help) { - document.getElementById("help-window").classList.remove("disabled"); - return this.liveHelp(); - } - }); + this.editor.getSession().on("change", (function(_this) { + return function() { + return _this.editorContentsChanged(); + }; + })(this)); + this.editor.on("blur", (function(_this) { + return function() { + _this.app.runwindow.rulercanvas.hide(); + return document.getElementById("help-window").classList.add("disabled"); + }; + })(this)); + this.editor.on("focus", (function(_this) { + return function() { + _this.checkValueToolButtons(); + _this.cancelValueTool(); + if (_this.show_help) { + document.getElementById("help-window").classList.remove("disabled"); + return _this.liveHelp(); + } + }; + })(this)); this.RULER_FUNCTIONS = ["fillRect", "fillRound", "fillRoundRect", "drawRect", "drawRound", "drawRoundRect", "drawSprite", "drawMap", "drawText", "drawLine", "drawPolygon", "fillPolygon"]; this.number_tool_button = document.getElementById("number-value-tool-button"); this.color_tool_button = document.getElementById("color-value-tool-button"); - this.number_tool_button.addEventListener("click", (event) => { - event.preventDefault(); - if (this.value_tool) { - return this.cancelValueTool(); - } else { - return this.showValueTool(); - } - }); - this.color_tool_button.addEventListener("click", (event) => { - event.preventDefault(); - if (this.value_tool) { - return this.cancelValueTool(); - } else { - return this.showValueTool(); - } - }); - this.editor.selection.on("changeCursor", () => { - this.liveHelp(); - if (this.value_tool == null) { - this.drawHelper(); - } - return this.checkValueToolButtons(); - }); + this.number_tool_button.addEventListener("click", (function(_this) { + return function(event) { + event.preventDefault(); + if (_this.value_tool) { + return _this.cancelValueTool(); + } else { + return _this.showValueTool(); + } + }; + })(this)); + this.color_tool_button.addEventListener("click", (function(_this) { + return function(event) { + event.preventDefault(); + if (_this.value_tool) { + return _this.cancelValueTool(); + } else { + return _this.showValueTool(); + } + }; + })(this)); + this.editor.selection.on("changeCursor", (function(_this) { + return function() { + _this.liveHelp(); + if (_this.value_tool == null) { + _this.drawHelper(); + } + return _this.checkValueToolButtons(); + }; + })(this)); this.show_help = true; - document.querySelector("#help-window-content").addEventListener("mousedown", (event) => { - event.stopPropagation(); - this.show_help = !this.show_help; - event.preventDefault(); - if (!this.show_help) { - document.querySelector("#help-window").classList.add("disabled"); - return document.querySelector("#help-window-content").classList.remove("displaycontent"); - } else { - document.querySelector("#help-window").classList.remove("disabled"); - this.liveHelp(); - return this.editor.focus(); - } - }); - document.addEventListener("keydown", (event) => { - var err; - try { - if (event.keyCode === 13 && this.editor.getSelectionRange().start.column > 1) { - this.lines_of_code += 1; - } else if (event.keyCode !== 13) { - this.keydown_count += 1; + document.querySelector("#help-window-content").addEventListener("mousedown", (function(_this) { + return function(event) { + event.stopPropagation(); + _this.show_help = !_this.show_help; + event.preventDefault(); + if (!_this.show_help) { + document.querySelector("#help-window").classList.add("disabled"); + return document.querySelector("#help-window-content").classList.remove("displaycontent"); + } else { + document.querySelector("#help-window").classList.remove("disabled"); + _this.liveHelp(); + return _this.editor.focus(); } - } catch (error) { - err = error; - console.error(err); - } - if (event.keyCode !== 17 && event.ctrlKey) { - this.cancelValueTool(); - this.ignore_ctrl_up = true; - } - }); - document.addEventListener("keyup", (event) => { - if (document.getElementById("editor-view").offsetParent == null) { - return; - } - if (event.keyCode === 17 && !event.altKey) { - if (this.ignore_ctrl_up) { - this.ignore_ctrl_up = false; + }; + })(this)); + document.addEventListener("keydown", (function(_this) { + return function(event) { + var err; + try { + if (event.keyCode === 13 && _this.editor.getSelectionRange().start.column > 1) { + _this.lines_of_code += 1; + } else if (event.keyCode !== 13) { + _this.keydown_count += 1; + } + } catch (error) { + err = error; + console.error(err); + } + if (event.keyCode !== 17 && event.ctrlKey) { + _this.cancelValueTool(); + _this.ignore_ctrl_up = true; + } + }; + })(this)); + document.addEventListener("keyup", (function(_this) { + return function(event) { + if (document.getElementById("editor-view").offsetParent == null) { return; } - if (this.value_tool) { - this.cancelValueTool(); - } else { - this.showValueTool(); + if (event.keyCode === 17 && !event.altKey) { + if (_this.ignore_ctrl_up) { + _this.ignore_ctrl_up = false; + return; + } + if (_this.value_tool) { + _this.cancelValueTool(); + } else { + _this.showValueTool(); + } } - } - }); - document.querySelector("#code-search").addEventListener("click", (event) => { - return this.editor.execCommand("find"); - }); + }; + })(this)); + document.querySelector("#code-search").addEventListener("click", (function(_this) { + return function(event) { + return _this.editor.execCommand("find"); + }; + })(this)); this.font_size = 14; this.MIN_FONT_SIZE = 8; this.MAX_FONT_SIZE = 30; @@ -146,29 +171,35 @@ this.Editor = class Editor extends Manager { } } catch (error) {} } - document.querySelector("#code-font-minus").addEventListener("click", (event) => { - this.font_size = Math.max(this.MIN_FONT_SIZE, this.font_size - 1); - this.editor.setOptions({ - fontSize: this.font_size - }); - return localStorage.setItem("code_editor_font_size", this.font_size); - }); - document.querySelector("#code-font-plus").addEventListener("click", (event) => { - this.font_size = Math.min(this.MAX_FONT_SIZE, this.font_size + 1); - this.editor.setOptions({ - fontSize: this.font_size - }); - return localStorage.setItem("code_editor_font_size", this.font_size); - }); + document.querySelector("#code-font-minus").addEventListener("click", (function(_this) { + return function(event) { + _this.font_size = Math.max(_this.MIN_FONT_SIZE, _this.font_size - 1); + _this.editor.setOptions({ + fontSize: _this.font_size + }); + return localStorage.setItem("code_editor_font_size", _this.font_size); + }; + })(this)); + document.querySelector("#code-font-plus").addEventListener("click", (function(_this) { + return function(event) { + _this.font_size = Math.min(_this.MAX_FONT_SIZE, _this.font_size + 1); + _this.editor.setOptions({ + fontSize: _this.font_size + }); + return localStorage.setItem("code_editor_font_size", _this.font_size); + }; + })(this)); this.lib_manager_button = document.querySelector("#manage-libs-button"); this.lib_manager = document.querySelector(".lib-manager-container"); this.editor_view = document.querySelector("#editor-view"); - this.lib_manager_button.addEventListener("click", () => { - return this.toggleLibManager(); - }); + this.lib_manager_button.addEventListener("click", (function(_this) { + return function() { + return _this.toggleLibManager(); + }; + })(this)); } - updateLanguage() { + Editor.prototype.updateLanguage = function() { if (this.app.project) { switch (this.app.project.language) { case "python": @@ -189,9 +220,9 @@ this.Editor = class Editor extends Manager { } this.editor.getSession().setMode(this.language.ace_mode); return this.updateSourceLanguage(); - } + }; - checkEmbeddedJavaScript(src) { + Editor.prototype.checkEmbeddedJavaScript = function(src) { if (this.app.project.language === "microscript_v2") { if (/^\s*\/\/\s*javascript\s*\n/.test(src)) { if (this.language !== this.app.languages.javascript) { @@ -205,9 +236,9 @@ this.Editor = class Editor extends Manager { } } } - } + }; - editorContentsChanged() { + Editor.prototype.editorContentsChanged = function() { var source, src; if (this.ignore_changes) { return; @@ -218,7 +249,7 @@ this.Editor = class Editor extends Manager { this.save_time = Date.now(); this.app.project.addPendingChange(this); if (this.selected_source != null) { - this.app.project.lockFile(`ms/${this.selected_source}.ms`); + this.app.project.lockFile("ms/" + this.selected_source + ".ms"); source = this.app.project.getSource(this.selected_source); if (source != null) { source.content = this.getCode(); @@ -227,9 +258,9 @@ this.Editor = class Editor extends Manager { if (this.value_tool == null) { return this.drawHelper(); } - } + }; - check() { + Editor.prototype.check = function() { var p, parser; if (this.update_time > 0 && (this.value_tool || Date.now() > this.update_time + this.update_delay)) { this.update_time = 0; @@ -243,27 +274,30 @@ this.Editor = class Editor extends Manager { return this.app.runwindow.updateCode(this.selected_source + ".ms", this.getCode()); } } - } + }; - getCurrentLine() { + Editor.prototype.getCurrentLine = function() { var range, row; range = this.editor.getSelectionRange(); row = range.start.row; return this.editor.session.getLine(row); - } + }; - checkSave(immediate = false, callback) { + Editor.prototype.checkSave = function(immediate, callback) { + if (immediate == null) { + immediate = false; + } if (this.save_time > 0 && (immediate || Date.now() > this.save_time + this.save_delay)) { this.saveCode(callback); return this.save_time = 0; } - } + }; - forceSave(callback) { + Editor.prototype.forceSave = function(callback) { return this.checkSave(true, callback); - } + }; - saveCode(callback) { + Editor.prototype.saveCode = function(callback) { var keycount, lines, saved, source; source = this.app.project.getSource(this.selected_source); saved = false; @@ -274,63 +308,69 @@ this.Editor = class Editor extends Manager { this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `ms/${this.selected_source}.ms`, + file: "ms/" + this.selected_source + ".ms", characters: keycount, lines: lines, content: this.getCode() - }, (msg) => { - saved = true; - if (this.save_time === 0) { - this.app.project.removePendingChange(this); - } - if (source) { - source.size = msg.size; - } - if (callback != null) { - return callback(); - } - }); - return setTimeout((() => { - if (!saved) { - this.save_time = Date.now(); - return console.info("retrying code save..."); - } - }), 10000); - } + }, (function(_this) { + return function(msg) { + saved = true; + if (_this.save_time === 0) { + _this.app.project.removePendingChange(_this); + } + if (source) { + source.size = msg.size; + } + if (callback != null) { + return callback(); + } + }; + })(this)); + return setTimeout(((function(_this) { + return function() { + if (!saved) { + _this.save_time = Date.now(); + return console.info("retrying code save..."); + } + }; + })(this)), 10000); + }; - getCode() { + Editor.prototype.getCode = function() { return this.editor.getValue(); - } + }; - setCode(code) { + Editor.prototype.setCode = function(code) { this.ignore_changes = true; this.editor.setValue(code, -1); this.editor.getSession().setUndoManager(new ace.UndoManager()); this.ignore_changes = false; this.updateCurrentFileLock(); return this.checkEmbeddedJavaScript(code); - } + }; - addDocButton(pointer, section) { + Editor.prototype.addDocButton = function(pointer, section) { var button, content; content = document.querySelector("#help-window .content"); button = document.createElement("div"); button.classList.add("see-doc-button"); button.innerHTML = " " + this.app.translator.get("View doc"); - button.addEventListener("mousedown", (event) => { - var element; - event.stopPropagation(); - this.app.documentation.setSection(section || "API"); - this.app.appui.setMainSection("help", true); - element = document.getElementById(pointer); - if (element != null) { - return element.scrollIntoView(); - } - }); + button.addEventListener("mousedown", (function(_this) { + return function(event) { + var element; + event.stopPropagation(); + _this.app.documentation.setSection(section || "API"); + _this.app.appui.setMainSection("help", true); + element = document.getElementById(pointer); + if (element != null) { + return element.scrollIntoView(); + } + }; + })(this)); return content.insertBefore(button, content.firstChild); - } + }; - liveHelp() { + Editor.prototype.liveHelp = function() { var c, column, content, help, j, len, line, md, res, suggest; if (!this.show_help) { return; @@ -378,9 +418,9 @@ this.Editor = class Editor extends Manager { c.classList.add("displaycontent"); return c.classList.remove("vertical"); } - } + }; - tokenizeLine(line) { + Editor.prototype.tokenizeLine = function(line) { var err, index, list, token, tokenizer; tokenizer = new Tokenizer(line.replace(":", ".")); index = 0; @@ -402,9 +442,9 @@ this.Editor = class Editor extends Manager { err = error; } return list; - } + }; - checkValueToolButtons() { + Editor.prototype.checkValueToolButtons = function() { var column, index, j, len, line, list, range, ref, row, token; range = this.editor.getSelectionRange(); row = range.start.row; @@ -440,14 +480,14 @@ this.Editor = class Editor extends Manager { } this.color_tool_button.style.display = "none"; return this.number_tool_button.style.display = "none"; - } + }; - hideValueToolButtons() { + Editor.prototype.hideValueToolButtons = function() { this.color_tool_button.style.display = "none"; return this.number_tool_button.style.display = "none"; - } + }; - showValueTool() { + Editor.prototype.showValueTool = function() { var column, end, endcolumn, index, j, len, line, list, pos, range, ref, ref1, row, start, start_token, token, value; if (this.value_tool != null) { return; @@ -491,32 +531,10 @@ this.Editor = class Editor extends Manager { start = line.substring(0, start_token.start); end = line.substring(token.end, line.length); pos = this.editor.renderer.$cursorLayer.getPixelPosition(range.start, true); - //@editor.selection.setRange(new ace.Range(row,start_token.start,row,token.end),true) this.editor.blur(); - this.value_tool = new ValueTool(this, pos.left, pos.top, value, (value) => { - this.editor.session.replace({ - start: { - row: row, - column: 0 - }, - end: { - row: row, - column: Number.MAX_VALUE - } - }, start + value + end); - this.editor.selection.setRange(new ace.Range(row, start_token.start, row, start_token.start + ("" + value).length), true); - return this.drawHelper(row, column); - }); - return true; - case Token.TYPE_STRING: - if (RegexLib.csscolor.test(token.token.value)) { - start = line.substring(0, token.start); - end = line.substring(token.end, line.length); - pos = this.editor.renderer.$cursorLayer.getPixelPosition(range.start, true); - this.editor.blur(); - this.value_tool = new ColorValueTool(this, pos.left, pos.top, token.token.value, (value) => { - value = `"${value}"`; - return this.editor.session.replace({ + this.value_tool = new ValueTool(this, pos.left, pos.top, value, (function(_this) { + return function(value) { + _this.editor.session.replace({ start: { row: row, column: 0 @@ -526,74 +544,103 @@ this.Editor = class Editor extends Manager { column: Number.MAX_VALUE } }, start + value + end); - }); + _this.editor.selection.setRange(new ace.Range(row, start_token.start, row, start_token.start + ("" + value).length), true); + return _this.drawHelper(row, column); + }; + })(this)); + return true; + case Token.TYPE_STRING: + if (RegexLib.csscolor.test(token.token.value)) { + start = line.substring(0, token.start); + end = line.substring(token.end, line.length); + pos = this.editor.renderer.$cursorLayer.getPixelPosition(range.start, true); + this.editor.blur(); + this.value_tool = new ColorValueTool(this, pos.left, pos.top, token.token.value, (function(_this) { + return function(value) { + value = "\"" + value + "\""; + return _this.editor.session.replace({ + start: { + row: row, + column: 0 + }, + end: { + row: row, + column: Number.MAX_VALUE + } + }, start + value + end); + }; + })(this)); return true; } } } return false; - } + }; - cancelValueTool() { + Editor.prototype.cancelValueTool = function() { if (this.value_tool) { this.value_tool.dispose(); this.value_tool = null; this.app.runwindow.rulercanvas.hide(); return this.editor.focus(); } - } + }; - evalArg(arg, callback) { + Editor.prototype.evalArg = function(arg, callback) { if (document.getElementById("runiframe") != null) { return this.app.runwindow.runCommand(arg, callback); } else { return callback(isFinite(arg) ? arg * 1 : 0); } - } + }; - drawHelper(row, column) { + Editor.prototype.drawHelper = function(row, column) { var args, err, funk, i, j, ref, res; try { res = this.analyzeLine(row, column); if (res != null) { if (this.app.project.language.startsWith("microscript")) { - if (res.function.indexOf("Polygon") > 0 || res.function === "drawLine") { + if (res["function"].indexOf("Polygon") > 0 || res["function"] === "drawLine") { args = []; - funk = (i) => { - return this.evalArg(res.args[i], (v) => { - args[i] = v; - if (i < res.args.length - 1) { - return funk(i + 1); - } else { - return this.app.runwindow.rulercanvas.showPolygon(args, res.arg); - } - }); - }; + funk = (function(_this) { + return function(i) { + return _this.evalArg(res.args[i], function(v) { + args[i] = v; + if (i < res.args.length - 1) { + return funk(i + 1); + } else { + return _this.app.runwindow.rulercanvas.showPolygon(args, res.arg); + } + }); + }; + })(this); return funk(0); } else { - return this.evalArg(res.args[0], (v1) => { - return this.evalArg(res.args[1], (v2) => { - return this.evalArg(res.args[2], (v3) => { - return this.evalArg(res.args[3], (v4) => { - switch (res.arg) { - case 0: - return this.app.runwindow.rulercanvas.showX(v1, v2, v3, v4); - case 1: - return this.app.runwindow.rulercanvas.showY(v1, v2, v3, v4); - case 2: - return this.app.runwindow.rulercanvas.showW(v1, v2, v3, v4); - case 3: - return this.app.runwindow.rulercanvas.showH(v1, v2, v3, v4); - default: - return this.app.runwindow.rulercanvas.showBox(v1, v2, v3, v4); - } + return this.evalArg(res.args[0], (function(_this) { + return function(v1) { + return _this.evalArg(res.args[1], function(v2) { + return _this.evalArg(res.args[2], function(v3) { + return _this.evalArg(res.args[3], function(v4) { + switch (res.arg) { + case 0: + return _this.app.runwindow.rulercanvas.showX(v1, v2, v3, v4); + case 1: + return _this.app.runwindow.rulercanvas.showY(v1, v2, v3, v4); + case 2: + return _this.app.runwindow.rulercanvas.showW(v1, v2, v3, v4); + case 3: + return _this.app.runwindow.rulercanvas.showH(v1, v2, v3, v4); + default: + return _this.app.runwindow.rulercanvas.showBox(v1, v2, v3, v4); + } + }); }); }); - }); - }); + }; + })(this)); } } else { - if (res.function.indexOf("Polygon") > 0 || res.function === "drawLine") { + if (res["function"].indexOf("Polygon") > 0 || res["function"] === "drawLine") { args = res.args; return this.app.runwindow.rulercanvas.showPolygon(args, res.arg); } else { @@ -622,9 +669,9 @@ this.Editor = class Editor extends Manager { err = error; return console.error(err); } - } + }; - analyzeLine(row, column) { + Editor.prototype.analyzeLine = function(row, column) { var a, arg, arg_value, args, f, i, j, len, line, p, parser, range, ref, ref1, ref2; range = this.editor.getSelectionRange(); if ((row == null) || (column == null)) { @@ -670,7 +717,7 @@ this.Editor = class Editor extends Manager { } } return { - function: f.expression.chain[0].value, + "function": f.expression.chain[0].value, arg: arg, value: arg_value, args: args @@ -678,9 +725,9 @@ this.Editor = class Editor extends Manager { } } return null; - } + }; - updateSourceLanguage() { + Editor.prototype.updateSourceLanguage = function() { var element, lang; lang = this.app.project.language.split("_")[0]; element = document.querySelector("#source-asset-bar .language"); @@ -688,15 +735,14 @@ this.Editor = class Editor extends Manager { element.className = ""; element.classList.add(lang); return element.classList.add("language"); - } + }; - // document.getElementById("code-toolbar").innerHTML += "#{lang}" - setSelectedItem(name) { + Editor.prototype.setSelectedItem = function(name) { this.setSelectedSource(name); - return super.setSelectedItem(name); - } + return Editor.__super__.setSelectedItem.call(this, name); + }; - setSelectedSource(name) { + Editor.prototype.setSelectedSource = function(name) { var different, source; this.toggleLibManager(false); this.checkSave(true); @@ -723,10 +769,10 @@ this.Editor = class Editor extends Manager { } else { return this.setCode(""); } - } + }; - projectOpened() { - super.projectOpened(); + Editor.prototype.projectOpened = function() { + Editor.__super__.projectOpened.call(this); this.sessions = {}; this.app.project.addListener(this); this.app.runwindow.resetButtons(); @@ -735,10 +781,10 @@ this.Editor = class Editor extends Manager { this.updateRunLink(); this.updateLanguage(); return this.update(); - } + }; - projectUpdate(change) { - super.projectUpdate(change); + Editor.prototype.projectUpdate = function(change) { + Editor.__super__.projectUpdate.call(this, change); if (change instanceof ProjectSource) { if (this.selected_source != null) { if (change === this.app.project.getSource(this.selected_source)) { @@ -753,9 +799,9 @@ this.Editor = class Editor extends Manager { } else if (change === "annotations") { return this.updateAnnotations(); } - } + }; - updateAnnotations() { + Editor.prototype.updateAnnotations = function() { var source; if (this.selected_source != null) { source = this.app.project.getSource(this.selected_source); @@ -763,16 +809,16 @@ this.Editor = class Editor extends Manager { return this.editor.session.setAnnotations(source.annotations || []); } } - } + }; - updateCurrentFileLock() { + Editor.prototype.updateCurrentFileLock = function() { var lock, source, user; lock = document.getElementById("editor-locked"); if (this.selected_source != null) { - if (this.app.project.isLocked(`ms/${this.selected_source}.ms`)) { + if (this.app.project.isLocked("ms/" + this.selected_source + ".ms")) { this.editor.setReadOnly(true); - user = this.app.project.isLocked(`ms/${this.selected_source}.ms`).user; - return this.showLock(` Locked by ${user}`, this.app.appui.createFriendColor(user)); + user = this.app.project.isLocked("ms/" + this.selected_source + ".ms").user; + return this.showLock(" Locked by " + user, this.app.appui.createFriendColor(user)); } else { source = this.app.project.getSource(this.selected_source); if ((source != null) && !source.fetched) { @@ -787,67 +833,77 @@ this.Editor = class Editor extends Manager { this.hideLock(); return this.editor.setReadOnly(true); } - } + }; - showLock(html, color) { + Editor.prototype.showLock = function(html, color) { var lock; lock = document.getElementById("editor-locked"); this.lock_shown = true; - lock.style = `display: block; background: ${color}; opacity: 1`; + lock.style = "display: block; background: " + color + "; opacity: 1"; lock.innerHTML = html; return document.getElementById("editor-view").style.opacity = .5; - } + }; - hideLock() { + Editor.prototype.hideLock = function() { var lock; lock = document.getElementById("editor-locked"); this.lock_shown = false; lock.style.opacity = 0; document.getElementById("editor-view").style.opacity = 1; - return setTimeout((() => { - if (!this.lock_shown) { - return lock.style.display = "none"; - } - }), 1000); - } + return setTimeout(((function(_this) { + return function() { + if (!_this.lock_shown) { + return lock.style.display = "none"; + } + }; + })(this)), 1000); + }; - selectedItemRenamed() { + Editor.prototype.selectedItemRenamed = function() { return this.selected_source = this.selected_item; - } + }; - rebuildList() { - super.rebuildList(); + Editor.prototype.rebuildList = function() { + Editor.__super__.rebuildList.call(this); if ((this.selected_source == null) || (this.app.project.getSource(this.selected_source) == null)) { if (this.app.project.source_list.length > 0) { return this.setSelectedItem(this.app.project.source_list[0].name); } } - } + }; - fileDropped(file, folder) { + Editor.prototype.fileDropped = function(file, folder) { var reader; - console.info(`processing ${file.name}`); + console.info("processing " + file.name); console.info("folder: " + folder); reader = new FileReader(); - reader.addEventListener("load", () => { - var name; - console.info("file read, size = " + reader.result.length); - if (reader.result.length > 1000000) { - return; - } - name = file.name.split(".")[0]; - name = RegexLib.fixFilename(name); - console.info(reader.result); - return this.createAsset(folder, name, reader.result); - }); + reader.addEventListener("load", (function(_this) { + return function() { + var name; + console.info("file read, size = " + reader.result.length); + if (reader.result.length > 1000000) { + return; + } + name = file.name.split(".")[0]; + name = RegexLib.fixFilename(name); + console.info(reader.result); + return _this.createAsset(folder, name, reader.result); + }; + })(this)); return reader.readAsText(file); - } + }; - createAsset(folder, name = "source", content = "") { + Editor.prototype.createAsset = function(folder, name, content) { var source; + if (name == null) { + name = "source"; + } + if (content == null) { + content = ""; + } this.checkSave(true); if (folder != null) { - name = folder.getFullDashPath() + `-${name}`; + name = folder.getFullDashPath() + ("-" + name); folder.setOpen(true); } source = this.app.project.createSource(name); @@ -856,24 +912,26 @@ this.Editor = class Editor extends Manager { return this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `ms/${name}.ms`, + file: "ms/" + name + ".ms", properties: {}, content: content - }, (msg) => { - console.info(msg); - this.app.project.updateSourceList(); - return this.setSelectedItem(name); - }); - } + }, (function(_this) { + return function(msg) { + console.info(msg); + _this.app.project.updateSourceList(); + return _this.setSelectedItem(name); + }; + })(this)); + }; - updateRunLink() { + Editor.prototype.updateRunLink = function() { var element, iframe, qrcode, url; element = document.getElementById("run-link"); if (this.app.project != null) { url = location.origin.replace(".dev", ".io") + "/"; url += this.app.project.owner.nick + "/"; url += this.app.project.slug + "/"; - if (!this.app.project.public) { + if (!this.app.project["public"]) { url += this.app.project.code + "/"; } element.innerText = url; @@ -885,19 +943,24 @@ this.Editor = class Editor extends Manager { } return qrcode = QRCode.toDataURL(url, { margin: 0 - }, (err, url) => { - var img; - if ((err == null) && (url != null)) { - img = new Image; - img.src = url; - document.getElementById("qrcode-button").innerHTML = ""; - return document.getElementById("qrcode-button").appendChild(img); - } - }); + }, (function(_this) { + return function(err, url) { + var img; + if ((err == null) && (url != null)) { + img = new Image; + img.src = url; + document.getElementById("qrcode-button").innerHTML = ""; + return document.getElementById("qrcode-button").appendChild(img); + } + }; + })(this)); } - } + }; - toggleLibManager(view = this.editor_view.style.display !== "none") { + Editor.prototype.toggleLibManager = function(view) { + if (view == null) { + view = this.editor_view.style.display !== "none"; + } if (view) { this.lib_manager.style.display = "block"; this.editor_view.style.display = "none"; @@ -907,6 +970,8 @@ this.Editor = class Editor extends Manager { this.editor_view.style.display = "block"; return this.lib_manager_button.classList.remove("selected"); } - } + }; + + return Editor; -}; +})(Manager); diff --git a/static/js/editor/runwindow.js b/static/js/editor/runwindow.js index 1d4dd3e2..4d3056b3 100644 --- a/static/js/editor/runwindow.js +++ b/static/js/editor/runwindow.js @@ -1,60 +1,90 @@ -this.RunWindow = class RunWindow { - constructor(app) { +this.RunWindow = (function() { + function RunWindow(app) { this.app = app; - this.app.appui.setAction("run-button", () => { - return this.play(); - }); - this.app.appui.setAction("pause-button", () => { - return this.pause(); - }); - this.app.appui.setAction("reload-button", () => { - return this.reload(); - }); - this.app.appui.setAction("run-button-win", () => { - return this.play(); - }); - this.app.appui.setAction("pause-button-win", () => { - return this.pause(); - }); - this.app.appui.setAction("reload-button-win", () => { - return this.reload(); - }); - this.app.appui.setAction("detach-button", () => { - return this.detach(); - }); - this.app.appui.setAction("qrcode-button", () => { - return this.showQRCode(); - }); - this.app.appui.setAction("take-picture-button", () => { - return this.takePicture(); - }); - this.app.appui.setAction("step-forward-button", () => { - return this.stepForward(); - }); - this.app.appui.setAction("step-forward-button-win", () => { - return this.stepForward(); - }); + this.app.appui.setAction("run-button", (function(_this) { + return function() { + return _this.play(); + }; + })(this)); + this.app.appui.setAction("pause-button", (function(_this) { + return function() { + return _this.pause(); + }; + })(this)); + this.app.appui.setAction("reload-button", (function(_this) { + return function() { + return _this.reload(); + }; + })(this)); + this.app.appui.setAction("run-button-win", (function(_this) { + return function() { + return _this.play(); + }; + })(this)); + this.app.appui.setAction("pause-button-win", (function(_this) { + return function() { + return _this.pause(); + }; + })(this)); + this.app.appui.setAction("reload-button-win", (function(_this) { + return function() { + return _this.reload(); + }; + })(this)); + this.app.appui.setAction("detach-button", (function(_this) { + return function() { + return _this.detach(); + }; + })(this)); + this.app.appui.setAction("qrcode-button", (function(_this) { + return function() { + return _this.showQRCode(); + }; + })(this)); + this.app.appui.setAction("take-picture-button", (function(_this) { + return function() { + return _this.takePicture(); + }; + })(this)); + this.app.appui.setAction("step-forward-button", (function(_this) { + return function() { + return _this.stepForward(); + }; + })(this)); + this.app.appui.setAction("step-forward-button-win", (function(_this) { + return function() { + return _this.stepForward(); + }; + })(this)); if (window.ms_standalone) { document.getElementById("qrcode-button").style.display = "none"; } - this.app.appui.setAction("clear-button", () => { - return this.clear(); - }); - this.app.appui.setAction("console-options-button", () => { - return this.toggleConsoleOptions(); - }); + this.app.appui.setAction("clear-button", (function(_this) { + return function() { + return _this.clear(); + }; + })(this)); + this.app.appui.setAction("console-options-button", (function(_this) { + return function() { + return _this.toggleConsoleOptions(); + }; + })(this)); this.rulercanvas = new RulerCanvas(this.app); - window.addEventListener("resize", () => { - return this.windowResized(); - }); + window.addEventListener("resize", (function(_this) { + return function() { + return _this.windowResized(); + }; + })(this)); this.terminal = new Terminal(this); - window.addEventListener("message", (msg) => { - var iframe; - iframe = document.getElementById("runiframe"); - if ((iframe != null) && msg.source === iframe.contentWindow) { - return this.messageReceived(msg.data); - } - }); + window.addEventListener("message", (function(_this) { + return function(msg) { + var iframe; + iframe = document.getElementById("runiframe"); + if ((iframe != null) && msg.source === iframe.contentWindow) { + return _this.messageReceived(msg.data); + } + }; + })(this)); this.command_table = {}; this.command_id = 0; this.floating_window = new FloatingWindow(this.app, "run-window", this); @@ -66,23 +96,31 @@ this.RunWindow = class RunWindow { this.server_bar = new ServerBar(this.app); } - initWarnings() { - document.getElementById("console-options-warning-undefined").addEventListener("change", () => { - this.warning_undefined = document.getElementById("console-options-warning-undefined").checked; - return localStorage.setItem("console_warning_undefined", this.warning_undefined); - }); - document.getElementById("console-options-warning-nonfunction").addEventListener("change", () => { - this.warning_nonfunction = document.getElementById("console-options-warning-nonfunction").checked; - return localStorage.setItem("console_warning_nonfunction", this.warning_nonfunction); - }); - document.getElementById("console-options-warning-assign").addEventListener("change", () => { - this.warning_assign = document.getElementById("console-options-warning-assign").checked; - return localStorage.setItem("console_warning_assign", this.warning_assign); - }); - document.getElementById("console-options-warning-condition").addEventListener("change", () => { - this.warning_condition = document.getElementById("console-options-warning-condition").checked; - return localStorage.setItem("console_warning_condition", this.warning_condition); - }); + RunWindow.prototype.initWarnings = function() { + document.getElementById("console-options-warning-undefined").addEventListener("change", (function(_this) { + return function() { + _this.warning_undefined = document.getElementById("console-options-warning-undefined").checked; + return localStorage.setItem("console_warning_undefined", _this.warning_undefined); + }; + })(this)); + document.getElementById("console-options-warning-nonfunction").addEventListener("change", (function(_this) { + return function() { + _this.warning_nonfunction = document.getElementById("console-options-warning-nonfunction").checked; + return localStorage.setItem("console_warning_nonfunction", _this.warning_nonfunction); + }; + })(this)); + document.getElementById("console-options-warning-assign").addEventListener("change", (function(_this) { + return function() { + _this.warning_assign = document.getElementById("console-options-warning-assign").checked; + return localStorage.setItem("console_warning_assign", _this.warning_assign); + }; + })(this)); + document.getElementById("console-options-warning-condition").addEventListener("change", (function(_this) { + return function() { + _this.warning_condition = document.getElementById("console-options-warning-condition").checked; + return localStorage.setItem("console_warning_condition", _this.warning_condition); + }; + })(this)); this.warning_undefined = localStorage.getItem("console_warning_undefined") === "true" || false; this.warning_nonfunction = localStorage.getItem("console_warning_nonfunction") !== "false"; this.warning_assign = localStorage.getItem("console_warning_assign") !== "false"; @@ -91,9 +129,9 @@ this.RunWindow = class RunWindow { document.getElementById("console-options-warning-nonfunction").checked = this.warning_nonfunction; document.getElementById("console-options-warning-assign").checked = this.warning_assign; return document.getElementById("console-options-warning-condition").checked = this.warning_condition; - } + }; - detach() { + RunWindow.prototype.detach = function() { var b, device, wincontent; if (this.app.project.networking) { return new FloatingRunWindow(this.app); @@ -117,13 +155,13 @@ this.RunWindow = class RunWindow { return document.getElementById("runtime").style.display = "none"; } } - } + }; - floatingWindowResized() { + RunWindow.prototype.floatingWindowResized = function() { return this.windowResized(); - } + }; - floatingWindowClosed() { + RunWindow.prototype.floatingWindowClosed = function() { var container, device; if (!this.detached) { return; @@ -140,24 +178,25 @@ this.RunWindow = class RunWindow { document.getElementById("runtime").style.display = "block"; return this.windowResized(); } - } + }; - run() { + RunWindow.prototype.run = function() { var code, device, origin, src, url; src = this.app.editor.editor.getValue(); device = document.getElementById("device"); - code = this.app.project.public ? "" : `${this.app.project.code}/`; - url = `${location.origin.replace(".dev", ".io")}/${this.app.project.owner.nick}/${this.app.project.slug}/${code}`; - origin = `${location.origin.replace(".dev", ".io")}`; - return this.app.project.savePendingChanges(() => { - device.innerHTML = ``; - //document.getElementById("runiframe").focus() - this.windowResized(); - return document.getElementById("take-picture-button").style.display = "inline-block"; - }); - } + code = this.app.project["public"] ? "" : this.app.project.code + "/"; + url = (location.origin.replace(".dev", ".io")) + "/" + this.app.project.owner.nick + "/" + this.app.project.slug + "/" + code; + origin = "" + (location.origin.replace(".dev", ".io")); + return this.app.project.savePendingChanges((function(_this) { + return function() { + device.innerHTML = ""; + _this.windowResized(); + return document.getElementById("take-picture-button").style.display = "inline-block"; + }; + })(this)); + }; - reload() { + RunWindow.prototype.reload = function() { this.terminal.clear(); this.run(); document.getElementById("run-button").classList.add("selected"); @@ -169,9 +208,9 @@ this.RunWindow = class RunWindow { document.getElementById("step-forward-button").style.display = "none"; document.getElementById("step-forward-button-win").style.display = "none"; return this.propagate("reload"); - } + }; - play() { + RunWindow.prototype.play = function() { if (document.getElementById("runiframe") != null) { return this.resume(); } else { @@ -186,9 +225,9 @@ this.RunWindow = class RunWindow { document.getElementById("step-forward-button-win").style.display = "none"; return this.propagate("play"); } - } + }; - pause() { + RunWindow.prototype.pause = function() { var e; e = document.getElementById("runiframe"); if (e != null) { @@ -205,19 +244,19 @@ this.RunWindow = class RunWindow { document.getElementById("step-forward-button").style.display = "inline-block"; document.getElementById("step-forward-button-win").style.display = "inline-block"; return this.propagate("pause"); - } + }; - isPaused() { + RunWindow.prototype.isPaused = function() { return document.getElementById("pause-button").classList.contains("selected") || document.getElementById("pause-button-win").classList.contains("selected"); - } + }; - stepForward() { + RunWindow.prototype.stepForward = function() { return this.postMessage({ name: "step_forward" }); - } + }; - resume() { + RunWindow.prototype.resume = function() { var e; e = document.getElementById("runiframe"); if (e != null) { @@ -235,9 +274,9 @@ this.RunWindow = class RunWindow { document.getElementById("step-forward-button").style.display = "none"; document.getElementById("step-forward-button-win").style.display = "none"; return this.propagate("resume"); - } + }; - resetButtons() { + RunWindow.prototype.resetButtons = function() { document.getElementById("run-button").classList.remove("selected"); document.getElementById("pause-button").classList.add("selected"); document.getElementById("reload-button").classList.add("selected"); @@ -246,13 +285,13 @@ this.RunWindow = class RunWindow { document.getElementById("reload-button-win").classList.add("selected"); document.getElementById("step-forward-button").style.display = "none"; return document.getElementById("step-forward-button-win").style.display = "none"; - } + }; - clear() { + RunWindow.prototype.clear = function() { return this.terminal.clear(); - } + }; - toggleConsoleOptions() { + RunWindow.prototype.toggleConsoleOptions = function() { var div; div = document.getElementById("console-options"); if (div.getBoundingClientRect().height <= 41) { @@ -262,31 +301,35 @@ this.RunWindow = class RunWindow { div.style.height = "0px"; document.getElementById("terminal-view").style.top = "40px"; } - return setTimeout((() => { - return this.app.appui.runtime_splitbar.update(); - }), 600); - } + return setTimeout(((function(_this) { + return function() { + return _this.app.appui.runtime_splitbar.update(); + }; + })(this)), 600); + }; - updateCode(file, src) { + RunWindow.prototype.updateCode = function(file, src) { var iframe; if (this.error_check != null) { clearTimeout(this.error_check); } this.error_buffer = []; - this.error_check = setTimeout((() => { - var err, i, len, ref, results; - this.error_check = null; - if (this.terminal.error_lines > 0) { - this.terminal.clear(); - } - ref = this.error_buffer; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - err = ref[i]; - results.push(this.logError(err)); - } - return results; - }), 3000); + this.error_check = setTimeout(((function(_this) { + return function() { + var err, i, len, ref, results; + _this.error_check = null; + if (_this.terminal.error_lines > 0) { + _this.terminal.clear(); + } + ref = _this.error_buffer; + results = []; + for (i = 0, len = ref.length; i < len; i++) { + err = ref[i]; + results.push(_this.logError(err)); + } + return results; + }; + })(this)), 3000); src = this.app.editor.editor.getValue(); iframe = document.getElementById("runiframe"); if (iframe != null) { @@ -296,9 +339,9 @@ this.RunWindow = class RunWindow { code: src }), "*"); } - } + }; - updateSprite(name) { + RunWindow.prototype.updateSprite = function(name) { var data, iframe, properties, sprite; iframe = document.getElementById("runiframe"); if (iframe != null) { @@ -317,9 +360,9 @@ this.RunWindow = class RunWindow { }), "*"); } } - } + }; - updateMap(name) { + RunWindow.prototype.updateMap = function(name) { var data, iframe, map; iframe = document.getElementById("runiframe"); if (iframe != null) { @@ -333,9 +376,9 @@ this.RunWindow = class RunWindow { }), "*"); } } - } + }; - windowResized() { + RunWindow.prototype.windowResized = function() { var c, ch, cw, h, r, ratio, w; r = document.getElementById("device"); c = document.getElementById("device").firstChild; @@ -350,8 +393,6 @@ this.RunWindow = class RunWindow { "2x1": 2 / 1, "1x1": 1 / 1 }[this.app.project.aspect]; - //if not ratio? and @app.project.orientation in ["portrait","landscape"] - // ratio = 16/9 if (ratio != null) { switch (this.app.project.orientation) { case "portrait": @@ -380,14 +421,14 @@ this.RunWindow = class RunWindow { h = ch; } if (c != null) { - c.style["margin-top"] = "0px"; //{}Math.round((ch-h)/2)+"px" + c.style["margin-top"] = "0px"; c.style.width = Math.round(cw) + "px"; c.style.height = Math.round(ch) + "px"; } return this.rulercanvas.resize(Math.round(w), Math.round(h), Math.round((ch - h) / 2)); - } + }; - logError(err) { + RunWindow.prototype.logError = function(err) { var error, text; if (this.error_check != null) { this.error_buffer.push(err); @@ -439,13 +480,12 @@ this.RunWindow = class RunWindow { return this.terminal.error(error); } } else { - return this.terminal.error(`${error}`); + return this.terminal.error("" + error); } - } + }; - annotateWarning(warning, info) { + RunWindow.prototype.annotateWarning = function(warning, info) { var source; - // if @app.editor.selected_source == info.file source = this.app.project.getSource(info.file); if (source != null) { if (source.annotations == null) { @@ -459,9 +499,9 @@ this.RunWindow = class RunWindow { }); return this.app.project.notifyListeners("annotations"); } - } + }; - messageReceived(msg) { + RunWindow.prototype.messageReceived = function(msg) { var c, e, err, iframe, source; try { msg = JSON.parse(msg); @@ -489,7 +529,6 @@ this.RunWindow = class RunWindow { source = this.app.project.getSource(msg.file); if (source != null) { if ((source.annotations != null) && source.annotations.length > 0) { - // @terminal.clear() source.annotations = []; return this.app.project.notifyListeners("annotations"); } @@ -549,9 +588,9 @@ this.RunWindow = class RunWindow { } catch (error1) { err = error1; } - } + }; - runCommand(command, output_callback) { + RunWindow.prototype.runCommand = function(command, output_callback) { var iframe, parser; this.nesting = 0; if (command.trim().length === 0) { @@ -595,9 +634,9 @@ this.RunWindow = class RunWindow { }; return this.play(); } - } + }; - projectOpened() { + RunWindow.prototype.projectOpened = function() { var iframe; iframe = document.getElementById("runiframe"); if (iframe != null) { @@ -607,9 +646,9 @@ this.RunWindow = class RunWindow { this.updateServerBar(); this.app.appui.server_splitbar.update(); return this.app.appui.debug_splitbar.update(); - } + }; - updateServerBar() { + RunWindow.prototype.updateServerBar = function() { if ((this.app.project != null) && this.app.project.networking) { document.getElementById("runtime").classList.add("server-open"); document.querySelector("#detach-button i").classList.remove("fa-window-restore"); @@ -620,9 +659,9 @@ this.RunWindow = class RunWindow { document.querySelector("#detach-button i").classList.remove("fa-table"); } return this.server_bar.update(this.app.project); - } + }; - projectClosed() { + RunWindow.prototype.projectClosed = function() { var i, iframe, len, list, w; this.floating_window.close(); iframe = document.getElementById("runiframe"); @@ -641,16 +680,16 @@ this.RunWindow = class RunWindow { } document.querySelector("#runtime-server-view").innerHTML = ""; this.app.appui.server_splitbar.closed1 = true; - } + }; - hideQRCode() { + RunWindow.prototype.hideQRCode = function() { if (this.qrcode != null) { document.body.removeChild(this.qrcode); return this.qrcode = null; } - } + }; - showQRCode() { + RunWindow.prototype.showQRCode = function() { var qrcode, url; if (this.app.project != null) { if (this.qrcode != null) { @@ -659,37 +698,39 @@ this.RunWindow = class RunWindow { url = location.origin.replace(".dev", ".io") + "/"; url += this.app.project.owner.nick + "/"; url += this.app.project.slug + "/"; - if (!this.app.project.public) { + if (!this.app.project["public"]) { url += this.app.project.code + "/"; } return qrcode = QRCode.toDataURL(url, { margin: 2, scale: 8 - }, (err, url) => { - var img; - if ((err == null) && (url != null)) { - img = new Image; - img.src = url; - return img.onload = () => { - var b; - b = document.getElementById("qrcode-button").getBoundingClientRect(); - img.style.position = "absolute"; - img.style.top = `${b.y + b.height + 20}px`; - img.style.left = `${Math.min(b.x + b.width / 2 - 132, window.innerWidth - img.width - 10)}px`; - img.style["z-index"] = 20; - this.qrcode = img; - this.qrcode.addEventListener("click", () => { - return this.showQRCode(); - }); - return document.body.appendChild(this.qrcode); - }; - } - }); + }, (function(_this) { + return function(err, url) { + var img; + if ((err == null) && (url != null)) { + img = new Image; + img.src = url; + return img.onload = function() { + var b; + b = document.getElementById("qrcode-button").getBoundingClientRect(); + img.style.position = "absolute"; + img.style.top = (b.y + b.height + 20) + "px"; + img.style.left = (Math.min(b.x + b.width / 2 - 132, window.innerWidth - img.width - 10)) + "px"; + img.style["z-index"] = 20; + _this.qrcode = img; + _this.qrcode.addEventListener("click", function() { + return _this.showQRCode(); + }); + return document.body.appendChild(_this.qrcode); + }; + } + }; + })(this)); } } - } + }; - takePicture() { + RunWindow.prototype.takePicture = function() { var iframe; iframe = document.getElementById("runiframe"); if (iframe != null) { @@ -697,24 +738,24 @@ this.RunWindow = class RunWindow { name: "take_picture" }), "*"); } - } + }; - hidePicture() { + RunWindow.prototype.hidePicture = function() { if (this.picture != null) { document.body.removeChild(this.picture); return this.picture = null; } - } + }; - showPicture(data) { + RunWindow.prototype.showPicture = function(data) { var b, button, div, img, save_button, set_button; this.hidePicture(); this.picture = div = document.createElement("div"); div.classList.add("show-picture"); div.style.position = "absolute"; b = document.getElementById("take-picture-button").getBoundingClientRect(); - div.style.top = `${b.y + b.height + 20}px`; - div.style.left = `${Math.min(b.x + b.width / 2 - 180, window.innerWidth - 360 - 10)}px`; + div.style.top = (b.y + b.height + 20) + "px"; + div.style.left = (Math.min(b.x + b.width / 2 - 180, window.innerWidth - 360 - 10)) + "px"; document.body.appendChild(div); img = new Image; img.src = data; @@ -724,88 +765,96 @@ this.RunWindow = class RunWindow { save_button = document.createElement("div"); save_button.innerText = this.app.translator.get("Save"); save_button.classList.add("save"); - save_button.addEventListener("click", () => { - return this.savePicture(data, save_button); - }); + save_button.addEventListener("click", (function(_this) { + return function() { + return _this.savePicture(data, save_button); + }; + })(this)); div.appendChild(save_button); div.appendChild(document.createElement("br")); set_button = document.createElement("div"); set_button.innerText = this.app.translator.get("Set as project poster image"); - set_button.addEventListener("click", () => { - return this.setAsPoster(data, set_button); - }); + set_button.addEventListener("click", (function(_this) { + return function() { + return _this.setAsPoster(data, set_button); + }; + })(this)); div.appendChild(set_button); div.appendChild(document.createElement("br")); button = document.createElement("div"); button.innerText = this.app.translator.get("Close"); button.classList.add("close"); - button.addEventListener("click", () => { - return this.hidePicture(); - }); + button.addEventListener("click", (function(_this) { + return function() { + return _this.hidePicture(); + }; + })(this)); return div.appendChild(button); - } + }; - savePicture(data, button) { + RunWindow.prototype.savePicture = function(data, button) { var link; link = document.createElement("a"); link.setAttribute("href", data); - link.setAttribute("download", `${this.app.project.slug}.png`); + link.setAttribute("download", this.app.project.slug + ".png"); link.click(); return button.style.display = "none"; - } + }; - setAsPoster(data, button) { + RunWindow.prototype.setAsPoster = function(data, button) { var img; button.style.display = "none"; img = new Image; img.src = data; - return img.onload = () => { - var canvas, h, ih, iw, poster, r, w; - canvas = document.createElement("canvas"); - iw = img.width; - ih = img.height; - if (iw < ih) { - h = Math.min(360, ih); - r = h / ih * 1.2; - canvas.width = w = h / 9 * 16; - canvas.height = h; - canvas.getContext("2d").fillStyle = "#000"; - canvas.getContext("2d").fillRect(0, 0, canvas.width, canvas.height); - canvas.getContext("2d").drawImage(img, w / 2 - r * img.width / 2, h / 2 - r * img.height / 2, img.width * r, img.height * r); - } else { - w = Math.min(640, iw, ih / 9 * 16); - h = w / 16 * 9; - r = Math.max(w / img.width, h / img.height); - canvas.width = w; - canvas.height = h; - canvas.getContext("2d").drawImage(img, w / 2 - r * img.width / 2, h / 2 - r * img.height / 2, img.width * r, img.height * r); - } - data = canvas.toDataURL().split(",")[1]; - poster = this.app.project.getSprite("poster"); - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: "sprites/poster.png", - properties: { - frames: 1, - fps: 5 - }, - content: data - }, (msg) => { - this.app.project.updateSpriteList(); - if (poster != null) { - return poster.reload(); + return img.onload = (function(_this) { + return function() { + var canvas, h, ih, iw, poster, r, w; + canvas = document.createElement("canvas"); + iw = img.width; + ih = img.height; + if (iw < ih) { + h = Math.min(360, ih); + r = h / ih * 1.2; + canvas.width = w = h / 9 * 16; + canvas.height = h; + canvas.getContext("2d").fillStyle = "#000"; + canvas.getContext("2d").fillRect(0, 0, canvas.width, canvas.height); + canvas.getContext("2d").drawImage(img, w / 2 - r * img.width / 2, h / 2 - r * img.height / 2, img.width * r, img.height * r); + } else { + w = Math.min(640, iw, ih / 9 * 16); + h = w / 16 * 9; + r = Math.max(w / img.width, h / img.height); + canvas.width = w; + canvas.height = h; + canvas.getContext("2d").drawImage(img, w / 2 - r * img.width / 2, h / 2 - r * img.height / 2, img.width * r, img.height * r); } - }); - }; - } + data = canvas.toDataURL().split(",")[1]; + poster = _this.app.project.getSprite("poster"); + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "sprites/poster.png", + properties: { + frames: 1, + fps: 5 + }, + content: data + }, function(msg) { + _this.app.project.updateSpriteList(); + if (poster != null) { + return poster.reload(); + } + }); + }; + })(this); + }; - hideAll() { + RunWindow.prototype.hideAll = function() { this.hideQRCode(); return this.hidePicture(); - } + }; - exit() { + RunWindow.prototype.exit = function() { this.projectClosed(); document.getElementById("run-button").classList.remove("selected"); document.getElementById("pause-button").classList.remove("selected"); @@ -814,25 +863,25 @@ this.RunWindow = class RunWindow { document.getElementById("pause-button-win").classList.remove("selected"); document.getElementById("reload-button-win").classList.remove("selected"); return this.propagate("exit"); - } + }; - postMessage(data) { + RunWindow.prototype.postMessage = function(data) { var iframe; iframe = document.getElementById("runiframe"); if (iframe != null) { return iframe.contentWindow.postMessage(JSON.stringify(data), "*"); } - } + }; - addMessageListener(name, callback) { + RunWindow.prototype.addMessageListener = function(name, callback) { return this.message_listeners[name] = callback; - } + }; - addListener(callback) { + RunWindow.prototype.addListener = function(callback) { return this.listeners.push(callback); - } + }; - propagate(event) { + RunWindow.prototype.propagate = function(event) { var i, l, len, ref, results; ref = this.listeners; results = []; @@ -841,25 +890,33 @@ this.RunWindow = class RunWindow { results.push(l(event)); } return results; - } + }; -}; + return RunWindow; -this.ServerBar = class ServerBar { - constructor(app) { +})(); + +this.ServerBar = (function() { + function ServerBar(app) { this.app = app; - document.getElementById("start-server-button").addEventListener("click", () => { - return this.startServer(true); - }); - document.getElementById("start-server-tab-button").addEventListener("click", () => { - return this.startServer(false); - }); - document.getElementById("stop-server-button").addEventListener("click", () => { - return this.stopServer(); - }); + document.getElementById("start-server-button").addEventListener("click", (function(_this) { + return function() { + return _this.startServer(true); + }; + })(this)); + document.getElementById("start-server-tab-button").addEventListener("click", (function(_this) { + return function() { + return _this.startServer(false); + }; + })(this)); + document.getElementById("stop-server-button").addEventListener("click", (function(_this) { + return function() { + return _this.stopServer(); + }; + })(this)); } - update(project) { + ServerBar.prototype.update = function(project) { this.project = project; if ((this.project != null) && this.project.networking) { if (this.watcher != null) { @@ -871,9 +928,9 @@ this.ServerBar = class ServerBar { delete this.watcher; } return this.forced_stop = false; - } + }; - setStatus(status, message) { + ServerBar.prototype.setStatus = function(status, message) { if (status === "running" && !this.forced_stop) { document.querySelector("#serverbar .status").classList.add("running"); document.getElementById("start-server-button").style.display = "none"; @@ -886,16 +943,16 @@ this.ServerBar = class ServerBar { document.getElementById("stop-server-button").style.display = "none"; } return document.querySelector("#serverbar .status-info").innerText = message; - } + }; - startServer(embedded) { + ServerBar.prototype.startServer = function(embedded) { var iframe, parent, url; this.forced_stop = false; if (this.app.project != null) { url = dev_domain + "/"; url += this.app.project.owner.nick + "/"; url += this.app.project.slug + "/"; - if (!this.app.project.public) { + if (!this.app.project["public"]) { url += this.app.project.code + "/"; } url += "?server"; @@ -904,16 +961,16 @@ this.ServerBar = class ServerBar { } else { parent = document.getElementById("runtime-server-view"); parent.style.overflow = "hidden"; - iframe = ``; + iframe = ""; parent.innerHTML = iframe; this.app.appui.server_splitbar.closed1 = false; this.app.appui.server_splitbar.update(); return this.app.appui.debug_splitbar.update(); } } - } + }; - stopServer() { + ServerBar.prototype.stopServer = function() { document.getElementById("runtime-server-view").innerHTML = ""; this.app.appui.server_splitbar.closed1 = true; this.app.appui.server_splitbar.update(); @@ -923,22 +980,26 @@ this.ServerBar = class ServerBar { this.server_tab = null; } return this.forced_stop = true; - } + }; -}; + return ServerBar; -this.ServerWatcher = class ServerWatcher { - constructor(app, server_bar) { +})(); + +this.ServerWatcher = (function() { + function ServerWatcher(app, server_bar) { this.app = app; this.server_bar = server_bar; this.project = this.app.project; this.watch(); - this.interval = setInterval((() => { - return this.watch(); - }), 1000); + this.interval = setInterval(((function(_this) { + return function() { + return _this.watch(); + }; + })(this)), 1000); } - watch() { + ServerWatcher.prototype.watch = function() { var err; if ((this.socket != null) && this.socket.readyState <= 1) { if (this.socket.readyState === 1) { @@ -953,50 +1014,54 @@ this.ServerWatcher = class ServerWatcher { } delete this.socket; } - return this.getRelay((address) => { - return this.connect(address); - }); + return this.getRelay((function(_this) { + return function(address) { + return _this.connect(address); + }; + })(this)); } - } + }; - sendCheck() { + ServerWatcher.prototype.sendCheck = function() { var err; try { return this.socket.send(JSON.stringify({ name: "mp_server_status", - server_id: `${this.project.owner.nick}/${this.project.slug}` + server_id: this.project.owner.nick + "/" + this.project.slug })); } catch (error1) { err = error1; return console.error(err); } - } + }; - getRelay(callback) { + ServerWatcher.prototype.getRelay = function(callback) { if (this.relay != null) { return callback(this.relay); } return this.app.client.sendRequest({ name: "get_relay_server" - }, (msg) => { - var address; - if (msg.name === "error") { - return this.server_bar.setStatus("error", msg.error); - } else { - address = msg.address; - if (address === "self") { - address = location.origin.replace("http", "ws"); + }, (function(_this) { + return function(msg) { + var address; + if (msg.name === "error") { + return _this.server_bar.setStatus("error", msg.error); + } else { + address = msg.address; + if (address === "self") { + address = location.origin.replace("http", "ws"); + } + return callback(_this.relay = address); } - return callback(this.relay = address); - } - }); - } + }; + })(this)); + }; - stop() { + ServerWatcher.prototype.stop = function() { return clearInterval(this.interval); - } + }; - connect(address) { + ServerWatcher.prototype.connect = function(address) { var err; try { this.socket = new WebSocket(address); @@ -1004,39 +1069,47 @@ this.ServerWatcher = class ServerWatcher { err = error1; this.server_bar.setStatus("error", this.app.translator.get("Relay service unreachable")); } - this.socket.onerror = () => { - return this.server_bar.setStatus("error", this.app.translator.get("Relay service unreachable")); - }; - this.socket.onmessage = (msg) => { - console.info("received: " + msg.data); - try { - msg = JSON.parse(msg.data); - if (msg.name === "mp_server_status") { - if (msg.running) { - return this.server_bar.setStatus("running", this.app.translator.get("Running")); - } else { - return this.server_bar.setStatus("stopped", this.app.translator.get("Server is not running")); + this.socket.onerror = (function(_this) { + return function() { + return _this.server_bar.setStatus("error", _this.app.translator.get("Relay service unreachable")); + }; + })(this); + this.socket.onmessage = (function(_this) { + return function(msg) { + console.info("received: " + msg.data); + try { + msg = JSON.parse(msg.data); + if (msg.name === "mp_server_status") { + if (msg.running) { + return _this.server_bar.setStatus("running", _this.app.translator.get("Running")); + } else { + return _this.server_bar.setStatus("stopped", _this.app.translator.get("Server is not running")); + } } + } catch (error1) { + err = error1; + return console.error(err); } - } catch (error1) { - err = error1; - return console.error(err); - } - }; - return this.socket.onopen = () => { - return this.sendCheck(); - }; - } + }; + })(this); + return this.socket.onopen = (function(_this) { + return function() { + return _this.sendCheck(); + }; + })(this); + }; -}; + return ServerWatcher; -this.FloatingRunWindow = class FloatingRunWindow { - constructor(app) { +})(); + +this.FloatingRunWindow = (function() { + function FloatingRunWindow(app) { var bounds, code, div, height, id, left, origin, parent, top, url, width; this.app = app; - code = this.app.project.public ? "" : `${this.app.project.code}/`; - url = `${location.origin.replace(".dev", ".io")}/${this.app.project.owner.nick}/${this.app.project.slug}/${code}`; - origin = `${location.origin.replace(".dev", ".io")}`; + code = this.app.project["public"] ? "" : this.app.project.code + "/"; + url = (location.origin.replace(".dev", ".io")) + "/" + this.app.project.owner.nick + "/" + this.app.project.slug + "/" + code; + origin = "" + (location.origin.replace(".dev", ".io")); bounds = document.querySelector("#device").getBoundingClientRect(); if (FloatingRunWindow.offset == null) { FloatingRunWindow.offset = 0; @@ -1053,23 +1126,29 @@ this.FloatingRunWindow = class FloatingRunWindow { } FloatingRunWindow.offset = (FloatingRunWindow.offset + 40) % 200; div = document.createElement("div"); - div.style = `top: ${top}px; left: ${left}px; width: ${width}px; height: ${height}px; display: block; z-index: 11;`; + div.style = "top: " + top + "px; left: " + left + "px; width: " + width + "px; height: " + height + "px; display: block; z-index: 11;"; div.classList.add("floating-window"); div.classList.add("fw-run"); div.style.position = "absolute"; div.id = id = "fw-run-" + FloatingRunWindow.id++; - div.innerHTML = `
\n \n
\n
\n
Client ${FloatingRunWindow.id - 1}
\n \n
\n`; + div.innerHTML = "
\n \n
\n
\n
Client " + (FloatingRunWindow.id - 1) + "
\n \n
\n
"; parent = document.querySelector("#runtime .devicecontainer"); parent.appendChild(div); - div.querySelector(".titlebar").addEventListener("mouseup", () => { - console.info("focusing window"); - return div.querySelector("iframe").contentWindow.focus(); - }); + div.querySelector(".titlebar").addEventListener("mouseup", (function(_this) { + return function() { + console.info("focusing window"); + return div.querySelector("iframe").contentWindow.focus(); + }; + })(this)); new FloatingWindow(this.app, id, { - floatingWindowClosed: () => { - return parent.removeChild(div); - } + floatingWindowClosed: (function(_this) { + return function() { + return parent.removeChild(div); + }; + })(this) }); } -}; + return FloatingRunWindow; + +})(); diff --git a/static/js/explore/explore.js b/static/js/explore/explore.js index 6a880c54..267bfe77 100644 --- a/static/js/explore/explore.js +++ b/static/js/explore/explore.js @@ -1,11 +1,13 @@ -this.Explore = class Explore { - constructor(app) { +this.Explore = (function() { + function Explore(app) { var likes; this.app = app; - this.get("explore-back-button").addEventListener("click", () => { - this.closeDetails(); - return this.app.appui.setMainSection("explore", true); - }); + this.get("explore-back-button").addEventListener("click", (function(_this) { + return function() { + _this.closeDetails(); + return _this.app.appui.setMainSection("explore", true); + }; + })(this)); this.sort = "hot"; this.active_tags = []; this.search = ""; @@ -21,114 +23,128 @@ this.Explore = class Explore { top: function(a, b) { return b.likes - a.likes; }, - new: function(a, b) { + "new": function(a, b) { return b.date_published - a.date_published; } }; - document.getElementById("explore-sort-button").addEventListener("click", () => { - var e, j, len, ref, s; - s = this.sort_types.indexOf(this.sort); - s = (s + 1) % this.sort_types.length; - this.sort = this.sort_types[s]; - e = document.getElementById("explore-sort-button"); - ref = this.sort_types; - for (j = 0, len = ref.length; j < len; j++) { - s = ref[j]; - if (s === this.sort) { - e.classList.add(s); - } else { - e.classList.remove(s); + document.getElementById("explore-sort-button").addEventListener("click", (function(_this) { + return function() { + var e, j, len, ref, s; + s = _this.sort_types.indexOf(_this.sort); + s = (s + 1) % _this.sort_types.length; + _this.sort = _this.sort_types[s]; + e = document.getElementById("explore-sort-button"); + ref = _this.sort_types; + for (j = 0, len = ref.length; j < len; j++) { + s = ref[j]; + if (s === _this.sort) { + e.classList.add(s); + } else { + e.classList.remove(s); + } } - } - document.querySelector("#explore-sort-button span").innerText = this.app.translator.get(this.sort.substring(0, 1).toUpperCase() + this.sort.substring(1)); - return this.query(); - }); - document.getElementById("explore-type-button").addEventListener("click", () => { - var s; - s = this.project_types.indexOf(this.project_type); - s = (s + 1) % this.project_types.length; - this.setProjectType(this.project_types[s]); - return this.query(); - }); - document.getElementById("explore-search-input").addEventListener("input", () => { - this.search = document.getElementById("explore-search-input").value; - if (this.search_timeout != null) { - clearTimeout(this.search_timeout); - } - return this.search_timeout = setTimeout((() => { - return this.query(); - }), 1500); - }); - document.getElementById("explore-contents").addEventListener("scroll", () => { - var contents, h1, h2, pos, scrollzone; - contents = document.getElementById("explore-box-list"); - scrollzone = document.getElementById("explore-contents"); - h1 = contents.getBoundingClientRect().height; - h2 = scrollzone.getBoundingClientRect().height; - if (scrollzone.scrollTop > h1 - h2 - 100) { //contents.getBoundingClientRect().height < scrollzone.scrollTop+window.innerHeight*2 - if (!this.completed) { - pos = this.projects.length; - if (pos !== this.query_position) { - this.query(pos); + document.querySelector("#explore-sort-button span").innerText = _this.app.translator.get(_this.sort.substring(0, 1).toUpperCase() + _this.sort.substring(1)); + return _this.query(); + }; + })(this)); + document.getElementById("explore-type-button").addEventListener("click", (function(_this) { + return function() { + var s; + s = _this.project_types.indexOf(_this.project_type); + s = (s + 1) % _this.project_types.length; + _this.setProjectType(_this.project_types[s]); + return _this.query(); + }; + })(this)); + document.getElementById("explore-search-input").addEventListener("input", (function(_this) { + return function() { + _this.search = document.getElementById("explore-search-input").value; + if (_this.search_timeout != null) { + clearTimeout(_this.search_timeout); + } + return _this.search_timeout = setTimeout((function() { + return _this.query(); + }), 1500); + }; + })(this)); + document.getElementById("explore-contents").addEventListener("scroll", (function(_this) { + return function() { + var contents, h1, h2, pos, scrollzone; + contents = document.getElementById("explore-box-list"); + scrollzone = document.getElementById("explore-contents"); + h1 = contents.getBoundingClientRect().height; + h2 = scrollzone.getBoundingClientRect().height; + if (scrollzone.scrollTop > h1 - h2 - 100) { + if (!_this.completed) { + pos = _this.projects.length; + if (pos !== _this.query_position) { + _this.query(pos); + } } } - } - }); + }; + })(this)); this.cloned = {}; - this.get("project-details-clonebutton").addEventListener("click", () => { - if (this.app.user == null) { - return alert(this.app.translator.get("Log in or create your account to clone this project.")); - } - this.get("project-details-clonebutton").style.display = "none"; - this.cloned[this.project.id] = true; - return this.app.client.sendRequest({ - name: "clone_public_project", - project: this.project.id - }, (msg) => { - this.app.appui.setMainSection("projects"); - this.app.appui.backToProjectList(); - this.app.updateProjectList(msg.id); - return this.app.appui.showNotification(this.app.translator.get("Project cloned! Here is your copy.")); - }); - }); + this.get("project-details-clonebutton").addEventListener("click", (function(_this) { + return function() { + if (_this.app.user == null) { + return alert(_this.app.translator.get("Log in or create your account to clone this project.")); + } + _this.get("project-details-clonebutton").style.display = "none"; + _this.cloned[_this.project.id] = true; + return _this.app.client.sendRequest({ + name: "clone_public_project", + project: _this.project.id + }, function(msg) { + _this.app.appui.setMainSection("projects"); + _this.app.appui.backToProjectList(); + _this.app.updateProjectList(msg.id); + return _this.app.appui.showNotification(_this.app.translator.get("Project cloned! Here is your copy.")); + }); + }; + })(this)); likes = this.get("project-details-likes"); - likes.addEventListener("click", () => { - if (!this.app.user.flags.validated) { - return alert(this.app.translator.get("Validate your e-mail address to enable votes.")); - } - if (this.project != null) { - return this.app.client.sendRequest({ - name: "toggle_like", - project: this.project.id - }, (msg) => { - if (msg.name === "project_likes") { - likes.innerHTML = " " + msg.likes; - if (msg.liked) { - return likes.classList.add("voted"); - } else { - return likes.classList.remove("voted"); + likes.addEventListener("click", (function(_this) { + return function() { + if (!_this.app.user.flags.validated) { + return alert(_this.app.translator.get("Validate your e-mail address to enable votes.")); + } + if (_this.project != null) { + return _this.app.client.sendRequest({ + name: "toggle_like", + project: _this.project.id + }, function(msg) { + if (msg.name === "project_likes") { + likes.innerHTML = " " + msg.likes; + if (msg.liked) { + return likes.classList.add("voted"); + } else { + return likes.classList.remove("voted"); + } } - } - }); - } - }); - document.querySelector("#explore-tags-bar i").addEventListener("click", () => { - var bar, icon; - bar = document.querySelector("#explore-tags-bar"); - icon = bar.querySelector("i"); - if (bar.classList.contains("collapsed")) { - bar.classList.remove("collapsed"); - icon.classList.remove("fa-caret-right"); - return icon.classList.add("fa-caret-down"); - } else { - bar.classList.add("collapsed"); - icon.classList.add("fa-caret-right"); - return icon.classList.remove("fa-caret-down"); - } - }); + }); + } + }; + })(this)); + document.querySelector("#explore-tags-bar i").addEventListener("click", (function(_this) { + return function() { + var bar, icon; + bar = document.querySelector("#explore-tags-bar"); + icon = bar.querySelector("i"); + if (bar.classList.contains("collapsed")) { + bar.classList.remove("collapsed"); + icon.classList.remove("fa-caret-right"); + return icon.classList.add("fa-caret-down"); + } else { + bar.classList.add("collapsed"); + icon.classList.add("fa-caret-right"); + return icon.classList.remove("fa-caret-down"); + } + }; + })(this)); } - setProjectType(project_type) { + Explore.prototype.setProjectType = function(project_type) { var e, j, len, ref, s; this.project_type = project_type; e = document.getElementById("explore-type-button"); @@ -142,20 +158,19 @@ this.Explore = class Explore { } } return document.querySelector("#explore-type-button span").innerText = this.app.translator.get(this.project_type.substring(0, 1).toUpperCase() + this.project_type.substring(1)); - } + }; - closeDetails() { + Explore.prototype.closeDetails = function() { return this.closeProject(); - } + }; - //@app.setHomeState() - closed() { + Explore.prototype.closed = function() { if (!document.title.startsWith("microStudio")) { return document.title = "microStudio"; } - } + }; - findBestTag(p) { + Explore.prototype.findBestTag = function(p) { var index, j, len, ref, score, t, tag; tag = p.tags[0]; score = this.tags.indexOf(tag); @@ -172,9 +187,9 @@ this.Explore = class Explore { } } return tag; - } + }; - createProjectBox(p) { + Explore.prototype.createProjectBox = function(p) { var author, awaiting, element, icon, infobox, label, likes, runbutton, smallicon, tag, title; element = document.createElement("div"); element.classList.add("explore-project-box"); @@ -186,14 +201,13 @@ this.Explore = class Explore { } if (p.poster) { icon = new Image; - icon.src = location.origin + `/${p.owner}/${p.slug}/poster.png`; + icon.src = location.origin + ("/" + p.owner + "/" + p.slug + "/poster.png"); icon.classList.add("poster"); - //icon.classList.add "pixelated" icon.alt = p.title; icon.title = p.title; element.appendChild(icon); smallicon = new Image; - smallicon.src = location.origin + `/${p.owner}/${p.slug}/icon.png`; + smallicon.src = location.origin + ("/" + p.owner + "/" + p.slug + "/icon.png"); smallicon.classList.add("smallicon"); smallicon.classList.add("pixelated"); smallicon.alt = p.title; @@ -202,9 +216,9 @@ this.Explore = class Explore { } else { icon = new Image; if (p.icon || p.type !== "example") { - icon.src = location.origin + `/${p.owner}/${p.slug}/icon.png`; + icon.src = location.origin + ("/" + p.owner + "/" + p.slug + "/icon.png"); } else { - icon.src = `${dev_domain}/img/lightbulb16.png`; + icon.src = dev_domain + "/img/lightbulb16.png"; } icon.classList.add("icon"); icon.classList.add("pixelated"); @@ -215,9 +229,11 @@ this.Explore = class Explore { element.style.opacity = 0; element.style["transition-duration"] = "1s"; element.style["transition-property"] = "opacity"; - icon.onload = () => { - return element.style.opacity = 1; - }; + icon.onload = (function(_this) { + return function() { + return element.style.opacity = 1; + }; + })(this); infobox = document.createElement("div"); infobox.classList.add("explore-infobox"); element.appendChild(infobox); @@ -238,47 +254,49 @@ this.Explore = class Explore { runbutton.classList.add("run-button"); runbutton.innerHTML = " " + this.app.translator.get("Run"); element.appendChild(runbutton); - likes.addEventListener("click", (event) => { - event.stopImmediatePropagation(); - if (!this.app.user.flags.validated) { - return alert(this.app.translator.get("Validate your e-mail address to enable votes.")); - } - return this.app.client.sendRequest({ - name: "toggle_like", - project: p.id - }, (msg) => { - if (msg.name === "project_likes") { - likes.innerHTML = " " + msg.likes; - p.likes = msg.likes; - if (msg.liked) { - likes.classList.add("voted"); - return p.liked = true; - } else { - p.liked = false; - return likes.classList.remove("voted"); - } + likes.addEventListener("click", (function(_this) { + return function(event) { + event.stopImmediatePropagation(); + if (!_this.app.user.flags.validated) { + return alert(_this.app.translator.get("Validate your e-mail address to enable votes.")); } - }); - }); + return _this.app.client.sendRequest({ + name: "toggle_like", + project: p.id + }, function(msg) { + if (msg.name === "project_likes") { + likes.innerHTML = " " + msg.likes; + p.likes = msg.likes; + if (msg.liked) { + likes.classList.add("voted"); + return p.liked = true; + } else { + p.liked = false; + return likes.classList.remove("voted"); + } + } + }); + }; + })(this)); if (p.type !== "app") { label = document.createElement("div"); label.classList.add("type-label"); label.classList.add(p.type); switch (p.type) { case "library": - label.innerHTML = ` ${this.app.translator.get("Library")}`; + label.innerHTML = " " + (this.app.translator.get("Library")); break; case "plugin": - label.innerHTML = ` ${this.app.translator.get("Plug-in")}`; + label.innerHTML = " " + (this.app.translator.get("Plug-in")); break; case "tutorial": - label.innerHTML = ` ${this.app.translator.get("Tutorial")}`; + label.innerHTML = " " + (this.app.translator.get("Tutorial")); break; case "example": - label.innerHTML = ` ${this.app.translator.get("Example")}`; + label.innerHTML = " " + (this.app.translator.get("Example")); break; case "template": - label.innerHTML = ` ${this.app.translator.get("Template")}`; + label.innerHTML = " " + (this.app.translator.get("Template")); } element.appendChild(label); } @@ -288,35 +306,39 @@ this.Explore = class Explore { awaiting.innerHTML = "Awaiting approval"; element.appendChild(awaiting); } - runbutton.addEventListener("click", (event) => { - event.stopPropagation(); - if (p.type === "tutorial") { - return window.open(location.origin.replace(".dev", ".io") + `/tutorial/${p.owner}/${p.slug}/`, "_blank"); - } else { - return window.open(location.origin.replace(".dev", ".io") + `/${p.owner}/${p.slug}/`, "_blank"); - } - }); - element.addEventListener("click", () => { - if (screen.width <= 700) { - return window.open(location.origin.replace(".dev", ".io") + `/${p.owner}/${p.slug}/`, "_blank"); - } else { - this.app.app_state.pushState("project_details", `/i/${p.owner}/${p.slug}/`, { - project: p - }); - this.openProject(p); - return this.canBack = true; - } - }); + runbutton.addEventListener("click", (function(_this) { + return function(event) { + event.stopPropagation(); + if (p.type === "tutorial") { + return window.open(location.origin.replace(".dev", ".io") + ("/tutorial/" + p.owner + "/" + p.slug + "/"), "_blank"); + } else { + return window.open(location.origin.replace(".dev", ".io") + ("/" + p.owner + "/" + p.slug + "/"), "_blank"); + } + }; + })(this)); + element.addEventListener("click", (function(_this) { + return function() { + if (screen.width <= 700) { + return window.open(location.origin.replace(".dev", ".io") + ("/" + p.owner + "/" + p.slug + "/"), "_blank"); + } else { + _this.app.app_state.pushState("project_details", "/i/" + p.owner + "/" + p.slug + "/", { + project: p + }); + _this.openProject(p); + return _this.canBack = true; + } + }; + })(this)); return element; - } + }; - get(id) { + Explore.prototype.get = function(id) { return document.getElementById(id); - } + }; - findProject(owner, slug) { + Explore.prototype.findProject = function(owner, slug) { var id, j, len, p, ref; - id = `${owner}.${slug}`; + id = owner + "." + slug; if (this.visited_projects[id] != null) { return this.visited_projects[id]; } @@ -330,11 +352,11 @@ this.Explore = class Explore { } } return null; - } + }; - openProject(p) { + Explore.prototype.openProject = function(p) { var desc, div, j, k, len, len1, lib, likes, list, ref, ref1, t; - this.visited_projects[`${p.owner}.${p.slug}`] = p; + this.visited_projects[p.owner + "." + p.slug] = p; this.project = p; if (this.cloned[this.project.id]) { this.get("project-details-clonebutton").style.display = "none"; @@ -347,28 +369,28 @@ this.Explore = class Explore { this.get("explore-tags-bar").style.display = "none"; this.get("explore-contents").style.display = "none"; this.get("explore-project-details").style.display = "block"; - this.get("project-details-image").src = p.icon || p.type !== "example" ? location.origin + `/${p.owner}/${p.slug}/icon.png` : `${dev_domain}/img/lightbulb16.png`; + this.get("project-details-image").src = p.icon || p.type !== "example" ? location.origin + ("/" + p.owner + "/" + p.slug + "/icon.png") : dev_domain + "/img/lightbulb16.png"; this.get("project-details-title").innerText = p.title; desc = DOMPurify.sanitize(marked(p.description)); if (p.poster) { - this.get("project-details-info").style.background = `linear-gradient(to bottom, hsla(200,10%,10%,0.8), hsla(200,10%,10%,0.9)),url(/${p.owner}/${p.slug}/poster.png)`; + this.get("project-details-info").style.background = "linear-gradient(to bottom, hsla(200,10%,10%,0.8), hsla(200,10%,10%,0.9)),url(/" + p.owner + "/" + p.slug + "/poster.png)"; this.get("project-details-info").style["background-size"] = "100%"; this.get("project-details-info").style["background-repeat"] = "no-repeat"; } else { this.get("project-details-info").style.background = "none"; } - desc += `

${this.app.translator.get("First published on %DATE%").replace("%DATE%", new Date(p.date_published).toLocaleDateString())}

`; - desc += `

${this.app.translator.get("Last modified on %DATE%").replace("%DATE%", new Date(p.last_modified).toLocaleDateString())}

`; + desc += "

" + (this.app.translator.get("First published on %DATE%").replace("%DATE%", new Date(p.date_published).toLocaleDateString())) + "

"; + desc += "

" + (this.app.translator.get("Last modified on %DATE%").replace("%DATE%", new Date(p.last_modified).toLocaleDateString())) + "

"; ref = p.libs; for (j = 0, len = ref.length; j < len; j++) { lib = ref[j]; - desc = `

${this.app.translator.get("This project uses this optional library:")} ${lib}

` + desc; + desc = ("

" + (this.app.translator.get("This project uses this optional library:")) + " " + lib + "

") + desc; } if (p.graphics !== "M1") { - desc = `

${this.app.translator.get("This project uses this graphics API:")} ${p.graphics}

` + desc; + desc = ("

" + (this.app.translator.get("This project uses this graphics API:")) + " " + p.graphics + "

") + desc; } if (p.language != null) { - desc = `
${(p.language.split("_")[0])}

` + desc; + desc = ("
" + (p.language.split("_")[0]) + "

") + desc; } this.get("project-details-description").innerHTML = desc; document.querySelector("#project-details-author").innerHTML = ""; @@ -381,11 +403,11 @@ this.Explore = class Explore { likes.classList.remove("voted"); } if (p.type === "tutorial") { - this.get("project-details-runbutton").href = location.origin.replace(".dev", ".io") + `/tutorial/${p.owner}/${p.slug}/`; + this.get("project-details-runbutton").href = location.origin.replace(".dev", ".io") + ("/tutorial/" + p.owner + "/" + p.slug + "/"); } else if (p.type === "example") { - this.get("project-details-runbutton").href = `${dev_domain}/tutorials/examples/${p.owner}/${p.slug}/`; + this.get("project-details-runbutton").href = dev_domain + "/tutorials/examples/" + p.owner + "/" + p.slug + "/"; } else { - this.get("project-details-runbutton").href = location.origin.replace(".dev", ".io") + `/${p.owner}/${p.slug}/`; + this.get("project-details-runbutton").href = location.origin.replace(".dev", ".io") + ("/" + p.owner + "/" + p.slug + "/"); } list = this.get("project-details-tags"); list.innerHTML = ""; @@ -397,124 +419,138 @@ this.Explore = class Explore { div.innerText = t; list.appendChild(div); if ((this.app.user != null) && this.app.user.flags.admin) { - ((t) => { - return div.addEventListener("click", () => { - var index; - if (confirm("really delete tag?")) { - index = p.tags.indexOf(t); - if (index >= 0) { - p.tags.splice(index, 1); - return this.app.client.sendRequest({ - name: "set_project_tags", - project: p.id, - tags: p.tags - }, (msg) => { - return this.openProject(p); - }); + (function(_this) { + return (function(t) { + return div.addEventListener("click", function() { + var index; + if (confirm("really delete tag?")) { + index = p.tags.indexOf(t); + if (index >= 0) { + p.tags.splice(index, 1); + return _this.app.client.sendRequest({ + name: "set_project_tags", + project: p.id, + tags: p.tags + }, function(msg) { + return _this.openProject(p); + }); + } } - } + }); }); - })(t); + })(this)(t); } } if ((this.app.user != null) && (this.app.user.flags.admin || this.app.user.flags.moderator) && window.ms_project_moderation) { if (p.owner_info.approved) { document.getElementById("project-details-description").appendChild(this.createModerationParagraph("User approved, project visible to everyone")); - document.getElementById("project-details-description").appendChild(this.createModerationButton("Remove user approval", () => { - if (confirm("Really remove user approval?")) { - return this.app.client.sendRequest({ - name: "set_user_approved", - user: p.owner, - approved: false - }, (msg) => { - return location.reload(); - }); - } - })); + document.getElementById("project-details-description").appendChild(this.createModerationButton("Remove user approval", (function(_this) { + return function() { + if (confirm("Really remove user approval?")) { + return _this.app.client.sendRequest({ + name: "set_user_approved", + user: p.owner, + approved: false + }, function(msg) { + return location.reload(); + }); + } + }; + })(this))); } else if (p.flags.approved) { document.getElementById("project-details-description").appendChild(this.createModerationParagraph("Project is approved and visible to everyone")); - document.getElementById("project-details-description").appendChild(this.createModerationButton("Remove project approval", () => { - if (confirm("Really remove project approval?")) { - return this.app.client.sendRequest({ - name: "set_project_approved", - project: p.id, - approved: false - }, (msg) => { - return location.reload(); - }); - } - })); + document.getElementById("project-details-description").appendChild(this.createModerationButton("Remove project approval", (function(_this) { + return function() { + if (confirm("Really remove project approval?")) { + return _this.app.client.sendRequest({ + name: "set_project_approved", + project: p.id, + approved: false + }, function(msg) { + return location.reload(); + }); + } + }; + })(this))); } else { document.getElementById("project-details-description").appendChild(this.createModerationParagraph("Project is visible only to moderators, awaiting approval")); - document.getElementById("project-details-description").appendChild(this.createModerationButton("Approve project", () => { - if (confirm("Really approve project?")) { - return this.app.client.sendRequest({ - name: "set_project_approved", - project: p.id, - approved: true - }, (msg) => { - return location.reload(); - }); - } - })); - document.getElementById("project-details-description").appendChild(this.createModerationButton("Approve user", () => { - if (confirm("Really approve user?")) { - return this.app.client.sendRequest({ - name: "set_user_approved", - user: p.owner, - approved: true - }, (msg) => { - return location.reload(); - }); - } - })); + document.getElementById("project-details-description").appendChild(this.createModerationButton("Approve project", (function(_this) { + return function() { + if (confirm("Really approve project?")) { + return _this.app.client.sendRequest({ + name: "set_project_approved", + project: p.id, + approved: true + }, function(msg) { + return location.reload(); + }); + } + }; + })(this))); + document.getElementById("project-details-description").appendChild(this.createModerationButton("Approve user", (function(_this) { + return function() { + if (confirm("Really approve user?")) { + return _this.app.client.sendRequest({ + name: "set_user_approved", + user: p.owner, + approved: true + }, function(msg) { + return location.reload(); + }); + } + }; + })(this))); } div = document.createElement("div"); div.classList.add("tag"); div.innerText = "+ add"; div.style = "background: hsl(0,50%,50%)"; list.appendChild(div); - div.addEventListener("click", () => { - var value; - value = prompt("add tag"); - if ((value != null) && value.length > 1) { - p.tags.push(value); - return this.app.client.sendRequest({ - name: "set_project_tags", - project: p.id, - tags: p.tags - }, (msg) => { - return this.openProject(p); - }); - } - }); + div.addEventListener("click", (function(_this) { + return function() { + var value; + value = prompt("add tag"); + if ((value != null) && value.length > 1) { + p.tags.push(value); + return _this.app.client.sendRequest({ + name: "set_project_tags", + project: p.id, + tags: p.tags + }, function(msg) { + return _this.openProject(p); + }); + } + }; + })(this)); } if (this.details == null) { this.details = new ProjectDetails(this.app); } return this.details.set(p); - } + }; - createModerationParagraph(text) { + Explore.prototype.createModerationParagraph = function(text) { var p; p = document.createElement("p"); p.style = "padding: 25px 0px 5px 0"; p.innerHTML = text; return p; - } + }; - createModerationButton(text, callback) { + Explore.prototype.createModerationButton = function(text, callback) { var div; div = document.createElement("div"); div.style = "padding: 5px 10px ; margin-left: 10px ; background:hsl(20,50%,50%) ; cursor: pointer; display: inline-block; border-radius: 5px"; div.innerHTML = text; - div.addEventListener("click", () => { - return callback(); - }); + div.addEventListener("click", (function(_this) { + return function() { + return callback(); + }; + })(this)); return div; - } + }; - closeProject(p) { + Explore.prototype.closeProject = function(p) { this.get("explore-back-button").style.display = "none"; this.get("explore-tools").style.display = "inline-block"; this.get("explore-tags-bar").style.display = "block"; @@ -522,13 +558,29 @@ this.Explore = class Explore { this.get("explore-project-details").style.display = "none"; this.project = null; return this.closed(); - } + }; - createTags(tags) { - var div, j, len, ref, t; + Explore.prototype.createTags = function(tags) { + var div, fn, j, len, ref, t; this.tags = tags; document.getElementById("explore-tags").innerHTML = ""; ref = this.tags; + fn = (function(_this) { + return function(t, div) { + return div.addEventListener("click", function() { + var index; + index = _this.active_tags.indexOf(t); + if (index >= 0) { + _this.active_tags.splice(index, 1); + div.classList.remove("active"); + } else { + _this.active_tags.push(t); + div.classList.add("active"); + } + return _this.query(); + }); + }; + })(this); for (j = 0, len = ref.length; j < len; j++) { t = ref[j]; div = document.createElement("div"); @@ -536,29 +588,16 @@ this.Explore = class Explore { if (this.active_tags.includes(t)) { div.classList.add("active"); } - //span = document.createElement "span" - //span.innerText = t.count - //div.appendChild span document.getElementById("explore-tags").appendChild(div); - ((t, div) => { - return div.addEventListener("click", () => { - var index; - index = this.active_tags.indexOf(t); - if (index >= 0) { - this.active_tags.splice(index, 1); - div.classList.remove("active"); - } else { - this.active_tags.push(t); - div.classList.add("active"); - } - return this.query(); - }); - })(t, div); + fn(t, div); } - } + }; - loadProjects(pos = 0) { + Explore.prototype.loadProjects = function(pos) { var contents, i, j, mod, p, ref, ref1, scrollzone; + if (pos == null) { + pos = 0; + } if (this.projects == null) { return; } @@ -574,9 +613,9 @@ this.Explore = class Explore { contents.appendChild(this.createProjectBox(p)); } } - } + }; - update() { + Explore.prototype.update = function() { var owner, project; if (!this.initialized && location.pathname.startsWith("/i/")) { document.getElementById("explore-section").style.opacity = 0; @@ -589,27 +628,34 @@ this.Explore = class Explore { name: "get_public_project", owner: owner, project: project - }, (msg) => { - project = msg.project; - if (project != null) { - this.openProject(project); - document.getElementById("explore-section").style.opacity = 1; - } - }); + }, (function(_this) { + return function(msg) { + project = msg.project; + if (project != null) { + _this.openProject(project); + document.getElementById("explore-section").style.opacity = 1; + } + }; + })(this)); } else { if ((this.projects == null) || this.projects.length === 0) { return this.query(); } } - } + }; - query(position = 0) { + Explore.prototype.query = function(position) { var f; + if (position == null) { + position = 0; + } this.query_position = position; if (position === 0 || (this.current_offset == null)) { this.current_offset = 0; } - f = () => {}; + f = (function(_this) { + return function() {}; + })(this); this.app.client.sendRequest({ name: "get_public_projects", ranking: this.sort, @@ -618,33 +664,35 @@ this.Explore = class Explore { search: this.search.toLowerCase(), position: position, offset: this.current_offset - }, (msg) => { - var pos; - if (position === 0) { - this.current_position = position; - this.current_offset = msg.offset; - this.completed = false; - this.projects = msg.list; - this.createTags(msg.tags); - this.loadProjects(); - document.getElementById("explore-contents").scrollTop = 0; - } else { - if (msg.list.length === 0) { - this.completed = true; + }, (function(_this) { + return function(msg) { + var pos; + if (position === 0) { + _this.current_position = position; + _this.current_offset = msg.offset; + _this.completed = false; + _this.projects = msg.list; + _this.createTags(msg.tags); + _this.loadProjects(); + document.getElementById("explore-contents").scrollTop = 0; + } else { + if (msg.list.length === 0) { + _this.completed = true; + } + _this.current_position = position; + _this.current_offset = msg.offset; + pos = _this.projects.length; + _this.projects = _this.projects.concat(msg.list); + _this.loadProjects(pos); } - this.current_position = position; - this.current_offset = msg.offset; - pos = this.projects.length; - this.projects = this.projects.concat(msg.list); - this.loadProjects(pos); - } - if (!this.initialized) { - this.initialized = true; - return document.getElementById("explore-section").style.opacity = 1; - } - }); - } + if (!_this.initialized) { + _this.initialized = true; + return document.getElementById("explore-section").style.opacity = 1; + } + }; + })(this)); + }; -}; + return Explore; -//@app.setHomeState() +})(); diff --git a/static/js/explore/projectdetails.js b/static/js/explore/projectdetails.js index 6266b3df..52f1cd07 100644 --- a/static/js/explore/projectdetails.js +++ b/static/js/explore/projectdetails.js @@ -1,16 +1,19 @@ -this.ProjectDetails = class ProjectDetails { - constructor(app) { - var j, len, ref, s; +this.ProjectDetails = (function() { + function ProjectDetails(app) { + var fn, j, len, ref, s; this.app = app; this.menu = ["code", "sprites", "sounds", "music", "assets", "doc"]; ref = this.menu; + fn = (function(_this) { + return function(s) { + return document.getElementById("project-contents-menu-" + s).addEventListener("click", function() { + return _this.setSection(s); + }); + }; + })(this); for (j = 0, len = ref.length; j < len; j++) { s = ref[j]; - ((s) => { - return document.getElementById(`project-contents-menu-${s}`).addEventListener("click", () => { - return this.setSection(s); - }); - })(s); + fn(s); } this.splitbar = new SplitBar("explore-project-details", "horizontal"); this.splitbar.setPosition(45); @@ -22,120 +25,132 @@ this.ProjectDetails = class ProjectDetails { this.editor.getSession().setOptions({ tabSize: 2, useSoftTabs: true, - useWorker: false // disables lua autocorrection ; preserves syntax coloring - }); - document.querySelector("#project-contents-source-import").addEventListener("click", () => { - var count, file, name; - if (this.app.project == null) { - return; - } - file = this.selected_source; - if (file == null) { - return; - } - if (this.imported_sources[file]) { - return; - } - this.imported_sources[file] = true; - name = file.split(".")[0]; - count = 1; - while (this.app.project.getSource(name) != null) { - count += 1; - name = file.split(".")[0] + count; - } - file = name + ".ms"; - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: `ms/${file}`, - content: this.sources[this.selected_source] - }, (msg) => { - this.app.project.updateSourceList(); - return this.setSelectedSource(this.selected_source); - }); - }); - document.getElementById("project-contents-sprite-import").addEventListener("click", () => { - var base, count, data, name; - if (this.app.project == null) { - return; - } - if (this.selected_sprite == null) { - return; - } - name = this.selected_sprite.name; - if (name == null) { - return; - } - if (this.imported_sprites[name]) { - return; - } - this.imported_sprites[name] = true; - document.getElementById("project-contents-sprite-import").style.display = "none"; - count = 1; - base = name; - while (this.app.project.getSprite(name) != null) { - count += 1; - name = base + count; - } - data = this.selected_sprite.saveData().split(",")[1]; - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: `sprites/${name}.png`, - properties: { - frames: this.selected_sprite.frames.length, - fps: this.selected_sprite.fps - }, - content: data - }, (msg) => { - return this.app.project.updateSpriteList(); - }); - }); - document.querySelector("#project-contents-doc-import").addEventListener("click", () => { - var value; - if (this.app.project == null) { - return; - } - if (this.imported_doc || (this.doc == null)) { - return; - } - this.imported_doc = true; - value = this.app.doc_editor.editor.getValue(); - if ((value != null) && value.length > 0) { - value = value + "\n\n" + this.doc; - } else { - value = this.doc; - } - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: "doc/doc.md", - content: value - }, (msg) => { - this.app.project.loadDoc(); - document.querySelector("#project-contents-doc-import").classList.add("done"); - document.querySelector("#project-contents-doc-import i").classList.add("fa-check"); - document.querySelector("#project-contents-doc-import i").classList.remove("fa-download"); - return document.querySelector("#project-contents-doc-import span").innerText = this.app.translator.get("Doc imported"); - }); - }); - document.getElementById("post-project-comment-button").addEventListener("click", () => { - var text; - text = document.querySelector("#post-project-comment textarea").value; - if ((text != null) && text.length > 0) { - this.postComment(text); - return document.querySelector("#post-project-comment textarea").value = ""; - } - }); - document.getElementById("login-to-post-comment").addEventListener("click", () => { - return this.app.appui.showLoginPanel(); - }); - document.getElementById("validate-to-post-comment").addEventListener("click", () => { - return this.app.appui.setMainSection("usersettings"); + useWorker: false }); + document.querySelector("#project-contents-source-import").addEventListener("click", (function(_this) { + return function() { + var count, file, name; + if (_this.app.project == null) { + return; + } + file = _this.selected_source; + if (file == null) { + return; + } + if (_this.imported_sources[file]) { + return; + } + _this.imported_sources[file] = true; + name = file.split(".")[0]; + count = 1; + while (_this.app.project.getSource(name) != null) { + count += 1; + name = file.split(".")[0] + count; + } + file = name + ".ms"; + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "ms/" + file, + content: _this.sources[_this.selected_source] + }, function(msg) { + _this.app.project.updateSourceList(); + return _this.setSelectedSource(_this.selected_source); + }); + }; + })(this)); + document.getElementById("project-contents-sprite-import").addEventListener("click", (function(_this) { + return function() { + var base, count, data, name; + if (_this.app.project == null) { + return; + } + if (_this.selected_sprite == null) { + return; + } + name = _this.selected_sprite.name; + if (name == null) { + return; + } + if (_this.imported_sprites[name]) { + return; + } + _this.imported_sprites[name] = true; + document.getElementById("project-contents-sprite-import").style.display = "none"; + count = 1; + base = name; + while (_this.app.project.getSprite(name) != null) { + count += 1; + name = base + count; + } + data = _this.selected_sprite.saveData().split(",")[1]; + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "sprites/" + name + ".png", + properties: { + frames: _this.selected_sprite.frames.length, + fps: _this.selected_sprite.fps + }, + content: data + }, function(msg) { + return _this.app.project.updateSpriteList(); + }); + }; + })(this)); + document.querySelector("#project-contents-doc-import").addEventListener("click", (function(_this) { + return function() { + var value; + if (_this.app.project == null) { + return; + } + if (_this.imported_doc || (_this.doc == null)) { + return; + } + _this.imported_doc = true; + value = _this.app.doc_editor.editor.getValue(); + if ((value != null) && value.length > 0) { + value = value + "\n\n" + _this.doc; + } else { + value = _this.doc; + } + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "doc/doc.md", + content: value + }, function(msg) { + _this.app.project.loadDoc(); + document.querySelector("#project-contents-doc-import").classList.add("done"); + document.querySelector("#project-contents-doc-import i").classList.add("fa-check"); + document.querySelector("#project-contents-doc-import i").classList.remove("fa-download"); + return document.querySelector("#project-contents-doc-import span").innerText = _this.app.translator.get("Doc imported"); + }); + }; + })(this)); + document.getElementById("post-project-comment-button").addEventListener("click", (function(_this) { + return function() { + var text; + text = document.querySelector("#post-project-comment textarea").value; + if ((text != null) && text.length > 0) { + _this.postComment(text); + return document.querySelector("#post-project-comment textarea").value = ""; + } + }; + })(this)); + document.getElementById("login-to-post-comment").addEventListener("click", (function(_this) { + return function() { + return _this.app.appui.showLoginPanel(); + }; + })(this)); + document.getElementById("validate-to-post-comment").addEventListener("click", (function(_this) { + return function() { + return _this.app.appui.setMainSection("usersettings"); + }; + })(this)); } - set(project1) { + ProjectDetails.prototype.set = function(project1) { var a, j, len, ref, ref1, section, t; this.project = project1; this.splitbar.update(); @@ -158,7 +173,6 @@ this.ProjectDetails = class ProjectDetails { document.querySelector("#project-contents-view .sound-list").innerHTML = ""; document.querySelector("#project-contents-view .music-list").innerHTML = ""; document.querySelector("#project-contents-view .asset-list").innerHTML = ""; - //document.querySelector("#project-contents-view .maps").innerHTML = "" document.querySelector("#project-contents-view .doc-render").innerHTML = ""; section = "code"; ref = this.project.tags; @@ -180,61 +194,67 @@ this.ProjectDetails = class ProjectDetails { name: "list_public_project_files", project: this.project.id, folder: "ms" - }, (msg) => { - return this.setSourceList(msg.files); - }); + }, (function(_this) { + return function(msg) { + return _this.setSourceList(msg.files); + }; + })(this)); this.app.client.sendRequest({ name: "list_public_project_files", project: this.project.id, folder: "sprites" - }, (msg) => { - return this.setSpriteList(msg.files); - }); + }, (function(_this) { + return function(msg) { + return _this.setSpriteList(msg.files); + }; + })(this)); this.app.client.sendRequest({ name: "list_public_project_files", project: this.project.id, folder: "sounds" - }, (msg) => { - return this.setSoundList(msg.files); - }); + }, (function(_this) { + return function(msg) { + return _this.setSoundList(msg.files); + }; + })(this)); this.app.client.sendRequest({ name: "list_public_project_files", project: this.project.id, folder: "music" - }, (msg) => { - return this.setMusicList(msg.files); - }); + }, (function(_this) { + return function(msg) { + return _this.setMusicList(msg.files); + }; + })(this)); this.app.client.sendRequest({ name: "list_public_project_files", project: this.project.id, folder: "assets" - }, (msg) => { - return this.setAssetList(msg.files); - }); - //@app.client.sendRequest { - // name: "list_public_project_files" - // project: @project.id - // folder: "maps" - //},(msg)=> - // @setMapList msg.files + }, (function(_this) { + return function(msg) { + return _this.setAssetList(msg.files); + }; + })(this)); this.app.client.sendRequest({ name: "list_public_project_files", project: this.project.id, folder: "doc" - }, (msg) => { - return this.setDocList(msg.files); - }); + }, (function(_this) { + return function(msg) { + return _this.setDocList(msg.files); + }; + })(this)); this.updateComments(); this.updateCredentials(); a = document.querySelector("#project-contents-view .sprites .export-panel a"); - a.href = `/${this.project.owner}/${this.project.slug}/export/sprites/`; - a.download = `${this.project.slug}_sprites.zip`; + a.href = "/" + this.project.owner + "/" + this.project.slug + "/export/sprites/"; + a.download = this.project.slug + "_sprites.zip"; a = document.querySelector("#project-details-exportbutton"); - a.href = `/${this.project.owner}/${this.project.slug}/export/project/`; - return a.download = `${this.project.slug}_files.zip`; - } + a.href = "/" + this.project.owner + "/" + this.project.slug + "/export/project/"; + return a.download = this.project.slug + "_files.zip"; + }; - updateCredentials() { + ProjectDetails.prototype.updateCredentials = function() { if (this.app.user != null) { document.getElementById("login-to-post-comment").style.display = "none"; if (this.app.user.flags.validated) { @@ -249,59 +269,63 @@ this.ProjectDetails = class ProjectDetails { document.getElementById("validate-to-post-comment").style.display = "none"; return document.getElementById("post-project-comment").style.display = "none"; } - } + }; - loadFile(url, callback) { + ProjectDetails.prototype.loadFile = function(url, callback) { var req; req = new XMLHttpRequest(); - req.onreadystatechange = (event) => { - if (req.readyState === XMLHttpRequest.DONE) { - if (req.status === 200) { - return callback(req.responseText); + req.onreadystatechange = (function(_this) { + return function(event) { + if (req.readyState === XMLHttpRequest.DONE) { + if (req.status === 200) { + return callback(req.responseText); + } } - } - }; + }; + })(this); req.open("GET", url); return req.send(); - } + }; - setSection(section) { + ProjectDetails.prototype.setSection = function(section) { var j, len, ref, s; ref = this.menu; for (j = 0, len = ref.length; j < len; j++) { s = ref[j]; if (s === section) { - document.getElementById(`project-contents-menu-${s}`).classList.add("selected"); - document.querySelector(`#project-contents-view .${s}`).style.display = "block"; + document.getElementById("project-contents-menu-" + s).classList.add("selected"); + document.querySelector("#project-contents-view ." + s).style.display = "block"; } else { - document.getElementById(`project-contents-menu-${s}`).classList.remove("selected"); - document.querySelector(`#project-contents-view .${s}`).style.display = "none"; + document.getElementById("project-contents-menu-" + s).classList.remove("selected"); + document.querySelector("#project-contents-view ." + s).style.display = "none"; } } - } + }; - createSourceEntry(file) { + ProjectDetails.prototype.createSourceEntry = function(file) { return this.app.client.sendRequest({ name: "read_public_project_file", project: this.project.id, - file: `ms/${file}` - }, (msg) => { - var div; - this.sources[file] = msg.content; - div = document.createElement("div"); - div.innerHTML = ` ${(file.split(".")[0])}`; - document.querySelector("#project-contents-view .code-list").appendChild(div); - div.id = `project-contents-view-source-${file}`; - div.addEventListener("click", () => { - return this.setSelectedSource(file); - }); - if (this.selected_source == null) { - return this.setSelectedSource(file); - } - }); - } + file: "ms/" + file + }, (function(_this) { + return function(msg) { + var div; + _this.sources[file] = msg.content; + div = document.createElement("div"); + div.innerHTML = " " + (file.split(".")[0]); + document.querySelector("#project-contents-view .code-list").appendChild(div); + div.id = "project-contents-view-source-" + file; + div.addEventListener("click", function() { + return _this.setSelectedSource(file); + }); + if (_this.selected_source == null) { + return _this.setSelectedSource(file); + } + }; + })(this)); + }; - setSelectedSource(file) { + ProjectDetails.prototype.setSelectedSource = function(file) { var lang, source; this.selected_source = file; this.source_folder.setSelectedItem(file); @@ -332,34 +356,34 @@ this.ProjectDetails = class ProjectDetails { document.querySelector("#project-contents-source-import i").classList.remove("fa-check"); return document.querySelector("#project-contents-source-import span").innerText = this.app.translator.get("Import source file to") + " " + this.app.project.title; } - } + }; - setSourceList(files) { + ProjectDetails.prototype.setSourceList = function(files) { var f, folder, j, len, manager, project, s, table, view; - // for f in files - // @createSourceEntry(f.file) - // return table = {}; manager = { folder: "ms", item: "source", - openItem: (item) => { - return this.setSelectedSource(item); - } + openItem: (function(_this) { + return function(item) { + return _this.setSelectedSource(item); + }; + })(this) }; - // table[item].play() this.project_sources = {}; - project = JSON.parse(JSON.stringify(this.project)); // create a clone + project = JSON.parse(JSON.stringify(this.project)); project.app = this.app; - project.notifyListeners = (source) => { - this.sources[source.name] = source.content; - if (this.selected_source == null) { - return this.setSelectedSource(source.name); - } - }; + project.notifyListeners = (function(_this) { + return function(source) { + _this.sources[source.name] = source.content; + if (_this.selected_source == null) { + return _this.setSelectedSource(source.name); + } + }; + })(this); project.getFullURL = function() { var url; - return url = location.origin + `/${project.owner}/${project.slug}/`; + return url = location.origin + ("/" + project.owner + "/" + project.slug + "/"); }; folder = new ProjectFolder(null, "source"); for (j = 0, len = files.length; j < len; j++) { @@ -373,30 +397,32 @@ this.ProjectDetails = class ProjectDetails { this.source_folder = view; view.editable = false; view.rebuildList(folder); - } + }; - setSpriteList(files) { + ProjectDetails.prototype.setSpriteList = function(files) { var f, folder, j, len, manager, project, s, table; table = {}; this.sprites = {}; manager = { folder: "sprites", item: "sprite", - openItem: (item) => { - this.sprites_folder_view.setSelectedItem(item); - this.selected_sprite = this.sprites[item]; - if ((this.app.project != null) && !this.imported_sprites[item]) { - document.querySelector("#project-contents-sprite-import span").innerText = this.app.translator.get("Import %ITEM% to project %PROJECT%").replace("%ITEM%", item.replace(/-/g, "/")).replace("%PROJECT%", this.app.project.title); - return document.getElementById("project-contents-sprite-import").style.display = "block"; - } else { - return document.getElementById("project-contents-sprite-import").style.display = "none"; - } - } + openItem: (function(_this) { + return function(item) { + _this.sprites_folder_view.setSelectedItem(item); + _this.selected_sprite = _this.sprites[item]; + if ((_this.app.project != null) && !_this.imported_sprites[item]) { + document.querySelector("#project-contents-sprite-import span").innerText = _this.app.translator.get("Import %ITEM% to project %PROJECT%").replace("%ITEM%", item.replace(/-/g, "/")).replace("%PROJECT%", _this.app.project.title); + return document.getElementById("project-contents-sprite-import").style.display = "block"; + } else { + return document.getElementById("project-contents-sprite-import").style.display = "none"; + } + }; + })(this) }; - project = JSON.parse(JSON.stringify(this.project)); // create a clone + project = JSON.parse(JSON.stringify(this.project)); project.getFullURL = function() { var url; - return url = location.origin + `/${project.owner}/${project.slug}/`; + return url = location.origin + ("/" + project.owner + "/" + project.slug + "/"); }; project.map_list = []; project.notifyListeners = function() {}; @@ -412,9 +438,9 @@ this.ProjectDetails = class ProjectDetails { this.sprites_folder_view.editable = false; this.sprites_folder_view.rebuildList(folder); document.getElementById("project-contents-sprite-import").style.display = "none"; - } + }; - setSoundList(files) { + ProjectDetails.prototype.setSoundList = function(files) { var f, folder, j, len, manager, project, s, table, view; if (files.length > 0) { document.getElementById("project-contents-menu-sounds").style.display = "block"; @@ -429,10 +455,10 @@ this.ProjectDetails = class ProjectDetails { return table[item].play(); } }; - project = JSON.parse(JSON.stringify(this.project)); // create a clone + project = JSON.parse(JSON.stringify(this.project)); project.getFullURL = function() { var url; - return url = location.origin + `/${project.owner}/${project.slug}/`; + return url = location.origin + ("/" + project.owner + "/" + project.slug + "/"); }; folder = new ProjectFolder(null, "sounds"); for (j = 0, len = files.length; j < len; j++) { @@ -444,9 +470,9 @@ this.ProjectDetails = class ProjectDetails { view = new FolderView(manager, document.querySelector("#project-contents-view .sound-list")); view.editable = false; view.rebuildList(folder); - } + }; - setMusicList(files) { + ProjectDetails.prototype.setMusicList = function(files) { var f, folder, j, len, manager, project, s, table, view; if (files.length > 0) { document.getElementById("project-contents-menu-music").style.display = "block"; @@ -461,11 +487,13 @@ this.ProjectDetails = class ProjectDetails { return table[item].play(); } }; - project = JSON.parse(JSON.stringify(this.project)); // create a clone - project.getFullURL = () => { - var url; - return url = location.origin + `/${project.owner}/${project.slug}/`; - }; + project = JSON.parse(JSON.stringify(this.project)); + project.getFullURL = (function(_this) { + return function() { + var url; + return url = location.origin + ("/" + project.owner + "/" + project.slug + "/"); + }; + })(this); folder = new ProjectFolder(null, "sounds"); for (j = 0, len = files.length; j < len; j++) { f = files[j]; @@ -476,9 +504,9 @@ this.ProjectDetails = class ProjectDetails { view = new FolderView(manager, document.querySelector("#project-contents-view .music-list")); view.editable = false; view.rebuildList(folder); - } + }; - setAssetList(files) { + ProjectDetails.prototype.setAssetList = function(files) { var f, folder, j, len, manager, project, s, table, view; if (files.length > 0) { document.getElementById("project-contents-menu-assets").style.display = "block"; @@ -491,10 +519,10 @@ this.ProjectDetails = class ProjectDetails { item: "asset", openItem: function(item) {} }; - project = JSON.parse(JSON.stringify(this.project)); // create a clone + project = JSON.parse(JSON.stringify(this.project)); project.getFullURL = function() { var url; - return url = location.origin + `/${project.owner}/${project.slug}/`; + return url = location.origin + ("/" + project.owner + "/" + project.slug + "/"); }; folder = new ProjectFolder(null, "assets"); for (j = 0, len = files.length; j < len; j++) { @@ -506,52 +534,55 @@ this.ProjectDetails = class ProjectDetails { view = new FolderView(manager, document.querySelector("#project-contents-view .asset-list")); view.editable = false; view.rebuildList(folder); - } + }; - setMapList(files) { + ProjectDetails.prototype.setMapList = function(files) { return console.info(files); - } + }; - setDocList(files) { + ProjectDetails.prototype.setDocList = function(files) { if (files.length > 0) { document.getElementById("project-contents-menu-doc").style.display = "block"; return this.app.client.sendRequest({ name: "read_public_project_file", project: this.project.id, - file: `doc/${files[0].file}` - }, (msg) => { - this.doc = msg.content; - if ((this.doc != null) && this.doc.trim().length > 0) { - return document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize(marked(msg.content)); - } else { - return document.getElementById("project-contents-menu-doc").style.display = "none"; - } - }); + file: "doc/" + files[0].file + }, (function(_this) { + return function(msg) { + _this.doc = msg.content; + if ((_this.doc != null) && _this.doc.trim().length > 0) { + return document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize(marked(msg.content)); + } else { + return document.getElementById("project-contents-menu-doc").style.display = "none"; + } + }; + })(this)); } else { return document.getElementById("project-contents-menu-doc").style.display = "none"; } - } + }; - //console.info files - updateComments() { + ProjectDetails.prototype.updateComments = function() { return this.app.client.sendRequest({ name: "get_project_comments", project: this.project.id - }, (msg) => { - var c, e, j, len, ref; - e = document.getElementById("project-comment-list"); - e.innerHTML = ""; - if (msg.comments != null) { - ref = msg.comments; - for (j = 0, len = ref.length; j < len; j++) { - c = ref[j]; - this.createCommentBox(c); + }, (function(_this) { + return function(msg) { + var c, e, j, len, ref; + e = document.getElementById("project-comment-list"); + e.innerHTML = ""; + if (msg.comments != null) { + ref = msg.comments; + for (j = 0, len = ref.length; j < len; j++) { + c = ref[j]; + _this.createCommentBox(c); + } } - } - }); - } + }; + })(this)); + }; - createCommentBox(c) { + ProjectDetails.prototype.createCommentBox = function(c) { var author, buttons, clear, contents, div, i, span, t, time, tt; console.info(c); div = document.createElement("div"); @@ -598,12 +629,11 @@ this.ProjectDetails = class ProjectDetails { if ((this.app.user != null) && (this.app.user.nick === c.user || this.app.user.flags.admin)) { buttons = document.createElement("div"); buttons.classList.add("buttons"); - //buttons.appendChild @createButton "edit","Edit","green",()=> - // @editComment c - //buttons.appendChild document.createElement "br" - buttons.appendChild(this.createButton("trash", this.app.translator.get("Delete"), "red", () => { - return this.deleteComment(c); - })); + buttons.appendChild(this.createButton("trash", this.app.translator.get("Delete"), "red", (function(_this) { + return function() { + return _this.deleteComment(c); + }; + })(this))); div.appendChild(buttons); } contents = document.createElement("div"); @@ -614,61 +644,69 @@ this.ProjectDetails = class ProjectDetails { clear.style = "clear:both"; div.appendChild(clear); return document.getElementById("project-comment-list").appendChild(div); - } + }; - createButton(icon, text, color, callback) { + ProjectDetails.prototype.createButton = function(icon, text, color, callback) { var button, i, span; button = document.createElement("div"); button.classList.add("small" + color + "button"); i = document.createElement("i"); i.classList.add("fa"); - i.classList.add(`fa-${icon}`); + i.classList.add("fa-" + icon); button.appendChild(i); span = document.createElement("span"); span.innerText = text; button.appendChild(span); - button.addEventListener("click", () => { - return callback(); - }); + button.addEventListener("click", (function(_this) { + return function() { + return callback(); + }; + })(this)); return button; - } + }; - postComment(text) { + ProjectDetails.prototype.postComment = function(text) { return this.app.client.sendRequest({ name: "add_project_comment", project: this.project.id, text: text - }, (msg) => { - return this.updateComments(); - }); - } + }, (function(_this) { + return function(msg) { + return _this.updateComments(); + }; + })(this)); + }; - editComment(id, text) {} + ProjectDetails.prototype.editComment = function(id, text) {}; - deleteComment(c) { - return ConfirmDialog.confirm(this.app.translator.get("Do you really want to delete this comment?"), this.app.translator.get("Delete"), this.app.translator.get("Cancel"), () => { - return this.app.client.sendRequest({ - name: "delete_project_comment", - project: this.project.id, - id: c.id - }, (msg) => { - return this.updateComments(); - }); - }); - } + ProjectDetails.prototype.deleteComment = function(c) { + return ConfirmDialog.confirm(this.app.translator.get("Do you really want to delete this comment?"), this.app.translator.get("Delete"), this.app.translator.get("Cancel"), (function(_this) { + return function() { + return _this.app.client.sendRequest({ + name: "delete_project_comment", + project: _this.project.id, + id: c.id + }, function(msg) { + return _this.updateComments(); + }); + }; + })(this)); + }; + + return ProjectDetails; -}; +})(); -this.ExploreProjectSource = class ExploreProjectSource { - constructor(project1, file1, size = 0) { +this.ExploreProjectSource = (function() { + function ExploreProjectSource(project1, file1, size) { var s; this.project = project1; this.file = file1; - this.size = size; + this.size = size != null ? size : 0; this.name = this.file.split(".")[0]; this.ext = this.file.split(".")[1]; this.filename = this.file; - this.file = `ms/${this.file}`; + this.file = "ms/" + this.file; s = this.name.split("-"); this.shortname = s[s.length - 1]; this.path_prefix = s.length > 1 ? s.splice(0, s.length - 1).join("-") + "-" : ""; @@ -677,14 +715,18 @@ this.ExploreProjectSource = class ExploreProjectSource { this.reload(); } - reload() { - return fetch(this.project.getFullURL() + `ms/${this.name}.ms`).then((result) => { - return result.text().then((text) => { - this.content = text; - this.fetched = true; - return this.project.notifyListeners(this); - }); - }); - } + ExploreProjectSource.prototype.reload = function() { + return fetch(this.project.getFullURL() + ("ms/" + this.name + ".ms")).then((function(_this) { + return function(result) { + return result.text().then(function(text) { + _this.content = text; + _this.fetched = true; + return _this.project.notifyListeners(_this); + }); + }; + })(this)); + }; + + return ExploreProjectSource; -}; +})(); diff --git a/static/js/folderview.js b/static/js/folderview.js index c82e7c3d..5416c8ac 100644 --- a/static/js/folderview.js +++ b/static/js/folderview.js @@ -1,14 +1,14 @@ -var indexOf = [].indexOf; +var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; -this.FolderView = class FolderView { - constructor(manager, panel) { +this.FolderView = (function() { + function FolderView(manager, panel) { this.manager = manager; this.panel = panel; this.editable = true; this.app = this.manager.app; } - isDroppable(event) { + FolderView.prototype.isDroppable = function(event) { var i, j, len, ref; ref = event.dataTransfer.items; for (j = 0, len = ref.length; j < len; j++) { @@ -24,84 +24,94 @@ this.FolderView = class FolderView { } } return false; - } + }; - init() { + FolderView.prototype.init = function() { var count; - this.panel.addEventListener("mousedown", () => { - return this.setSelectedFolder(null); - }); + this.panel.addEventListener("mousedown", (function(_this) { + return function() { + return _this.setSelectedFolder(null); + }; + })(this)); if (this.editable && (this.manager.fileDropped != null)) { - this.panel.addEventListener("dragover", (event) => { - if (this.isDroppable(event)) { - return event.preventDefault(); - } - }); - this.panel.addEventListener("drop", (event) => { - var err, ext, file, i, j, len, list, ref, results, split; - event.preventDefault(); - this.panel.classList.remove("dragover"); - try { - list = []; - ref = event.dataTransfer.items; - results = []; - for (j = 0, len = ref.length; j < len; j++) { - i = ref[j]; - list.push(i.getAsFile()); - if (i.kind === "file") { - file = i.getAsFile(); - split = file.name.split("."); - ext = split[split.length - 1].toLowerCase(); - if (indexOf.call(this.manager.extensions, ext) >= 0) { - results.push(this.manager.fileDropped(file)); + this.panel.addEventListener("dragover", (function(_this) { + return function(event) { + if (_this.isDroppable(event)) { + return event.preventDefault(); + } + }; + })(this)); + this.panel.addEventListener("drop", (function(_this) { + return function(event) { + var err, ext, file, i, j, len, list, ref, results, split; + event.preventDefault(); + _this.panel.classList.remove("dragover"); + try { + list = []; + ref = event.dataTransfer.items; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + i = ref[j]; + list.push(i.getAsFile()); + if (i.kind === "file") { + file = i.getAsFile(); + split = file.name.split("."); + ext = split[split.length - 1].toLowerCase(); + if (indexOf.call(_this.manager.extensions, ext) >= 0) { + results.push(_this.manager.fileDropped(file)); + } else { + results.push(void 0); + } + } else if (i.kind === "string") { + results.push(i.getAsString(function(s) { + var data, err, name; + console.info(s); + try { + data = JSON.parse(s); + if (data.type === _this.manager.item && (_this.drag_file != null)) { + if (_this.drag_file.parent !== _this.folder) { + name = _this.manager.findNewFilename(_this.drag_file.shortname, _this.manager.get_item); + return _this.manager.renameItem(_this.drag_file, name); + } + } else if (data.type === "folder" && (_this.drag_folder != null)) { + return _this.moveFolder(_this.drag_folder, _this.folder); + } + } catch (error) { + err = error; + return console.error(err); + } + })); } else { results.push(void 0); } - } else if (i.kind === "string") { - results.push(i.getAsString((s) => { - var data, err, name; - console.info(s); - try { - data = JSON.parse(s); - if (data.type === this.manager.item && (this.drag_file != null)) { - if (this.drag_file.parent !== this.folder) { - name = this.manager.findNewFilename(this.drag_file.shortname, this.manager.get_item); - return this.manager.renameItem(this.drag_file, name); - } - } else if (data.type === "folder" && (this.drag_folder != null)) { - return this.moveFolder(this.drag_folder, this.folder); - } - } catch (error) { - err = error; - return console.error(err); - } - })); - } else { - results.push(void 0); } + return results; + } catch (error) { + err = error; + return console.error(err); } - return results; - } catch (error) { - err = error; - return console.error(err); - } - }); + }; + })(this)); count = 0; - this.panel.addEventListener("dragenter", (event) => { - count += 1; - this.panel.classList.add("dragover"); - return this.setSelectedFolder(null); - }); - return this.panel.addEventListener("dragleave", (event) => { - count -= 1; - if (count === 0) { - return this.panel.classList.remove("dragover"); - } - }); + this.panel.addEventListener("dragenter", (function(_this) { + return function(event) { + count += 1; + _this.panel.classList.add("dragover"); + return _this.setSelectedFolder(null); + }; + })(this)); + return this.panel.addEventListener("dragleave", (function(_this) { + return function(event) { + count -= 1; + if (count === 0) { + return _this.panel.classList.remove("dragover"); + } + }; + })(this)); } - } + }; - moveFolder(folder, dest) { + FolderView.prototype.moveFolder = function(folder, dest) { var f, j, len, ref; ref = dest.subfolders; for (j = 0, len = ref.length; j < len; j++) { @@ -112,9 +122,9 @@ this.FolderView = class FolderView { } dest.addFolder(folder); return this.fixFilesPath(folder); - } + }; - fixFilesPath(folder) { + FolderView.prototype.fixFilesPath = function(folder) { var f, j, k, len, len1, name, ref, ref1; ref = folder.subfolders; for (j = 0, len = ref.length; j < len; j++) { @@ -127,13 +137,13 @@ this.FolderView = class FolderView { name = folder.getFullDashPath() + "-" + f.shortname; this.manager.renameItem(f, name); } - } + }; - createItemBox(item) { + FolderView.prototype.createItemBox = function(item) { var activeuser, element, icon, text; element = document.createElement("div"); element.classList.add("asset-box"); - element.classList.add(`asset-box-${this.manager.item}`); + element.classList.add("asset-box-" + this.manager.item); item.element = element; element.dataset.id = item.name; element.setAttribute("title", item.shortname); @@ -144,44 +154,50 @@ this.FolderView = class FolderView { icon = new Image; icon.src = item.getThumbnailURL(); icon.loading = "lazy"; - icon.setAttribute("id", `asset-image-${item.name}`); + icon.setAttribute("id", "asset-image-" + item.name); element.appendChild(icon); icon.draggable = false; } else if (item.getThumbnailElement != null) { icon = item.getThumbnailElement(); - //icon.setAttribute "id","asset-image-#{item.name}" element.appendChild(icon); icon.draggable = false; } text = document.createElement("div"); text.classList.add("asset-box-name"); if (this.manager.file_icon != null) { - text.innerHTML = ` ${item.shortname}`; + text.innerHTML = " " + item.shortname; } else { text.innerHTML = item.shortname; } element.appendChild(text); - element.addEventListener("click", () => { - return this.manager.openItem(item.name); - }); + element.addEventListener("click", (function(_this) { + return function() { + return _this.manager.openItem(item.name); + }; + })(this)); activeuser = document.createElement("i"); activeuser.classList.add("active-user"); activeuser.classList.add("fa"); activeuser.classList.add("fa-user"); element.appendChild(activeuser); element.draggable = item.canBeRenamed != null ? item.canBeRenamed() : true; - element.addEventListener("dragstart", (event) => { - this.drag_file = item; - return event.dataTransfer.setData("application/json", JSON.stringify({ - type: this.manager.item, - id: item.name - })); - }); + element.addEventListener("dragstart", (function(_this) { + return function(event) { + _this.drag_file = item; + return event.dataTransfer.setData("application/json", JSON.stringify({ + type: _this.manager.item, + id: item.name + })); + }; + })(this)); return element; - } + }; - setSelectedFolder(folder, current = this.folder) { + FolderView.prototype.setSelectedFolder = function(folder, current) { var f, j, len, ref; + if (current == null) { + current = this.folder; + } this.selected_folder = folder; if (current == null) { return; @@ -198,52 +214,27 @@ this.FolderView = class FolderView { f = ref[j]; this.setSelectedFolder(folder, f); } - } + }; - createItemFolder(folder, element) { - var content, f, fdiv, j, k, len, len1, ref, ref1, title; + FolderView.prototype.createItemFolder = function(folder, element) { + var content, f, fdiv, fn, j, k, len, len1, ref, ref1, title; ref = folder.subfolders; - for (j = 0, len = ref.length; j < len; j++) { - f = ref[j]; - fdiv = document.createElement("div"); - fdiv.classList.add("folder"); - element.appendChild(fdiv); - f.setElement(fdiv); - // del = document.createElement "i" - // del.classList.add "fa" - // del.classList.add "fa-trash" - // del.classList.add "trash" - // title.appendChild del - title = document.createElement("div"); - title.classList.add("folder-title"); - title.innerHTML = ` ${f.name} `; - title.addEventListener("resize", () => { - if (title.getBoundingClientRect().width < 200) { - return title.querySelector(".trash").style.display = "none"; - } else { - return title.querySelector(".trash").style.display = "inline-block"; - } - }); - fdiv.appendChild(title); - content = document.createElement("div"); - content.classList.add("folder-content"); - fdiv.appendChild(content); - ((f, fdiv, title) => { + fn = (function(_this) { + return function(f, fdiv, title) { var count, span, toggle; - if (this.editable) { - title.querySelector(".trash").addEventListener("click", () => { - this.manager.deleteFolder(f); - return this.setSelectedFolder(null); + if (_this.editable) { + title.querySelector(".trash").addEventListener("click", function() { + _this.manager.deleteFolder(f); + return _this.setSelectedFolder(null); }); - fdiv.addEventListener("mousedown", (event) => { + fdiv.addEventListener("mousedown", function(event) { event.stopPropagation(); - this.setSelectedFolder(f); - // this ensures potential active audio preview will stop playing + _this.setSelectedFolder(f); return document.body.dispatchEvent(new MouseEvent("mousedown", {})); }); title.draggable = true; - title.addEventListener("dragstart", (event) => { - this.drag_folder = f; + title.addEventListener("dragstart", function(event) { + _this.drag_folder = f; return event.dataTransfer.setData("application/json", JSON.stringify({ type: "folder", id: f.getFullDashPath() @@ -253,40 +244,40 @@ this.FolderView = class FolderView { toggle = function() { return f.setOpen(!f.open); }; - title.addEventListener("click", (event) => { + title.addEventListener("click", function(event) { if (event.clientX < title.getBoundingClientRect().x + 50) { return toggle(); } }); - title.addEventListener("dblclick", (event) => { + title.addEventListener("dblclick", function(event) { return toggle(); }); - if (this.editable) { + if (_this.editable) { span = title.querySelector("span"); - span.addEventListener("dblclick", (event) => { + span.addEventListener("dblclick", function(event) { event.stopPropagation(); - return this.editFolderName(f); + return _this.editFolderName(f); }); - title.querySelector(".pencil").addEventListener("click", () => { - return this.editFolderName(f); + title.querySelector(".pencil").addEventListener("click", function() { + return _this.editFolderName(f); }); count = 0; - fdiv.addEventListener("dragenter", (event) => { + fdiv.addEventListener("dragenter", function(event) { event.stopPropagation(); count += 1; if (!f.element.classList.contains("selected")) { - this.setSelectedFolder(f); + _this.setSelectedFolder(f); } if (!f.open) { if (f.open_timeout == null) { - return f.open_timeout = setTimeout((() => { + return f.open_timeout = setTimeout((function() { f.setOpen(true); return delete f.open_timeout; }), 1000); } } }); - fdiv.addEventListener("dragleave", (event) => { + fdiv.addEventListener("dragleave", function(event) { event.stopPropagation(); count -= 1; if (count === 0) { @@ -296,12 +287,12 @@ this.FolderView = class FolderView { } } }); - fdiv.addEventListener("dragover", (event) => { - if (this.isDroppable(event)) { + fdiv.addEventListener("dragover", function(event) { + if (_this.isDroppable(event)) { return event.preventDefault(); } }); - return fdiv.addEventListener("drop", (event) => { + return fdiv.addEventListener("drop", function(event) { var err, ext, file, i, k, len1, list, ref1; event.preventDefault(); event.stopPropagation(); @@ -313,24 +304,24 @@ this.FolderView = class FolderView { if (i.kind === "file") { file = i.getAsFile(); ext = file.name.split(".")[1].toLowerCase(); - if (indexOf.call(this.manager.extensions, ext) >= 0) { - this.manager.fileDropped(file, f); + if (indexOf.call(_this.manager.extensions, ext) >= 0) { + _this.manager.fileDropped(file, f); } } else if (i.kind === "string") { - i.getAsString((s) => { + i.getAsString(function(s) { var data, err, fullname, name; console.info(s); try { data = JSON.parse(s); - if (data.type === this.manager.item && (this.drag_file != null)) { - if (this.drag_file.parent !== f) { - name = this.manager.findNewFilename(this.drag_file.shortname, this.manager.get_item, f); + if (data.type === _this.manager.item && (_this.drag_file != null)) { + if (_this.drag_file.parent !== f) { + name = _this.manager.findNewFilename(_this.drag_file.shortname, _this.manager.get_item, f); fullname = f.getFullDashPath() + "-" + name; - return this.manager.renameItem(this.drag_file, fullname); + return _this.manager.renameItem(_this.drag_file, fullname); } - } else if (data.type === "folder" && (this.drag_folder != null)) { - if (this.drag_folder !== f && !this.drag_folder.isAncestorOf(f)) { - return this.moveFolder(this.drag_folder, f); + } else if (data.type === "folder" && (_this.drag_folder != null)) { + if (_this.drag_folder !== f && !_this.drag_folder.isAncestorOf(f)) { + return _this.moveFolder(_this.drag_folder, f); } } } catch (error) { @@ -346,7 +337,31 @@ this.FolderView = class FolderView { } }); } - })(f, fdiv, title); + }; + })(this); + for (j = 0, len = ref.length; j < len; j++) { + f = ref[j]; + fdiv = document.createElement("div"); + fdiv.classList.add("folder"); + element.appendChild(fdiv); + f.setElement(fdiv); + title = document.createElement("div"); + title.classList.add("folder-title"); + title.innerHTML = " " + f.name + " "; + title.addEventListener("resize", (function(_this) { + return function() { + if (title.getBoundingClientRect().width < 200) { + return title.querySelector(".trash").style.display = "none"; + } else { + return title.querySelector(".trash").style.display = "inline-block"; + } + }; + })(this)); + fdiv.appendChild(title); + content = document.createElement("div"); + content.classList.add("folder-content"); + fdiv.appendChild(content); + fn(f, fdiv, title); this.createItemFolder(f, content); } ref1 = folder.files; @@ -354,15 +369,14 @@ this.FolderView = class FolderView { f = ref1[k]; element.appendChild(this.createItemBox(f)); } - } + }; - rebuildList(folder1) { + FolderView.prototype.rebuildList = function(folder1) { var scroll_top; this.folder = folder1; scroll_top = this.panel.scrollTop; this.panel.innerHTML = ""; this.createItemFolder(this.folder, this.panel); - //@updateActiveUsers() this.panel.scrollTop = scroll_top; if (this.selected_folder != null) { this.setSelectedFolder(this.selected_folder); @@ -370,9 +384,9 @@ this.FolderView = class FolderView { if (this.selected_item != null) { this.setSelectedItem(this.selected_item); } - } + }; - setSelectedItem(item) { + FolderView.prototype.setSelectedItem = function(item) { var e, j, k, len, len1, list; list = this.panel.getElementsByClassName("asset-box"); this.selected_item = item; @@ -391,9 +405,9 @@ this.FolderView = class FolderView { e.classList.remove("selected"); } } - } + }; - editFolderName(folder) { + FolderView.prototype.editFolderName = function(folder) { var f, files, input, j, k, len, len1, parent, span; parent = folder.parent; while (parent != null) { @@ -405,7 +419,7 @@ this.FolderView = class FolderView { files = folder.getAllFiles(); for (j = 0, len = files.length; j < len; j++) { f = files[j]; - if (this.app.project.isLocked(`${this.manager.folder}/${f.name}.${f.ext}`)) { + if (this.app.project.isLocked(this.manager.folder + "/" + f.name + "." + f.ext)) { return; } } @@ -415,55 +429,62 @@ this.FolderView = class FolderView { span.parentNode.replaceChild(input, span); for (k = 0, len1 = files.length; k < len1; k++) { f = files[k]; - this.app.project.lockFile(`${this.manager.folder}/${f.name}.${f.ext}`); + this.app.project.lockFile(this.manager.folder + "/" + f.name + "." + f.ext); } input.focus(); - input.addEventListener("dblclick", (event) => { - return event.stopPropagation(); - }); - input.addEventListener("blur", () => { - var l, len2, len3, m, name, oldpath, path, results, value; - input.parentNode.replaceChild(span, input); - value = RegexLib.fixFilename(input.value); - if (value !== folder.name) { - if (RegexLib.filename.test(value) && (folder.parent.getSubFolder(value) == null)) { - span.innerText = value; - for (l = 0, len2 = files.length; l < len2; l++) { - f = files[l]; - f.old_path = f.parent.getFullDashPath() + "-" + f.shortname + "." + f.ext; - } - folder.name = value; - results = []; - for (m = 0, len3 = files.length; m < len3; m++) { - f = files[m]; - oldpath = f.old_path; - name = f.parent.getFullDashPath() + "-" + f.shortname; - path = name + "." + f.ext; - f.rename(name); - results.push(this.app.client.sendRequest({ - name: "rename_project_file", - project: this.app.project.id, - source: `${this.manager.folder}/${oldpath}`, - dest: `${this.manager.folder}/${path}`, - thumbnail: this.manager.use_thumbnails - }, (msg) => { - return this.app.project[this.manager.update_list](); - })); + input.addEventListener("dblclick", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); + input.addEventListener("blur", (function(_this) { + return function() { + var l, len2, len3, m, name, oldpath, path, results, value; + input.parentNode.replaceChild(span, input); + value = RegexLib.fixFilename(input.value); + if (value !== folder.name) { + if (RegexLib.filename.test(value) && (folder.parent.getSubFolder(value) == null)) { + span.innerText = value; + for (l = 0, len2 = files.length; l < len2; l++) { + f = files[l]; + f.old_path = f.parent.getFullDashPath() + "-" + f.shortname + "." + f.ext; + } + folder.name = value; + results = []; + for (m = 0, len3 = files.length; m < len3; m++) { + f = files[m]; + oldpath = f.old_path; + name = f.parent.getFullDashPath() + "-" + f.shortname; + path = name + "." + f.ext; + f.rename(name); + results.push(_this.app.client.sendRequest({ + name: "rename_project_file", + project: _this.app.project.id, + source: _this.manager.folder + "/" + oldpath, + dest: _this.manager.folder + "/" + path, + thumbnail: _this.manager.use_thumbnails + }, function(msg) { + return _this.app.project[_this.manager.update_list](); + })); + } + return results; } - return results; } - } - }); - return input.addEventListener("keydown", (event) => { - // @app.project.lockFile "ms/#{source.name}.ms" - if (event.key === "Enter") { - event.preventDefault(); - input.blur(); - return false; - } else { - return true; - } - }); - } + }; + })(this)); + return input.addEventListener("keydown", (function(_this) { + return function(event) { + if (event.key === "Enter") { + event.preventDefault(); + input.blur(); + return false; + } else { + return true; + } + }; + })(this)); + }; + + return FolderView; -}; +})(); diff --git a/static/js/languages/javascript/runner.js b/static/js/languages/javascript/runner.js index 7c2cdfba..ecb5d4fa 100644 --- a/static/js/languages/javascript/runner.js +++ b/static/js/languages/javascript/runner.js @@ -1,15 +1,17 @@ -this.Runner = class Runner { - constructor(microvm) { +this.Runner = (function() { + function Runner(microvm) { this.microvm = microvm; } - init() { + Runner.prototype.init = function() { var kd, key, src; this.initialized = true; window.ctx = this.microvm.context.global; - window.ctx.print = (text) => { - return this.microvm.context.meta.print(text); - }; + window.ctx.print = (function(_this) { + return function(text) { + return _this.microvm.context.meta.print(text); + }; + })(this); src = ""; for (key in this.microvm.context.global) { kd = key; @@ -19,19 +21,22 @@ this.Runner = class Runner { if (key === "Map") { kd = "msMap"; } - src += `${kd} = window.ctx.${key};\n`; + src += kd + " = window.ctx." + key + ";\n"; } return this.run(src); - } + }; - run(program, name = "") { + Runner.prototype.run = function(program, name) { var err, file, line; + if (name == null) { + name = ""; + } if (!this.initialized) { this.init(); } - program += `\n//# sourceURL=${name}.js`; + program += "\n//# sourceURL=" + name + ".js"; try { - return window.eval(program); + return window["eval"](program); } catch (error) { err = error; if (err.stack != null) { @@ -56,9 +61,9 @@ this.Runner = class Runner { } throw err.message; } - } + }; - call(name, args) { + Runner.prototype.call = function(name, args) { var err, file, line; try { if (window[name] != null) { @@ -89,14 +94,16 @@ this.Runner = class Runner { } throw err.message; } - } + }; - toString(obj) { + Runner.prototype.toString = function(obj) { if (obj != null) { return obj.toString(); } else { return "null"; } - } + }; + + return Runner; -}; +})(); diff --git a/static/js/languages/microscript/v2/compiler.js b/static/js/languages/microscript/v2/compiler.js index 116b0f2d..b672cbff 100644 --- a/static/js/languages/microscript/v2/compiler.js +++ b/static/js/languages/microscript/v2/compiler.js @@ -1,190 +1,122 @@ var Compiler, LocalLayer; Compiler = (function() { - class Compiler { - constructor(program) { - var i, j, len, ref, s; - this.program = program; - this.code_saves = []; - this.code = ""; - this.code = [this.code]; - this.routine = new Routine(); - this.locals = new Locals(this); - this.count = 0; - ref = this.program.statements; - for (i = j = 0, len = ref.length; j < len; i = ++j) { - s = ref[i]; - this.compile(s); - if (i < this.program.statements.length - 1) { - this.routine.POP(s); - } - } - this.routine.optimize(); - this.routine.resolveLabels(); - this.count += this.routine.opcodes.length; - this.routine.locals_size = this.locals.max_index; - } - - // console.info(@routine.toString()) - // console.info("total length: "+@count) - compile(statement) { - if (statement instanceof Program.Value) { - return this.compileValue(statement); - } else if (statement instanceof Program.Operation) { - return this.compileOperation(statement); - } else if (statement instanceof Program.Assignment) { - return this.compileAssignment(statement); - } else if (statement instanceof Program.Variable) { - return this.compileVariable(statement); - } else if (statement instanceof Program.Function) { - return this.compileFunction(statement); - } else if (statement instanceof Program.FunctionCall) { - return this.compileFunctionCall(statement); - } else if (statement instanceof Program.While) { - return this.compileWhile(statement); - } - if (statement instanceof Program.SelfAssignment) { - return this.compileSelfAssignment(statement); - } else if (statement instanceof Program.Braced) { - return this.compileBraced(statement); - } else if (statement instanceof Program.CreateObject) { - return this.compileCreateObject(statement); - } else if (statement instanceof Program.Field) { - return this.compileField(statement); - } else if (statement instanceof Program.Negate) { - return this.compileNegate(statement); - } else if (statement instanceof Program.For) { - return this.compileFor(statement); - } else if (statement instanceof Program.ForIn) { - return this.compileForIn(statement); - } else if (statement instanceof Program.Not) { - return this.compileNot(statement); - } else if (statement instanceof Program.Return) { - return this.compileReturn(statement); - } else if (statement instanceof Program.Condition) { - return this.compileCondition(statement); - } else if (statement instanceof Program.Break) { - return this.compileBreak(statement); - } else if (statement instanceof Program.Continue) { - return this.compileContinue(statement); - } else if (statement instanceof Program.CreateClass) { - return this.compileCreateClass(statement); - } else if (statement instanceof Program.NewCall) { - return this.compileNewCall(statement); - } else if (statement instanceof Program.After) { - return this.compileAfter(statement); - } else if (statement instanceof Program.Every) { - return this.compileEvery(statement); - } else if (statement instanceof Program.Do) { - return this.compileDo(statement); - } else if (statement instanceof Program.Sleep) { - return this.compileSleep(statement); - } else if (statement instanceof Program.Delete) { - return this.compileDelete(statement); - } else if (true) { - console.info(statement); - throw "Not implemented"; - } + function Compiler(program) { + var i, j, len, ref, s; + this.program = program; + this.code_saves = []; + this.code = ""; + this.code = [this.code]; + this.routine = new Routine(); + this.locals = new Locals(this); + this.count = 0; + ref = this.program.statements; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + s = ref[i]; + this.compile(s); + if (i < this.program.statements.length - 1) { + this.routine.POP(s); + } + } + this.routine.optimize(); + this.routine.resolveLabels(); + this.count += this.routine.opcodes.length; + this.routine.locals_size = this.locals.max_index; + } + + Compiler.prototype.compile = function(statement) { + if (statement instanceof Program.Value) { + return this.compileValue(statement); + } else if (statement instanceof Program.Operation) { + return this.compileOperation(statement); + } else if (statement instanceof Program.Assignment) { + return this.compileAssignment(statement); + } else if (statement instanceof Program.Variable) { + return this.compileVariable(statement); + } else if (statement instanceof Program.Function) { + return this.compileFunction(statement); + } else if (statement instanceof Program.FunctionCall) { + return this.compileFunctionCall(statement); + } else if (statement instanceof Program.While) { + return this.compileWhile(statement); + } + if (statement instanceof Program.SelfAssignment) { + return this.compileSelfAssignment(statement); + } else if (statement instanceof Program.Braced) { + return this.compileBraced(statement); + } else if (statement instanceof Program.CreateObject) { + return this.compileCreateObject(statement); + } else if (statement instanceof Program.Field) { + return this.compileField(statement); + } else if (statement instanceof Program.Negate) { + return this.compileNegate(statement); + } else if (statement instanceof Program.For) { + return this.compileFor(statement); + } else if (statement instanceof Program.ForIn) { + return this.compileForIn(statement); + } else if (statement instanceof Program.Not) { + return this.compileNot(statement); + } else if (statement instanceof Program.Return) { + return this.compileReturn(statement); + } else if (statement instanceof Program.Condition) { + return this.compileCondition(statement); + } else if (statement instanceof Program.Break) { + return this.compileBreak(statement); + } else if (statement instanceof Program.Continue) { + return this.compileContinue(statement); + } else if (statement instanceof Program.CreateClass) { + return this.compileCreateClass(statement); + } else if (statement instanceof Program.NewCall) { + return this.compileNewCall(statement); + } else if (statement instanceof Program.After) { + return this.compileAfter(statement); + } else if (statement instanceof Program.Every) { + return this.compileEvery(statement); + } else if (statement instanceof Program.Do) { + return this.compileDo(statement); + } else if (statement instanceof Program.Sleep) { + return this.compileSleep(statement); + } else if (statement instanceof Program.Delete) { + return this.compileDelete(statement); + } else if (true) { + console.info(statement); + throw "Not implemented"; } + }; - compileAssignment(statement) { - var arg_index, f, i, index, j, ref; - if (statement.local) { - if (statement.field instanceof Program.Variable) { - if (statement.expression instanceof Program.Function) { - index = this.locals.register(statement.field.identifier); //# register function locally first - this.compile(statement.expression); //# then compile function which may refer to itself - this.routine.arg1[this.routine.arg1.length - 1].import_self = index; - return this.routine.STORE_LOCAL(index, statement); - } else if (statement.expression instanceof Program.After || statement.expression instanceof Program.Do || statement.expression instanceof Program.Every) { - index = this.locals.register(statement.field.identifier); //# register thread locally first - arg_index = this.routine.arg1.length; //# thread main routine will land here - this.compile(statement.expression); //# then compile function which may refer to itself - this.routine.arg1[arg_index].import_self = index; - return this.routine.STORE_LOCAL(index, statement); - } else { - this.compile(statement.expression); //# first compile expression which may refer to another local with same name - index = this.locals.register(statement.field.identifier); //# then register a local for that name - return this.routine.STORE_LOCAL(index, statement); - } - } else { - throw "illegal"; - } - } else { - if (statement.field instanceof Program.Variable) { - if (this.locals.get(statement.field.identifier) != null) { - this.compile(statement.expression); - index = this.locals.get(statement.field.identifier); - this.routine.STORE_LOCAL(index, statement); - } else if (statement.expression instanceof Program.CreateClass) { - return this.compileUpdateClass(statement.expression, statement.field.identifier); - } else { - this.compile(statement.expression); - this.routine.STORE_VARIABLE(statement.field.identifier, statement); - } + Compiler.prototype.compileAssignment = function(statement) { + var arg_index, f, i, index, j, ref; + if (statement.local) { + if (statement.field instanceof Program.Variable) { + if (statement.expression instanceof Program.Function) { + index = this.locals.register(statement.field.identifier); + this.compile(statement.expression); + this.routine.arg1[this.routine.arg1.length - 1].import_self = index; + return this.routine.STORE_LOCAL(index, statement); + } else if (statement.expression instanceof Program.After || statement.expression instanceof Program.Do || statement.expression instanceof Program.Every) { + index = this.locals.register(statement.field.identifier); + arg_index = this.routine.arg1.length; + this.compile(statement.expression); + this.routine.arg1[arg_index].import_self = index; + return this.routine.STORE_LOCAL(index, statement); } else { - f = statement.field; - if (f.expression instanceof Program.Variable) { - if (f.expression.identifier === "this") { - this.routine.LOAD_THIS(f); - } else if (this.locals.get(f.expression.identifier) != null) { - index = this.locals.get(f.expression.identifier); - this.routine.LOAD_LOCAL_OBJECT(index, f.expression); - } else if (f.expression.identifier === "global") { - this.routine.LOAD_GLOBAL(f); - } else { - this.routine.LOAD_VARIABLE_OBJECT(f.expression.identifier, statement); - } - } else { - this.compile(f.expression); - this.routine.MAKE_OBJECT(statement); - } - for (i = j = 0, ref = f.chain.length - 2; j <= ref; i = j += 1) { - this.compile(f.chain[i]); - this.routine.LOAD_PROPERTY_OBJECT(f.chain[i]); - } - this.compile(f.chain[f.chain.length - 1]); this.compile(statement.expression); - return this.routine.STORE_PROPERTY(statement); + index = this.locals.register(statement.field.identifier); + return this.routine.STORE_LOCAL(index, statement); } + } else { + throw "illegal"; } - } - - compileSelfAssignment(statement) { - var c, f, i, index, j, op, ref; - switch (statement.operation) { - case Token.TYPE_PLUS_EQUALS: - op = "ADD"; - break; - case Token.TYPE_MINUS_EQUALS: - op = "SUB"; - break; - case Token.TYPE_MULTIPLY_EQUALS: - op = "MUL"; - break; - case Token.TYPE_DIVIDE_EQUALS: - op = "DIV"; - break; - case Token.TYPE_MODULO_EQUALS: - op = "MODULO"; - break; - case Token.TYPE_AND_EQUALS: - op = "BINARY_AND"; - break; - case Token.TYPE_OR_EQUALS: - op = "BINARY_OR"; - } + } else { if (statement.field instanceof Program.Variable) { if (this.locals.get(statement.field.identifier) != null) { - index = this.locals.get(statement.field.identifier); - this.routine.LOAD_LOCAL(index, statement); this.compile(statement.expression); - this.routine[op](statement, 1); + index = this.locals.get(statement.field.identifier); this.routine.STORE_LOCAL(index, statement); + } else if (statement.expression instanceof Program.CreateClass) { + return this.compileUpdateClass(statement.expression, statement.field.identifier); } else { - this.routine.LOAD_VARIABLE(statement.field.identifier, statement); this.compile(statement.expression); - this.routine[op](statement, 1); this.routine.STORE_VARIABLE(statement.field.identifier, statement); } } else { @@ -194,7 +126,7 @@ Compiler = (function() { this.routine.LOAD_THIS(f); } else if (this.locals.get(f.expression.identifier) != null) { index = this.locals.get(f.expression.identifier); - this.routine.LOAD_LOCAL_OBJECT(index, statement); + this.routine.LOAD_LOCAL_OBJECT(index, f.expression); } else if (f.expression.identifier === "global") { this.routine.LOAD_GLOBAL(f); } else { @@ -208,609 +140,671 @@ Compiler = (function() { this.compile(f.chain[i]); this.routine.LOAD_PROPERTY_OBJECT(f.chain[i]); } - c = f.chain[f.chain.length - 1]; this.compile(f.chain[f.chain.length - 1]); - this.routine.LOAD_PROPERTY_ATOP(statement); this.compile(statement.expression); - this.routine[op](statement, 1); return this.routine.STORE_PROPERTY(statement); } } + }; - compileOperation(op) { - var jump, ref, ref1; - if ((ref = op.operation) === "+" || ref === "-" || ref === "*" || ref === "/" || ref === "%" || ref === "&" || ref === "|" || ref === "<<" || ref === ">>") { - this.compile(op.term1); - this.compile(op.term2); - switch (op.operation) { - case "+": - this.routine.ADD(op); - break; - case "-": - this.routine.SUB(op); - break; - case "*": - this.routine.MUL(op); - break; - case "/": - this.routine.DIV(op); - break; - case "%": - this.routine.MODULO(op); - break; - case "&": - this.routine.BINARY_AND(op); - break; - case "|": - this.routine.BINARY_OR(op); - break; - case "<<": - this.routine.SHIFT_LEFT(op); - break; - case ">>": - this.routine.SHIFT_RIGHT(op); - } - } else if ((ref1 = op.operation) === "==" || ref1 === "!=" || ref1 === "<" || ref1 === ">" || ref1 === "<=" || ref1 === ">=") { - this.compile(op.term1); - this.compile(op.term2); - switch (op.operation) { - case "==": - this.routine.EQ(op); - break; - case "!=": - this.routine.NEQ(op); - break; - case "<": - this.routine.LT(op); - break; - case ">": - this.routine.GT(op); - break; - case "<=": - this.routine.LTE(op); - break; - case ">=": - this.routine.GTE(op); + Compiler.prototype.compileSelfAssignment = function(statement) { + var c, f, i, index, j, op, ref; + switch (statement.operation) { + case Token.TYPE_PLUS_EQUALS: + op = "ADD"; + break; + case Token.TYPE_MINUS_EQUALS: + op = "SUB"; + break; + case Token.TYPE_MULTIPLY_EQUALS: + op = "MUL"; + break; + case Token.TYPE_DIVIDE_EQUALS: + op = "DIV"; + break; + case Token.TYPE_MODULO_EQUALS: + op = "MODULO"; + break; + case Token.TYPE_AND_EQUALS: + op = "BINARY_AND"; + break; + case Token.TYPE_OR_EQUALS: + op = "BINARY_OR"; + } + if (statement.field instanceof Program.Variable) { + if (this.locals.get(statement.field.identifier) != null) { + index = this.locals.get(statement.field.identifier); + this.routine.LOAD_LOCAL(index, statement); + this.compile(statement.expression); + this.routine[op](statement, 1); + this.routine.STORE_LOCAL(index, statement); + } else { + this.routine.LOAD_VARIABLE(statement.field.identifier, statement); + this.compile(statement.expression); + this.routine[op](statement, 1); + this.routine.STORE_VARIABLE(statement.field.identifier, statement); + } + } else { + f = statement.field; + if (f.expression instanceof Program.Variable) { + if (f.expression.identifier === "this") { + this.routine.LOAD_THIS(f); + } else if (this.locals.get(f.expression.identifier) != null) { + index = this.locals.get(f.expression.identifier); + this.routine.LOAD_LOCAL_OBJECT(index, statement); + } else if (f.expression.identifier === "global") { + this.routine.LOAD_GLOBAL(f); + } else { + this.routine.LOAD_VARIABLE_OBJECT(f.expression.identifier, statement); } - } else if (op.operation === "and") { - jump = this.routine.createLabel("and"); - this.compile(op.term1); - this.routine.JUMPN_NOPOP(jump, op); - this.routine.POP(op); - this.compile(op.term2); - return this.routine.setLabel(jump); - } else if (op.operation === "or") { - jump = this.routine.createLabel("or"); - this.compile(op.term1); - this.routine.JUMPY_NOPOP(jump, op); - this.routine.POP(op); - this.compile(op.term2); - return this.routine.setLabel(jump); - } else if (op.operation === "^") { - this.compile(op.term1); - this.compile(op.term2); - return this.routine.BINARY_OP(Compiler.predefined_binary_functions.pow, op); } else { - return ""; + this.compile(f.expression); + this.routine.MAKE_OBJECT(statement); + } + for (i = j = 0, ref = f.chain.length - 2; j <= ref; i = j += 1) { + this.compile(f.chain[i]); + this.routine.LOAD_PROPERTY_OBJECT(f.chain[i]); } + c = f.chain[f.chain.length - 1]; + this.compile(f.chain[f.chain.length - 1]); + this.routine.LOAD_PROPERTY_ATOP(statement); + this.compile(statement.expression); + this.routine[op](statement, 1); + return this.routine.STORE_PROPERTY(statement); } + }; - compileBraced(expression) { - this.compile(expression.expression); + Compiler.prototype.compileOperation = function(op) { + var jump, ref, ref1; + if ((ref = op.operation) === "+" || ref === "-" || ref === "*" || ref === "/" || ref === "%" || ref === "&" || ref === "|" || ref === "<<" || ref === ">>") { + this.compile(op.term1); + this.compile(op.term2); + switch (op.operation) { + case "+": + this.routine.ADD(op); + break; + case "-": + this.routine.SUB(op); + break; + case "*": + this.routine.MUL(op); + break; + case "/": + this.routine.DIV(op); + break; + case "%": + this.routine.MODULO(op); + break; + case "&": + this.routine.BINARY_AND(op); + break; + case "|": + this.routine.BINARY_OR(op); + break; + case "<<": + this.routine.SHIFT_LEFT(op); + break; + case ">>": + this.routine.SHIFT_RIGHT(op); + } + } else if ((ref1 = op.operation) === "==" || ref1 === "!=" || ref1 === "<" || ref1 === ">" || ref1 === "<=" || ref1 === ">=") { + this.compile(op.term1); + this.compile(op.term2); + switch (op.operation) { + case "==": + this.routine.EQ(op); + break; + case "!=": + this.routine.NEQ(op); + break; + case "<": + this.routine.LT(op); + break; + case ">": + this.routine.GT(op); + break; + case "<=": + this.routine.LTE(op); + break; + case ">=": + this.routine.GTE(op); + } + } else if (op.operation === "and") { + jump = this.routine.createLabel("and"); + this.compile(op.term1); + this.routine.JUMPN_NOPOP(jump, op); + this.routine.POP(op); + this.compile(op.term2); + return this.routine.setLabel(jump); + } else if (op.operation === "or") { + jump = this.routine.createLabel("or"); + this.compile(op.term1); + this.routine.JUMPY_NOPOP(jump, op); + this.routine.POP(op); + this.compile(op.term2); + return this.routine.setLabel(jump); + } else if (op.operation === "^") { + this.compile(op.term1); + this.compile(op.term2); + return this.routine.BINARY_OP(Compiler.predefined_binary_functions.pow, op); + } else { + return ""; } + }; - compileNegate(expression) { - if (expression.expression instanceof Program.Value && expression.expression.type === Program.Value.TYPE_NUMBER) { - return this.routine.LOAD_VALUE(-expression.expression.value, expression); - } else { - this.compile(expression.expression); - return this.routine.NEGATE(expression); - } - } + Compiler.prototype.compileBraced = function(expression) { + this.compile(expression.expression); + }; - compileNot(expression) { + Compiler.prototype.compileNegate = function(expression) { + if (expression.expression instanceof Program.Value && expression.expression.type === Program.Value.TYPE_NUMBER) { + return this.routine.LOAD_VALUE(-expression.expression.value, expression); + } else { this.compile(expression.expression); - return this.routine.NOT(expression); + return this.routine.NEGATE(expression); } + }; - compileValue(value) { - var i, j, ref; - switch (value.type) { - case Program.Value.TYPE_NUMBER: - this.routine.LOAD_VALUE(value.value, value); - break; - case Program.Value.TYPE_STRING: - this.routine.LOAD_VALUE(value.value, value); - break; - case Program.Value.TYPE_ARRAY: - this.routine.CREATE_ARRAY(value); - for (i = j = 0, ref = value.value.length - 1; j <= ref; i = j += 1) { - this.routine.LOAD_VALUE(i, value); - this.compile(value.value[i]); - this.routine.CREATE_PROPERTY(value); - } - } + Compiler.prototype.compileNot = function(expression) { + this.compile(expression.expression); + return this.routine.NOT(expression); + }; + + Compiler.prototype.compileValue = function(value) { + var i, j, ref; + switch (value.type) { + case Program.Value.TYPE_NUMBER: + this.routine.LOAD_VALUE(value.value, value); + break; + case Program.Value.TYPE_STRING: + this.routine.LOAD_VALUE(value.value, value); + break; + case Program.Value.TYPE_ARRAY: + this.routine.CREATE_ARRAY(value); + for (i = j = 0, ref = value.value.length - 1; j <= ref; i = j += 1) { + this.routine.LOAD_VALUE(i, value); + this.compile(value.value[i]); + this.routine.CREATE_PROPERTY(value); + } } + }; - compileVariable(variable) { - var index, v; - v = variable.identifier; - if (v === "this") { - return this.routine.LOAD_THIS(variable); - } else if (v === "global") { - return this.routine.LOAD_GLOBAL(variable); - } else if (Compiler.predefined_values[v] != null) { - return this.routine.LOAD_VALUE(Compiler.predefined_values[v], variable); - } else if (this.locals.get(v) != null) { - index = this.locals.get(v); - return this.routine.LOAD_LOCAL(index, variable); - } else { - return this.routine.LOAD_VARIABLE(v, variable); - } + Compiler.prototype.compileVariable = function(variable) { + var index, v; + v = variable.identifier; + if (v === "this") { + return this.routine.LOAD_THIS(variable); + } else if (v === "global") { + return this.routine.LOAD_GLOBAL(variable); + } else if (Compiler.predefined_values[v] != null) { + return this.routine.LOAD_VALUE(Compiler.predefined_values[v], variable); + } else if (this.locals.get(v) != null) { + index = this.locals.get(v); + return this.routine.LOAD_LOCAL(index, variable); + } else { + return this.routine.LOAD_VARIABLE(v, variable); } + }; - compileField(field) { - var c, i, id, index, j, k, len, ref, ref1; - c = field.chain[field.chain.length - 1]; - if (c instanceof Program.Value && c.value === "type") { - if (field.chain.length === 1) { - if (field.expression instanceof Program.Variable) { // variable.type - id = field.expression.identifier; - if (this.locals.get(id) != null) { - index = this.locals.get(id); - this.routine.LOAD_LOCAL(index, field); - this.routine.TYPE(field); - } else if (Compiler.predefined_values[id] != null) { - this.routine.LOAD_VALUE("number", field); - } else if ((Compiler.predefined_unary_functions[id] != null) || Compiler.predefined_binary_functions[id]) { - this.routine.LOAD_VALUE("function", field); - } else { - this.routine.VARIABLE_TYPE(id, field.expression); - } - } else { - this.compile(field.expression); + Compiler.prototype.compileField = function(field) { + var c, i, id, index, j, k, len, ref, ref1; + c = field.chain[field.chain.length - 1]; + if (c instanceof Program.Value && c.value === "type") { + if (field.chain.length === 1) { + if (field.expression instanceof Program.Variable) { + id = field.expression.identifier; + if (this.locals.get(id) != null) { + index = this.locals.get(id); + this.routine.LOAD_LOCAL(index, field); this.routine.TYPE(field); + } else if (Compiler.predefined_values[id] != null) { + this.routine.LOAD_VALUE("number", field); + } else if ((Compiler.predefined_unary_functions[id] != null) || Compiler.predefined_binary_functions[id]) { + this.routine.LOAD_VALUE("function", field); + } else { + this.routine.VARIABLE_TYPE(id, field.expression); } } else { this.compile(field.expression); - for (i = j = 0, ref = field.chain.length - 3; j <= ref; i = j += 1) { - this.compile(field.chain[i]); - this.routine.LOAD_PROPERTY(field); - } - this.compile(field.chain[field.chain.length - 2]); - this.routine.PROPERTY_TYPE(field.expression); + this.routine.TYPE(field); } } else { this.compile(field.expression); - ref1 = field.chain; - for (k = 0, len = ref1.length; k < len; k++) { - c = ref1[k]; - this.compile(c); + for (i = j = 0, ref = field.chain.length - 3; j <= ref; i = j += 1) { + this.compile(field.chain[i]); this.routine.LOAD_PROPERTY(field); } + this.compile(field.chain[field.chain.length - 2]); + this.routine.PROPERTY_TYPE(field.expression); } - } - - compileFieldParent(field) { - var c, i, j, ref; + } else { this.compile(field.expression); - for (i = j = 0, ref = field.chain.length - 2; j <= ref; i = j += 1) { - c = field.chain[i]; + ref1 = field.chain; + for (k = 0, len = ref1.length; k < len; k++) { + c = ref1[k]; this.compile(c); this.routine.LOAD_PROPERTY(field); } } + }; - compileFunctionCall(call) { - var a, funk, i, index, j, k, l, len, len1, len2, len3, len4, m, n, ref, ref1, ref2, ref3, ref4; - if (call.expression instanceof Program.Field) { - ref = call.args; - for (i = j = 0, len = ref.length; j < len; i = ++j) { - a = ref[i]; - this.compile(a); + Compiler.prototype.compileFieldParent = function(field) { + var c, i, j, ref; + this.compile(field.expression); + for (i = j = 0, ref = field.chain.length - 2; j <= ref; i = j += 1) { + c = field.chain[i]; + this.compile(c); + this.routine.LOAD_PROPERTY(field); + } + }; + + Compiler.prototype.compileFunctionCall = function(call) { + var a, funk, i, index, j, k, l, len, len1, len2, len3, len4, m, n, ref, ref1, ref2, ref3, ref4; + if (call.expression instanceof Program.Field) { + ref = call.args; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + a = ref[i]; + this.compile(a); + } + this.compileFieldParent(call.expression); + this.compile(call.expression.chain[call.expression.chain.length - 1]); + return this.routine.FUNCTION_APPLY_PROPERTY(call.args.length, call); + } else if (call.expression instanceof Program.Variable) { + if (Compiler.predefined_unary_functions[call.expression.identifier] != null) { + funk = Compiler.predefined_unary_functions[call.expression.identifier]; + if (call.args.length > 0) { + this.compile(call.args[0]); + } else { + this.routine.LOAD_VALUE(0, call); } - this.compileFieldParent(call.expression); - this.compile(call.expression.chain[call.expression.chain.length - 1]); - return this.routine.FUNCTION_APPLY_PROPERTY(call.args.length, call); - } else if (call.expression instanceof Program.Variable) { - if (Compiler.predefined_unary_functions[call.expression.identifier] != null) { - funk = Compiler.predefined_unary_functions[call.expression.identifier]; - if (call.args.length > 0) { - this.compile(call.args[0]); - } else { - this.routine.LOAD_VALUE(0, call); - } - return this.routine.UNARY_OP(funk, call); - } else if (Compiler.predefined_binary_functions[call.expression.identifier] != null) { - funk = Compiler.predefined_binary_functions[call.expression.identifier]; - if (call.args.length > 0) { - this.compile(call.args[0]); - } else { - this.routine.LOAD_VALUE(0, call); - } - if (call.args.length > 1) { - this.compile(call.args[1]); - } else { - this.routine.LOAD_VALUE(0, call); - } - return this.routine.BINARY_OP(funk, call); - } else if (call.expression.identifier === "super") { - ref1 = call.args; - for (i = k = 0, len1 = ref1.length; k < len1; i = ++k) { - a = ref1[i]; - this.compile(a); - } - return this.routine.SUPER_CALL(call.args.length, call); - } else if (this.locals.get(call.expression.identifier) != null) { - ref2 = call.args; - for (i = l = 0, len2 = ref2.length; l < len2; i = ++l) { - a = ref2[i]; - this.compile(a); - } - index = this.locals.get(call.expression.identifier); - this.routine.LOAD_LOCAL(index, call); - return this.routine.FUNCTION_CALL(call.args.length, call); + return this.routine.UNARY_OP(funk, call); + } else if (Compiler.predefined_binary_functions[call.expression.identifier] != null) { + funk = Compiler.predefined_binary_functions[call.expression.identifier]; + if (call.args.length > 0) { + this.compile(call.args[0]); } else { - ref3 = call.args; - for (i = m = 0, len3 = ref3.length; m < len3; i = ++m) { - a = ref3[i]; - this.compile(a); - } - this.routine.LOAD_VALUE(call.expression.identifier, call); - return this.routine.FUNCTION_APPLY_VARIABLE(call.args.length, call); + this.routine.LOAD_VALUE(0, call); } - } else { - ref4 = call.args; - for (n = 0, len4 = ref4.length; n < len4; n++) { - a = ref4[n]; + if (call.args.length > 1) { + this.compile(call.args[1]); + } else { + this.routine.LOAD_VALUE(0, call); + } + return this.routine.BINARY_OP(funk, call); + } else if (call.expression.identifier === "super") { + ref1 = call.args; + for (i = k = 0, len1 = ref1.length; k < len1; i = ++k) { + a = ref1[i]; this.compile(a); } - this.compile(call.expression); + return this.routine.SUPER_CALL(call.args.length, call); + } else if (this.locals.get(call.expression.identifier) != null) { + ref2 = call.args; + for (i = l = 0, len2 = ref2.length; l < len2; i = ++l) { + a = ref2[i]; + this.compile(a); + } + index = this.locals.get(call.expression.identifier); + this.routine.LOAD_LOCAL(index, call); return this.routine.FUNCTION_CALL(call.args.length, call); - } - } - - compileFor(forloop) { - var for_continue, for_end, for_start, iterator, save_break, save_continue; - iterator = this.locals.register(forloop.iterator); - this.locals.allocate(); // range_to - this.locals.allocate(); // step - this.compile(forloop.range_from); - this.routine.STORE_LOCAL(iterator, forloop); - this.routine.POP(forloop); - this.compile(forloop.range_to); - if (forloop.range_by !== 0) { - this.compile(forloop.range_by); } else { - this.routine.LOAD_VALUE(0, forloop); - } - for_start = this.routine.createLabel("for_start"); - for_continue = this.routine.createLabel("for_continue"); - for_end = this.routine.createLabel("for_end"); - this.routine.FORLOOP_INIT([iterator, for_end], forloop); - this.routine.setLabel(for_start); - this.locals.push(); - save_break = this.break_label; - save_continue = this.continue_label; - this.break_label = for_end; - this.continue_label = for_continue; - this.compileSequence(forloop.sequence); - this.break_label = save_break; - this.continue_label = save_continue; - this.routine.setLabel(for_continue); - this.routine.FORLOOP_CONTROL([iterator, for_start], forloop); - this.routine.setLabel(for_end); - return this.locals.pop(); - } - - compileForIn(forloop) { - var for_continue, for_end, for_start, iterator, save_break, save_continue; - iterator = this.locals.register(forloop.iterator); - this.locals.allocate(); // array - this.locals.allocate(); // index - this.compile(forloop.list); - for_start = this.routine.createLabel("for_start"); - for_continue = this.routine.createLabel("for_continue"); - for_end = this.routine.createLabel("for_end"); - this.routine.FORIN_INIT([iterator, for_end], forloop); - this.routine.setLabel(for_start); - this.locals.push(); - save_break = this.break_label; - save_continue = this.continue_label; - this.break_label = for_end; - this.continue_label = for_continue; - this.compileSequence(forloop.sequence); - this.break_label = save_break; - this.continue_label = save_continue; - this.routine.setLabel(for_continue); - this.routine.FORIN_CONTROL([iterator, for_start], forloop); - this.routine.setLabel(for_end); - return this.locals.pop(); - } - - compileSequence(sequence) { - var i, j, ref; - for (i = j = 0, ref = sequence.length - 1; j <= ref; i = j += 1) { - if (!sequence[i].nopop) { - this.routine.POP(sequence[i]); + ref3 = call.args; + for (i = m = 0, len3 = ref3.length; m < len3; i = ++m) { + a = ref3[i]; + this.compile(a); } - this.compile(sequence[i]); + this.routine.LOAD_VALUE(call.expression.identifier, call); + return this.routine.FUNCTION_APPLY_VARIABLE(call.args.length, call); } + } else { + ref4 = call.args; + for (n = 0, len4 = ref4.length; n < len4; n++) { + a = ref4[n]; + this.compile(a); + } + this.compile(call.expression); + return this.routine.FUNCTION_CALL(call.args.length, call); } + }; - compileWhile(whiloop) { - var end, save_break, save_continue, start; - this.locals.push(); - start = this.routine.createLabel("while_start"); - end = this.routine.createLabel("while_end"); - this.routine.LOAD_VALUE(0, whiloop); - this.routine.setLabel(start); - this.compile(whiloop.condition); - this.routine.JUMPN(end); - save_break = this.break_label; - save_continue = this.continue_label; - this.break_label = end; - this.continue_label = start; - this.compileSequence(whiloop.sequence); - this.routine.JUMP(start, whiloop); - this.break_label = save_break; - this.continue_label = save_continue; - this.routine.setLabel(end); - return this.locals.pop(); - } - - compileBreak(statement) { - if (this.break_label != null) { - return this.routine.JUMP(this.break_label); + Compiler.prototype.compileFor = function(forloop) { + var for_continue, for_end, for_start, iterator, save_break, save_continue; + iterator = this.locals.register(forloop.iterator); + this.locals.allocate(); + this.locals.allocate(); + this.compile(forloop.range_from); + this.routine.STORE_LOCAL(iterator, forloop); + this.routine.POP(forloop); + this.compile(forloop.range_to); + if (forloop.range_by !== 0) { + this.compile(forloop.range_by); + } else { + this.routine.LOAD_VALUE(0, forloop); + } + for_start = this.routine.createLabel("for_start"); + for_continue = this.routine.createLabel("for_continue"); + for_end = this.routine.createLabel("for_end"); + this.routine.FORLOOP_INIT([iterator, for_end], forloop); + this.routine.setLabel(for_start); + this.locals.push(); + save_break = this.break_label; + save_continue = this.continue_label; + this.break_label = for_end; + this.continue_label = for_continue; + this.compileSequence(forloop.sequence); + this.break_label = save_break; + this.continue_label = save_continue; + this.routine.setLabel(for_continue); + this.routine.FORLOOP_CONTROL([iterator, for_start], forloop); + this.routine.setLabel(for_end); + return this.locals.pop(); + }; + + Compiler.prototype.compileForIn = function(forloop) { + var for_continue, for_end, for_start, iterator, save_break, save_continue; + iterator = this.locals.register(forloop.iterator); + this.locals.allocate(); + this.locals.allocate(); + this.compile(forloop.list); + for_start = this.routine.createLabel("for_start"); + for_continue = this.routine.createLabel("for_continue"); + for_end = this.routine.createLabel("for_end"); + this.routine.FORIN_INIT([iterator, for_end], forloop); + this.routine.setLabel(for_start); + this.locals.push(); + save_break = this.break_label; + save_continue = this.continue_label; + this.break_label = for_end; + this.continue_label = for_continue; + this.compileSequence(forloop.sequence); + this.break_label = save_break; + this.continue_label = save_continue; + this.routine.setLabel(for_continue); + this.routine.FORIN_CONTROL([iterator, for_start], forloop); + this.routine.setLabel(for_end); + return this.locals.pop(); + }; + + Compiler.prototype.compileSequence = function(sequence) { + var i, j, ref; + for (i = j = 0, ref = sequence.length - 1; j <= ref; i = j += 1) { + if (!sequence[i].nopop) { + this.routine.POP(sequence[i]); } + this.compile(sequence[i]); } + }; - compileContinue(statement) { - if (this.continue_label != null) { - return this.routine.JUMP(this.continue_label); - } + Compiler.prototype.compileWhile = function(whiloop) { + var end, save_break, save_continue, start; + this.locals.push(); + start = this.routine.createLabel("while_start"); + end = this.routine.createLabel("while_end"); + this.routine.LOAD_VALUE(0, whiloop); + this.routine.setLabel(start); + this.compile(whiloop.condition); + this.routine.JUMPN(end); + save_break = this.break_label; + save_continue = this.continue_label; + this.break_label = end; + this.continue_label = start; + this.compileSequence(whiloop.sequence); + this.routine.JUMP(start, whiloop); + this.break_label = save_break; + this.continue_label = save_continue; + this.routine.setLabel(end); + return this.locals.pop(); + }; + + Compiler.prototype.compileBreak = function(statement) { + if (this.break_label != null) { + return this.routine.JUMP(this.break_label); } + }; - compileFunction(func) { - var r; - r = this.compileFunctionBody(func); - return this.routine.LOAD_ROUTINE(r, func); - } - - compileFunctionBody(func) { - var a, args, i, index, j, k, l, label, len, local_index, locals, m, numargs, r, ref, ref1, ref2, ref3, routine; - routine = this.routine; - locals = this.locals; - this.routine = new Routine(func.args != null ? func.args.length : 0); - this.locals = new Locals(this, locals); - local_index = this.locals.index; - this.routine.uses_arguments = true; - if (func.args != null) { - if (this.routine.uses_arguments) { - args = this.locals.register("arguments"); - this.routine.STORE_LOCAL(args, func); - this.routine.POP(func); - } - numargs = this.locals.register("+numargs"); - this.routine.STORE_LOCAL(numargs, func); + Compiler.prototype.compileContinue = function(statement) { + if (this.continue_label != null) { + return this.routine.JUMP(this.continue_label); + } + }; + + Compiler.prototype.compileFunction = function(func) { + var r; + r = this.compileFunctionBody(func); + return this.routine.LOAD_ROUTINE(r, func); + }; + + Compiler.prototype.compileFunctionBody = function(func) { + var a, args, i, index, j, k, l, label, len, local_index, locals, m, numargs, r, ref, ref1, ref2, ref3, routine; + routine = this.routine; + locals = this.locals; + this.routine = new Routine(func.args != null ? func.args.length : 0); + this.locals = new Locals(this, locals); + local_index = this.locals.index; + this.routine.uses_arguments = true; + if (func.args != null) { + if (this.routine.uses_arguments) { + args = this.locals.register("arguments"); + this.routine.STORE_LOCAL(args, func); this.routine.POP(func); - for (i = j = ref = func.args.length - 1; j >= 0; i = j += -1) { - a = func.args[i]; - index = this.locals.register(a.name); + } + numargs = this.locals.register("+numargs"); + this.routine.STORE_LOCAL(numargs, func); + this.routine.POP(func); + for (i = j = ref = func.args.length - 1; j >= 0; i = j += -1) { + a = func.args[i]; + index = this.locals.register(a.name); + this.routine.STORE_LOCAL(index, func); + this.routine.POP(func); + } + for (i = k = 0, ref1 = func.args.length - 1; k <= ref1; i = k += 1) { + a = func.args[i]; + if (a["default"] != null) { + index = this.locals.get(a.name); + label = this.routine.createLabel("default_arg"); + this.routine.LOAD_VALUE(i, func); + this.routine.LOAD_LOCAL(numargs, func); + this.routine.LT(func); + this.routine.JUMPY(label, func); + this.compile(a["default"]); this.routine.STORE_LOCAL(index, func); this.routine.POP(func); - } - for (i = k = 0, ref1 = func.args.length - 1; k <= ref1; i = k += 1) { - a = func.args[i]; - if (a.default != null) { - index = this.locals.get(a.name); - label = this.routine.createLabel("default_arg"); - this.routine.LOAD_VALUE(i, func); - this.routine.LOAD_LOCAL(numargs, func); - this.routine.LT(func); - this.routine.JUMPY(label, func); - this.compile(a.default); - this.routine.STORE_LOCAL(index, func); - this.routine.POP(func); - this.routine.setLabel(label); - } + this.routine.setLabel(label); } } - if (func.sequence.length > 0) { - for (i = l = 0, ref2 = func.sequence.length - 1; l <= ref2; i = l += 1) { - this.compile(func.sequence[i]); - if (i < func.sequence.length - 1) { - this.routine.POP(func.sequence[i]); - } else { - this.routine.RETURN(func.sequence[i]); - } + } + if (func.sequence.length > 0) { + for (i = l = 0, ref2 = func.sequence.length - 1; l <= ref2; i = l += 1) { + this.compile(func.sequence[i]); + if (i < func.sequence.length - 1) { + this.routine.POP(func.sequence[i]); + } else { + this.routine.RETURN(func.sequence[i]); } - } else { - this.routine.LOAD_VALUE(0, func); - this.routine.RETURN(func); - } - if ((func.args != null) && !this.locals.arguments_used) { - this.routine.uses_arguments = false; - this.routine.remove(0); - this.routine.remove(0); - } - index = 0; - ref3 = this.locals.imports; - for (m = 0, len = ref3.length; m < len; m++) { - i = ref3[m]; - this.routine.OP_INSERT(OPCODES.LOAD_IMPORT, func, index, index * 3); - this.routine.OP_INSERT(OPCODES.STORE_LOCAL, func, i.index, index * 3 + 1); - this.routine.OP_INSERT(OPCODES.POP, func, 0, index * 3 + 2); - this.routine.import_refs.push(i.source); - index += 1; - } - this.routine.optimize(); - this.routine.resolveLabels(); - this.count += this.routine.opcodes.length; - r = this.routine; - // console.info r.toString() - this.routine.locals_size = this.locals.max_index; - this.routine = routine; - this.locals = locals; - return r; - } - - compileReturn(ret) { - if (ret.expression != null) { - this.compile(ret.expression); - return this.routine.RETURN(ret); - } else { - this.routine.LOAD_VALUE(0, ret); - return this.routine.RETURN(ret); } + } else { + this.routine.LOAD_VALUE(0, func); + this.routine.RETURN(func); + } + if ((func.args != null) && !this.locals.arguments_used) { + this.routine.uses_arguments = false; + this.routine.remove(0); + this.routine.remove(0); + } + index = 0; + ref3 = this.locals.imports; + for (m = 0, len = ref3.length; m < len; m++) { + i = ref3[m]; + this.routine.OP_INSERT(OPCODES.LOAD_IMPORT, func, index, index * 3); + this.routine.OP_INSERT(OPCODES.STORE_LOCAL, func, i.index, index * 3 + 1); + this.routine.OP_INSERT(OPCODES.POP, func, 0, index * 3 + 2); + this.routine.import_refs.push(i.source); + index += 1; + } + this.routine.optimize(); + this.routine.resolveLabels(); + this.count += this.routine.opcodes.length; + r = this.routine; + this.routine.locals_size = this.locals.max_index; + this.routine = routine; + this.locals = locals; + return r; + }; + + Compiler.prototype.compileReturn = function(ret) { + if (ret.expression != null) { + this.compile(ret.expression); + return this.routine.RETURN(ret); + } else { + this.routine.LOAD_VALUE(0, ret); + return this.routine.RETURN(ret); } + }; - compileCondition(condition) { - var c, chain, condition_end, condition_next, i, j, ref; - chain = condition.chain; - this.routine.LOAD_VALUE(0, condition); - condition_end = this.routine.createLabel("condition_end"); - for (i = j = 0, ref = chain.length - 1; j <= ref; i = j += 1) { - condition_next = this.routine.createLabel("condition_next"); - c = chain[i]; - this.compile(c.condition); - this.routine.JUMPN(condition_next); + Compiler.prototype.compileCondition = function(condition) { + var c, chain, condition_end, condition_next, i, j, ref; + chain = condition.chain; + this.routine.LOAD_VALUE(0, condition); + condition_end = this.routine.createLabel("condition_end"); + for (i = j = 0, ref = chain.length - 1; j <= ref; i = j += 1) { + condition_next = this.routine.createLabel("condition_next"); + c = chain[i]; + this.compile(c.condition); + this.routine.JUMPN(condition_next); + this.locals.push(); + this.compileSequence(c.sequence); + this.locals.pop(); + this.routine.JUMP(condition_end, condition); + this.routine.setLabel(condition_next); + if (i === chain.length - 1 && (c["else"] != null)) { this.locals.push(); - this.compileSequence(c.sequence); + this.compileSequence(c["else"]); this.locals.pop(); - this.routine.JUMP(condition_end, condition); - this.routine.setLabel(condition_next); - if (i === chain.length - 1 && (c.else != null)) { - this.locals.push(); - this.compileSequence(c.else); - this.locals.pop(); - } } - this.routine.setLabel(condition_end); } + this.routine.setLabel(condition_end); + }; - formatField(field) { - if (field === "constructor") { - field = "_constructor"; - } - return field.toString().replace(/"/g, "\\\""); - } - - compileCreateObject(statement) { - var f, j, len, ref; - this.routine.CREATE_OBJECT(statement); - ref = statement.fields; - for (j = 0, len = ref.length; j < len; j++) { - f = ref[j]; - this.routine.LOAD_VALUE(f.field, statement); - this.compile(f.value); - this.routine.CREATE_PROPERTY(statement); - } + Compiler.prototype.formatField = function(field) { + if (field === "constructor") { + field = "_constructor"; } + return field.toString().replace(/"/g, "\\\""); + }; - compileCreateClass(statement) { - var f, j, len, ref, variable; - if (statement.ext != null) { - statement.ext.nowarning = true; - this.compile(statement.ext); - } else { - this.routine.LOAD_VALUE(0, statement); - } - variable = (statement.ext != null) && statement.ext instanceof Program.Variable ? statement.ext.identifier : 0; - this.routine.CREATE_CLASS(variable, statement); - ref = statement.fields; - for (j = 0, len = ref.length; j < len; j++) { - f = ref[j]; - this.routine.LOAD_VALUE(f.field, statement); - this.compile(f.value); - this.routine.CREATE_PROPERTY(statement); - } + Compiler.prototype.compileCreateObject = function(statement) { + var f, j, len, ref; + this.routine.CREATE_OBJECT(statement); + ref = statement.fields; + for (j = 0, len = ref.length; j < len; j++) { + f = ref[j]; + this.routine.LOAD_VALUE(f.field, statement); + this.compile(f.value); + this.routine.CREATE_PROPERTY(statement); } + }; - compileUpdateClass(statement, variable) { - this.compileCreateClass(statement); - return this.routine.UPDATE_CLASS(variable, statement); + Compiler.prototype.compileCreateClass = function(statement) { + var f, j, len, ref, variable; + if (statement.ext != null) { + statement.ext.nowarning = true; + this.compile(statement.ext); + } else { + this.routine.LOAD_VALUE(0, statement); } - - compileNewCall(statement) { - var a, call, i, j, len, ref; - call = statement.expression; - this.routine.LOAD_VALUE(0, statement); // reserve spot on stack for the class instance - ref = call.args; - for (i = j = 0, len = ref.length; j < len; i = ++j) { - a = ref[i]; - this.compile(a); - } - this.compile(call.expression); - this.routine.NEW_CALL(call.args.length, statement); - return this.routine.POP(statement); // pop return value of class constructor - } - - compileAfter(after) { - var r; - r = this.compileFunctionBody(after); - this.routine.LOAD_ROUTINE(r, after); - this.compile(after.delay); - if ((after.multiplier != null) && after.multiplier !== 1) { - this.routine.LOAD_VALUE(after.multiplier, after); - this.routine.MUL(after); - } - return this.routine.AFTER(after); + variable = (statement.ext != null) && statement.ext instanceof Program.Variable ? statement.ext.identifier : 0; + this.routine.CREATE_CLASS(variable, statement); + ref = statement.fields; + for (j = 0, len = ref.length; j < len; j++) { + f = ref[j]; + this.routine.LOAD_VALUE(f.field, statement); + this.compile(f.value); + this.routine.CREATE_PROPERTY(statement); } + }; - compileEvery(every) { - var r; - r = this.compileFunctionBody(every); - this.routine.LOAD_ROUTINE(r, every); - this.compile(every.delay); - if ((every.multiplier != null) && every.multiplier !== 1) { - this.routine.LOAD_VALUE(every.multiplier, every); - this.routine.MUL(every); - } - return this.routine.EVERY(every); + Compiler.prototype.compileUpdateClass = function(statement, variable) { + this.compileCreateClass(statement); + return this.routine.UPDATE_CLASS(variable, statement); + }; + + Compiler.prototype.compileNewCall = function(statement) { + var a, call, i, j, len, ref; + call = statement.expression; + this.routine.LOAD_VALUE(0, statement); + ref = call.args; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + a = ref[i]; + this.compile(a); + } + this.compile(call.expression); + this.routine.NEW_CALL(call.args.length, statement); + return this.routine.POP(statement); + }; + + Compiler.prototype.compileAfter = function(after) { + var r; + r = this.compileFunctionBody(after); + this.routine.LOAD_ROUTINE(r, after); + this.compile(after.delay); + if ((after.multiplier != null) && after.multiplier !== 1) { + this.routine.LOAD_VALUE(after.multiplier, after); + this.routine.MUL(after); } + return this.routine.AFTER(after); + }; - compileDo(dostuff) { - var r; - r = this.compileFunctionBody(dostuff); - this.routine.LOAD_ROUTINE(r, dostuff); - return this.routine.DO(dostuff); + Compiler.prototype.compileEvery = function(every) { + var r; + r = this.compileFunctionBody(every); + this.routine.LOAD_ROUTINE(r, every); + this.compile(every.delay); + if ((every.multiplier != null) && every.multiplier !== 1) { + this.routine.LOAD_VALUE(every.multiplier, every); + this.routine.MUL(every); } + return this.routine.EVERY(every); + }; - compileSleep(sleep) { - this.compile(sleep.delay); - if ((sleep.multiplier != null) && sleep.multiplier !== 1) { - this.routine.LOAD_VALUE(sleep.multiplier, sleep); - this.routine.MUL(sleep); - } - return this.routine.SLEEP(sleep); + Compiler.prototype.compileDo = function(dostuff) { + var r; + r = this.compileFunctionBody(dostuff); + this.routine.LOAD_ROUTINE(r, dostuff); + return this.routine.DO(dostuff); + }; + + Compiler.prototype.compileSleep = function(sleep) { + this.compile(sleep.delay); + if ((sleep.multiplier != null) && sleep.multiplier !== 1) { + this.routine.LOAD_VALUE(sleep.multiplier, sleep); + this.routine.MUL(sleep); } + return this.routine.SLEEP(sleep); + }; - compileDelete(del) { - var chain, i, j, ref; - if (del.field instanceof Program.Variable) { - this.routine.LOAD_THIS(del); - this.routine.LOAD_VALUE(del.field.identifier, del); - this.routine.DELETE(del); - } else { - this.compile(del.field.expression); - chain = del.field.chain; - for (i = j = 0, ref = chain.length - 1; j <= ref; i = j += 1) { - this.compile(chain[i]); - if (i < chain.length - 1) { - this.routine.LOAD_PROPERTY(del); - } + Compiler.prototype.compileDelete = function(del) { + var chain, i, j, ref; + if (del.field instanceof Program.Variable) { + this.routine.LOAD_THIS(del); + this.routine.LOAD_VALUE(del.field.identifier, del); + this.routine.DELETE(del); + } else { + this.compile(del.field.expression); + chain = del.field.chain; + for (i = j = 0, ref = chain.length - 1; j <= ref; i = j += 1) { + this.compile(chain[i]); + if (i < chain.length - 1) { + this.routine.LOAD_PROPERTY(del); } - this.routine.DELETE(del); } + this.routine.DELETE(del); } + }; - exec(context) { - this.processor = new Processor(); - this.processor.load(this.routine); - return this.processor.run(context); - } - + Compiler.prototype.exec = function(context) { + this.processor = new Processor(); + this.processor.load(this.routine); + return this.processor.run(context); }; Compiler.predefined_unary_functions = { @@ -859,18 +853,18 @@ Compiler = (function() { Compiler.predefined_values = { PI: Math.PI, - true: 1, - false: 0 + "true": 1, + "false": 0 }; return Compiler; -}).call(this); +})(); -this.Locals = class Locals { - constructor(compiler, parent = null) { +this.Locals = (function() { + function Locals(compiler, parent) { this.compiler = compiler; - this.parent = parent; + this.parent = parent != null ? parent : null; this.layers = []; this.index = 0; this.max_index = 0; @@ -878,33 +872,30 @@ this.Locals = class Locals { this.imports = []; } - increment() { + Locals.prototype.increment = function() { var spot; spot = this.index++; this.max_index = Math.max(this.index, this.max_index); return spot; - } + }; - push() { + Locals.prototype.push = function() { return this.layers.push(new LocalLayer(this)); - } + }; - pop() { - // resetting the @index below was causing erasure of outer locals - // when used after the block ; such reset is not needed - //@index = @layers[@layers.length-1].start_index + Locals.prototype.pop = function() { return this.layers.splice(this.layers.length - 1, 1); - } + }; - register(name) { + Locals.prototype.register = function(name) { return this.layers[this.layers.length - 1].register(name); - } + }; - allocate() { + Locals.prototype.allocate = function() { return this.layers[this.layers.length - 1].allocate(); - } + }; - get(name) { + Locals.prototype.get = function(name) { var i, index, j, ref, v; if (name === "arguments") { this.arguments_used = true; @@ -928,31 +919,35 @@ this.Locals = class Locals { } } return null; - } + }; + + return Locals; -}; +})(); -LocalLayer = class LocalLayer { - constructor(locals1) { +LocalLayer = (function() { + function LocalLayer(locals1) { this.locals = locals1; this.start_index = this.locals.index; this.registered = {}; } - register(name) { + LocalLayer.prototype.register = function(name) { return this.registered[name] = this.locals.increment(); - } + }; - allocate() { + LocalLayer.prototype.allocate = function() { return this.locals.increment(); - } + }; - get(name) { + LocalLayer.prototype.get = function(name) { if (this.registered[name] != null) { return this.registered[name]; } else { return null; } - } + }; + + return LocalLayer; -}; +})(); diff --git a/static/js/languages/microscript/v2/parser.js b/static/js/languages/microscript/v2/parser.js index c9696477..0b5936b5 100644 --- a/static/js/languages/microscript/v2/parser.js +++ b/static/js/languages/microscript/v2/parser.js @@ -1,812 +1,813 @@ this.Parser = (function() { - class Parser { - constructor(input, filename = "") { - this.input = input; - this.filename = filename; - if (/^\s*\/\/\s*javascript\s*\n/.test(this.input)) { - this.input = 'system.javascript("""\n\n' + this.input.replace(/\\/g, "\\\\") + '\n\n""")'; - } - this.tokenizer = new Tokenizer(this.input, this.filename); - this.program = new Program(); - this.current_block = []; - this.current = { - line: 1, - column: 1 - }; - this.verbose = false; - this.nesting = 0; - this.object_nesting = 0; - this.not_terminated = []; - this.api_reserved = { - screen: true, - audio: true, - keyboard: true, - gamepad: true, - sprites: true, - sounds: true, - music: true, - assets: true, - asset_manager: true, - maps: true, - touch: true, - mouse: true, - fonts: true, - Sound: true, - Image: true, - Sprite: true, - Map: true, - system: true, - storage: true, - print: true, - random: true, - Function: true, - List: true, - Object: true, - String: true, - Number: true - }; - } - - nextToken() { - var token; - token = this.tokenizer.next(); - if (token == null) { - this.unexpected_eof = true; - throw "Unexpected end of file"; - } - return this.current = token; + function Parser(input, filename) { + this.input = input; + this.filename = filename != null ? filename : ""; + if (/^\s*\/\/\s*javascript\s*\n/.test(this.input)) { + this.input = 'system.javascript("""\n\n' + this.input.replace(/\\/g, "\\\\") + '\n\n""")'; + } + this.tokenizer = new Tokenizer(this.input, this.filename); + this.program = new Program(); + this.current_block = []; + this.current = { + line: 1, + column: 1 + }; + this.verbose = false; + this.nesting = 0; + this.object_nesting = 0; + this.not_terminated = []; + this.api_reserved = { + screen: true, + audio: true, + keyboard: true, + gamepad: true, + sprites: true, + sounds: true, + music: true, + assets: true, + asset_manager: true, + maps: true, + touch: true, + mouse: true, + fonts: true, + Sound: true, + Image: true, + Sprite: true, + Map: true, + system: true, + storage: true, + print: true, + random: true, + Function: true, + List: true, + Object: true, + String: true, + Number: true + }; + } + + Parser.prototype.nextToken = function() { + var token; + token = this.tokenizer.next(); + if (token == null) { + this.unexpected_eof = true; + throw "Unexpected end of file"; + } + return this.current = token; + }; + + Parser.prototype.nextTokenOptional = function() { + var token; + token = this.tokenizer.next(); + if (token != null) { + this.current = token; } + return token; + }; - nextTokenOptional() { - var token; - token = this.tokenizer.next(); - if (token != null) { - this.current = token; - } - return token; - } - - parse() { - var err, expression, nt, token; - try { - this.warnings = []; - while (true) { - expression = this.parseLine(); - if ((expression == null) && !this.tokenizer.finished()) { - token = this.tokenizer.next(); - if ((token != null) && token.reserved_keyword) { - if (token.value === "end") { - this.error("Too many 'end'"); - } else { - this.error(`Misuse of reserved keyword: '${token.value}'`); - } + Parser.prototype.parse = function() { + var err, expression, nt, token; + try { + this.warnings = []; + while (true) { + expression = this.parseLine(); + if ((expression == null) && !this.tokenizer.finished()) { + token = this.tokenizer.next(); + if ((token != null) && token.reserved_keyword) { + if (token.value === "end") { + this.error("Too many 'end'"); } else { - this.error("Unexpected data"); + this.error("Misuse of reserved keyword: '" + token.value + "'"); } - } - if (expression === null) { - break; - } - this.current_block.push(expression); - this.program.add(expression); - if (this.verbose) { - console.info(expression); + } else { + this.error("Unexpected data"); } } - return this; - } catch (error1) { - err = error1; - //console.info "Error at line: #{@current.line} column: #{@current.column}" - if (this.not_terminated.length > 0 && err === "Unexpected end of file") { - nt = this.not_terminated[this.not_terminated.length - 1]; - return this.error_info = { - error: `Unterminated '${nt.value}' ; no matching 'end' found`, - line: nt.line, - column: nt.column - }; - } else { - return this.error_info = { - error: err, - line: this.current.line, - column: this.current.column - }; + if (expression === null) { + break; + } + this.current_block.push(expression); + this.program.add(expression); + if (this.verbose) { + console.info(expression); } } + return this; + } catch (error1) { + err = error1; + if (this.not_terminated.length > 0 && err === "Unexpected end of file") { + nt = this.not_terminated[this.not_terminated.length - 1]; + return this.error_info = { + error: "Unterminated '" + nt.value + "' ; no matching 'end' found", + line: nt.line, + column: nt.column + }; + } else { + return this.error_info = { + error: err, + line: this.current.line, + column: this.current.column + }; + } } + }; - //console.error err - parseLine() { - var token; - token = this.nextTokenOptional(); - if (token == null) { - return null; + Parser.prototype.parseLine = function() { + var token; + token = this.nextTokenOptional(); + if (token == null) { + return null; + } + switch (token.type) { + case Token.TYPE_RETURN: + return new Program.Return(token, this.parseExpression()); + case Token.TYPE_BREAK: + return new Program.Break(token); + case Token.TYPE_CONTINUE: + return new Program.Continue(token); + case Token.TYPE_LOCAL: + return this.parseLocalAssignment(token); + default: + this.tokenizer.pushBack(token); + return this.parseExpression(); + } + }; + + Parser.prototype.parseExpression = function(filter, first_function_call) { + var access, expression; + if (first_function_call == null) { + first_function_call = false; + } + expression = this.parseExpressionStart(); + if (expression == null) { + return null; + } + while (true) { + access = this.parseExpressionSuffix(expression, filter); + if (access == null) { + return expression; } - switch (token.type) { - case Token.TYPE_RETURN: - return new Program.Return(token, this.parseExpression()); - case Token.TYPE_BREAK: - return new Program.Break(token); - case Token.TYPE_CONTINUE: - return new Program.Continue(token); - case Token.TYPE_LOCAL: - return this.parseLocalAssignment(token); - default: - this.tokenizer.pushBack(token); - return this.parseExpression(); + if (first_function_call && access instanceof Program.FunctionCall) { + return access; } + expression = access; } + }; - parseExpression(filter, first_function_call = false) { - var access, expression; - expression = this.parseExpressionStart(); - if (expression == null) { - return null; - } - while (true) { - access = this.parseExpressionSuffix(expression, filter); - if (access == null) { + Parser.prototype.assertExpression = function(filter, first_function_call) { + var exp; + if (first_function_call == null) { + first_function_call = false; + } + exp = this.parseExpression(filter, first_function_call); + if (exp == null) { + throw "Expression expected"; + } + return exp; + }; + + Parser.prototype.parseExpressionSuffix = function(expression, filter) { + var field, identifier, token; + token = this.nextTokenOptional(); + if (token == null) { + return (filter === "self" ? expression : null); + } + switch (token.type) { + case Token.TYPE_DOT: + if (expression instanceof Program.Value && expression.type === Program.Value.TYPE_NUMBER) { + this.tokenizer.pushBack(token); + return null; + } else { + this.tokenizer.changeNumberToIdentifier(); + identifier = this.assertBroadIdentifier("Expected identifier"); + return Program.CreateFieldAccess(token, expression, new Program.Value(identifier, Program.Value.TYPE_STRING, identifier.value)); + } + break; + case Token.TYPE_OPEN_BRACKET: + field = this.assertExpression(); + this.assert(Token.TYPE_CLOSED_BRACKET, "Expected ']'"); + return Program.CreateFieldAccess(token, expression, field); + case Token.TYPE_OPEN_BRACE: + return this.parseFunctionCall(token, expression); + case Token.TYPE_EQUALS: + return this.parseAssignment(token, expression); + case Token.TYPE_PLUS_EQUALS: + return this.parseSelfAssignment(token, expression, token.type); + case Token.TYPE_MINUS_EQUALS: + return this.parseSelfAssignment(token, expression, token.type); + case Token.TYPE_MULTIPLY_EQUALS: + return this.parseSelfAssignment(token, expression, token.type); + case Token.TYPE_DIVIDE_EQUALS: + return this.parseSelfAssignment(token, expression, token.type); + case Token.TYPE_MODULO_EQUALS: + case Token.TYPE_AND_EQUALS: + case Token.TYPE_OR_EQUALS: + return this.parseSelfAssignment(token, expression, token.type); + default: + if (filter === "self") { + this.tokenizer.pushBack(token); return expression; + } else if (token.is_binary_operator && filter !== "noop") { + return this.parseBinaryOperation(token, expression); + } else { + this.tokenizer.pushBack(token); + return null; } - if (first_function_call && access instanceof Program.FunctionCall) { - return access; + } + }; + + Parser.prototype.parseExpressionStart = function() { + var next, token; + token = this.nextTokenOptional(); + if (token == null) { + return null; + } + switch (token.type) { + case Token.TYPE_IDENTIFIER: + return new Program.Variable(token, token.value); + case Token.TYPE_NUMBER: + return this.parseNumberExpression(token); + case Token.TYPE_PLUS: + return this.assertExpression(); + case Token.TYPE_MINUS: + return this.parseExpressionSuffix(new Program.Negate(token, this.assertExpression("noop")), "self"); + case Token.TYPE_NOT: + return this.parseExpressionSuffix(new Program.Not(token, this.assertExpression("noop")), "self"); + case Token.TYPE_STRING: + return this.parseStringExpression(token); + case Token.TYPE_IF: + return this.parseIf(token); + case Token.TYPE_FOR: + return this.parseFor(token); + case Token.TYPE_WHILE: + return this.parseWhile(token); + case Token.TYPE_OPEN_BRACE: + return this.parseBracedExpression(token); + case Token.TYPE_OPEN_BRACKET: + return this.parseArray(token); + case Token.TYPE_FUNCTION: + return this.parseFunction(token); + case Token.TYPE_OBJECT: + return this.parseObject(token); + case Token.TYPE_CLASS: + return this.parseClass(token); + case Token.TYPE_NEW: + return this.parseNew(token); + case Token.TYPE_DOT: + next = this.assert(Token.TYPE_NUMBER, "malformed number"); + if (!Number.isInteger(next.value)) { + throw "malformed number"; } - expression = access; - } + return new Program.Value(token, Program.Value.TYPE_NUMBER, Number.parseFloat("." + next.string_value)); + case Token.TYPE_AFTER: + return this.parseAfter(token); + case Token.TYPE_EVERY: + return this.parseEvery(token); + case Token.TYPE_DO: + return this.parseDo(token); + case Token.TYPE_SLEEP: + return this.parseSleep(token); + case Token.TYPE_DELETE: + return this.parseDelete(token); + default: + this.tokenizer.pushBack(token); + return null; } + }; - assertExpression(filter, first_function_call = false) { - var exp; - exp = this.parseExpression(filter, first_function_call); - if (exp == null) { - throw "Expression expected"; - } - return exp; + Parser.prototype.parseNumberExpression = function(number) { + return new Program.Value(number, Program.Value.TYPE_NUMBER, number.value); + }; + + Parser.prototype.parseStringExpression = function(string) { + var token; + token = this.nextTokenOptional(); + if (token == null) { + return new Program.Value(string, Program.Value.TYPE_STRING, string.value); + } else { + this.tokenizer.pushBack(token); + return new Program.Value(string, Program.Value.TYPE_STRING, string.value); } + }; - parseExpressionSuffix(expression, filter) { - var field, identifier, token; - token = this.nextTokenOptional(); - if (token == null) { - return (filter === "self" ? expression : null); - } - switch (token.type) { - case Token.TYPE_DOT: - if (expression instanceof Program.Value && expression.type === Program.Value.TYPE_NUMBER) { - this.tokenizer.pushBack(token); - return null; - } else { - this.tokenizer.changeNumberToIdentifier(); - identifier = this.assertBroadIdentifier("Expected identifier"); - return Program.CreateFieldAccess(token, expression, new Program.Value(identifier, Program.Value.TYPE_STRING, identifier.value)); - } - break; - case Token.TYPE_OPEN_BRACKET: - field = this.assertExpression(); - this.assert(Token.TYPE_CLOSED_BRACKET, "Expected ']'"); - return Program.CreateFieldAccess(token, expression, field); - case Token.TYPE_OPEN_BRACE: - return this.parseFunctionCall(token, expression); - case Token.TYPE_EQUALS: - return this.parseAssignment(token, expression); - case Token.TYPE_PLUS_EQUALS: - return this.parseSelfAssignment(token, expression, token.type); - case Token.TYPE_MINUS_EQUALS: - return this.parseSelfAssignment(token, expression, token.type); - case Token.TYPE_MULTIPLY_EQUALS: - return this.parseSelfAssignment(token, expression, token.type); - case Token.TYPE_DIVIDE_EQUALS: - return this.parseSelfAssignment(token, expression, token.type); - case Token.TYPE_MODULO_EQUALS: - case Token.TYPE_AND_EQUALS: - case Token.TYPE_OR_EQUALS: - return this.parseSelfAssignment(token, expression, token.type); - default: - if (filter === "self") { - this.tokenizer.pushBack(token); - return expression; - } else if (token.is_binary_operator && filter !== "noop") { - return this.parseBinaryOperation(token, expression); - } else { - this.tokenizer.pushBack(token); - return null; - } + Parser.prototype.parseArray = function(bracket) { + var res, token; + res = []; + while (true) { + token = this.nextToken(); + if (token.type === Token.TYPE_CLOSED_BRACKET) { + return new Program.Value(bracket, Program.Value.TYPE_ARRAY, res); + } else if (token.type === Token.TYPE_COMMA) { + continue; + } else { + this.tokenizer.pushBack(token); + res.push(this.assertExpression()); } } + }; - parseExpressionStart() { - var next, token; + Parser.prototype.parseBinaryOperation = function(operation, term1) { + var ops, terms, token; + ops = [new Program.Operation(operation, operation.value)]; + terms = [term1]; + terms.push(this.assertExpression("noop")); + while (true) { token = this.nextTokenOptional(); if (token == null) { - return null; + break; } - switch (token.type) { - case Token.TYPE_IDENTIFIER: // variable name - return new Program.Variable(token, token.value); - case Token.TYPE_NUMBER: - return this.parseNumberExpression(token); - case Token.TYPE_PLUS: - return this.assertExpression(); - case Token.TYPE_MINUS: - return this.parseExpressionSuffix(new Program.Negate(token, this.assertExpression("noop")), "self"); - case Token.TYPE_NOT: - return this.parseExpressionSuffix(new Program.Not(token, this.assertExpression("noop")), "self"); - case Token.TYPE_STRING: - return this.parseStringExpression(token); - case Token.TYPE_IF: - return this.parseIf(token); - case Token.TYPE_FOR: - return this.parseFor(token); - case Token.TYPE_WHILE: - return this.parseWhile(token); - case Token.TYPE_OPEN_BRACE: - return this.parseBracedExpression(token); - case Token.TYPE_OPEN_BRACKET: - return this.parseArray(token); - case Token.TYPE_FUNCTION: - return this.parseFunction(token); - case Token.TYPE_OBJECT: - return this.parseObject(token); - case Token.TYPE_CLASS: - return this.parseClass(token); - case Token.TYPE_NEW: - return this.parseNew(token); - case Token.TYPE_DOT: - next = this.assert(Token.TYPE_NUMBER, "malformed number"); - if (!Number.isInteger(next.value)) { - throw "malformed number"; - } - return new Program.Value(token, Program.Value.TYPE_NUMBER, Number.parseFloat(`.${next.string_value}`)); - case Token.TYPE_AFTER: - return this.parseAfter(token); - case Token.TYPE_EVERY: - return this.parseEvery(token); - case Token.TYPE_DO: - return this.parseDo(token); - case Token.TYPE_SLEEP: - return this.parseSleep(token); - case Token.TYPE_DELETE: - return this.parseDelete(token); - default: - this.tokenizer.pushBack(token); - return null; + if (!token.is_binary_operator) { + this.tokenizer.pushBack(token); + break; } + ops.push(new Program.Operation(token, token.value)); + terms.push(this.assertExpression("noop")); } + return Program.BuildOperations(ops, terms); + }; - parseNumberExpression(number) { - return new Program.Value(number, Program.Value.TYPE_NUMBER, number.value); + Parser.prototype.parseAssignment = function(token, expression) { + var res; + if (!(expression instanceof Program.Variable) && !(expression instanceof Program.Field)) { + throw "Expected variable identifier or property"; + } + if (this.object_nesting === 0 && expression instanceof Program.Variable && this.api_reserved[expression.identifier]) { + this.warnings.push({ + type: "assigning_api_variable", + identifier: expression.identifier, + line: token.line, + column: token.column + }); } + if (expression instanceof Program.Field) { + this.object_nesting += 1; + res = new Program.Assignment(token, expression, this.assertExpression()); + this.object_nesting -= 1; + } else { + res = new Program.Assignment(token, expression, this.assertExpression()); + } + return res; + }; + + Parser.prototype.parseSelfAssignment = function(token, expression, operation) { + if (!(expression instanceof Program.Variable) && !(expression instanceof Program.Field)) { + throw "Expected variable identifier or property"; + } + return new Program.SelfAssignment(token, expression, operation, this.assertExpression()); + }; + + Parser.prototype.parseLocalAssignment = function(local) { + var identifier; + identifier = this.assert(Token.TYPE_IDENTIFIER, "Expected identifier"); + this.assert(Token.TYPE_EQUALS, "Expected '='"); + return new Program.Assignment(local, new Program.Variable(identifier, identifier.value), this.assertExpression(), true); + }; - parseStringExpression(string) { - var token; + Parser.prototype.parseBracedExpression = function(open) { + var expression, token; + expression = this.assertExpression(); + token = this.nextToken(); + if (token.type === Token.TYPE_CLOSED_BRACE) { + return new Program.Braced(open, expression); + } else { + return this.error("missing closing parenthese"); + } + }; + + Parser.prototype.parseFunctionCall = function(brace_token, expression) { + var args, start, token; + args = []; + this.last_function_call = new Program.FunctionCall(brace_token, expression, args); + this.last_function_call.argslimits = []; + while (true) { token = this.nextTokenOptional(); if (token == null) { - return new Program.Value(string, Program.Value.TYPE_STRING, string.value); + return this.error("missing closing parenthese"); + } else if (token.type === Token.TYPE_CLOSED_BRACE) { + return new Program.FunctionCall(token, expression, args); + } else if (token.type === Token.TYPE_COMMA) { + continue; } else { this.tokenizer.pushBack(token); - return new Program.Value(string, Program.Value.TYPE_STRING, string.value); + start = token.start; + args.push(this.assertExpression()); + this.last_function_call.argslimits.push({ + start: start, + end: this.tokenizer.index - 1 + }); } } + }; - parseArray(bracket) { - var res, token; - res = []; - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_CLOSED_BRACKET) { - return new Program.Value(bracket, Program.Value.TYPE_ARRAY, res); - } else if (token.type === Token.TYPE_COMMA) { - continue; - } else { - this.tokenizer.pushBack(token); - res.push(this.assertExpression()); - } - } + Parser.prototype.addTerminable = function(token) { + return this.not_terminated.push(token); + }; + + Parser.prototype.endTerminable = function() { + if (this.not_terminated.length > 0) { + this.not_terminated.splice(this.not_terminated.length - 1, 1); } + }; - parseBinaryOperation(operation, term1) { - var ops, terms, token; - ops = [new Program.Operation(operation, operation.value)]; - terms = [term1]; - terms.push(this.assertExpression("noop")); - while (true) { - token = this.nextTokenOptional(); - if (token == null) { - break; - } - if (!token.is_binary_operator) { - this.tokenizer.pushBack(token); - break; + Parser.prototype.parseFunction = function(funk) { + var args, line, sequence, token; + this.nesting += 1; + this.addTerminable(funk); + args = this.parseFunctionArgs(); + sequence = []; + while (true) { + token = this.nextToken(); + if (token.type === Token.TYPE_END) { + this.nesting -= 1; + this.endTerminable(); + return new Program.Function(funk, args, sequence, token); + } else { + this.tokenizer.pushBack(token); + line = this.parseLine(); + if (line != null) { + sequence.push(line); + } else { + this.error("Unexpected data while parsing function"); } - ops.push(new Program.Operation(token, token.value)); - terms.push(this.assertExpression("noop")); } - return Program.BuildOperations(ops, terms); } + }; - parseAssignment(token, expression) { - var res; - if (!(expression instanceof Program.Variable) && !(expression instanceof Program.Field)) { - throw "Expected variable identifier or property"; - } - if (this.object_nesting === 0 && expression instanceof Program.Variable && this.api_reserved[expression.identifier]) { - this.warnings.push({ - type: "assigning_api_variable", - identifier: expression.identifier, - line: token.line, - column: token.column + Parser.prototype.parseFunctionArgs = function() { + var args, exp, last, token; + token = this.nextToken(); + args = []; + last = null; + if (token.type !== Token.TYPE_OPEN_BRACE) { + return this.error("Expected opening parenthese"); + } + while (true) { + token = this.nextToken(); + if (token.type === Token.TYPE_CLOSED_BRACE) { + return args; + } else if (token.type === Token.TYPE_COMMA) { + last = null; + continue; + } else if (token.type === Token.TYPE_EQUALS && last === "argument") { + exp = this.assertExpression(); + args[args.length - 1]["default"] = exp; + } else if (token.type === Token.TYPE_IDENTIFIER) { + last = "argument"; + args.push({ + name: token.value }); - } - if (expression instanceof Program.Field) { - this.object_nesting += 1; - res = new Program.Assignment(token, expression, this.assertExpression()); - this.object_nesting -= 1; } else { - res = new Program.Assignment(token, expression, this.assertExpression()); - } - return res; - } - - parseSelfAssignment(token, expression, operation) { - if (!(expression instanceof Program.Variable) && !(expression instanceof Program.Field)) { - throw "Expected variable identifier or property"; + return this.error("Unexpected token"); } - return new Program.SelfAssignment(token, expression, operation, this.assertExpression()); } + }; - parseLocalAssignment(local) { - var identifier; - identifier = this.assert(Token.TYPE_IDENTIFIER, "Expected identifier"); - this.assert(Token.TYPE_EQUALS, "Expected '='"); - return new Program.Assignment(local, new Program.Variable(identifier, identifier.value), this.assertExpression(), true); + Parser.prototype.warningAssignmentCondition = function(expression) { + if (expression instanceof Program.Assignment) { + return this.warnings.push({ + type: "assignment_as_condition", + line: expression.token.line, + column: expression.token.column + }); } + }; - parseBracedExpression(open) { - var expression, token; - expression = this.assertExpression(); + Parser.prototype.parseIf = function(iftoken) { + var chain, current, line, token; + this.addTerminable(iftoken); + current = { + condition: this.assertExpression(), + sequence: [] + }; + this.warningAssignmentCondition(current.condition); + chain = []; + token = this.nextToken(); + if (token.type !== Token.TYPE_THEN) { + return this.error("Expected 'then'"); + } + while (true) { token = this.nextToken(); - if (token.type === Token.TYPE_CLOSED_BRACE) { - return new Program.Braced(open, expression); + if (token.type === Token.TYPE_ELSIF) { + chain.push(current); + current = { + condition: this.assertExpression(), + sequence: [] + }; + this.warningAssignmentCondition(current.condition); + this.assert(Token.TYPE_THEN, "Expected 'then'"); + } else if (token.type === Token.TYPE_ELSE) { + current["else"] = []; + } else if (token.type === Token.TYPE_END) { + chain.push(current); + this.endTerminable(); + return new Program.Condition(iftoken, chain); } else { - return this.error("missing closing parenthese"); - } - } - - parseFunctionCall(brace_token, expression) { - var args, start, token; - args = []; - this.last_function_call = new Program.FunctionCall(brace_token, expression, args); - this.last_function_call.argslimits = []; - while (true) { - token = this.nextTokenOptional(); - if (token == null) { - return this.error("missing closing parenthese"); - } else if (token.type === Token.TYPE_CLOSED_BRACE) { - return new Program.FunctionCall(token, expression, args); - } else if (token.type === Token.TYPE_COMMA) { - continue; + this.tokenizer.pushBack(token); + line = this.parseLine(); + if (line == null) { + throw Error("Unexpected data while parsing if"); + } + if (current["else"] != null) { + current["else"].push(line); } else { - this.tokenizer.pushBack(token); - start = token.start; - args.push(this.assertExpression()); - this.last_function_call.argslimits.push({ - start: start, - end: this.tokenizer.index - 1 - }); + current.sequence.push(line); } } } + }; - addTerminable(token) { - return this.not_terminated.push(token); + Parser.prototype.assert = function(type, error) { + var token; + token = this.nextToken(); + if (token.type !== type) { + throw error; } + return token; + }; - endTerminable() { - if (this.not_terminated.length > 0) { - this.not_terminated.splice(this.not_terminated.length - 1, 1); - } + Parser.prototype.assertBroadIdentifier = function(error) { + var token; + token = this.nextToken(); + if (token.type !== Token.TYPE_IDENTIFIER && token.reserved_keyword) { + token.type = Token.TYPE_IDENTIFIER; } - - parseFunction(funk) { - var args, line, sequence, token; - this.nesting += 1; - this.addTerminable(funk); - args = this.parseFunctionArgs(); - sequence = []; - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_END) { - this.nesting -= 1; - this.endTerminable(); - return new Program.Function(funk, args, sequence, token); - } else { - this.tokenizer.pushBack(token); - line = this.parseLine(); - if (line != null) { - sequence.push(line); - } else { - this.error("Unexpected data while parsing function"); - } - } - } + if (token.type !== Token.TYPE_IDENTIFIER) { + throw error; } + return token; + }; - parseFunctionArgs() { - var args, exp, last, token; + Parser.prototype.error = function(text) { + throw text; + }; + + Parser.prototype.parseFor = function(fortoken) { + var iterator, list, range_by, range_from, range_to, token; + iterator = this.assertExpression(); + if (iterator instanceof Program.Assignment) { + range_from = iterator.expression; + iterator = iterator.field; token = this.nextToken(); - args = []; - last = null; - if (token.type !== Token.TYPE_OPEN_BRACE) { - return this.error("Expected opening parenthese"); + if (token.type !== Token.TYPE_TO) { + return this.error("Expected 'to'"); } - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_CLOSED_BRACE) { - return args; - } else if (token.type === Token.TYPE_COMMA) { - last = null; - continue; - } else if (token.type === Token.TYPE_EQUALS && last === "argument") { - exp = this.assertExpression(); - args[args.length - 1].default = exp; - } else if (token.type === Token.TYPE_IDENTIFIER) { - last = "argument"; - args.push({ - name: token.value - }); - } else { - return this.error("Unexpected token"); - } + range_to = this.assertExpression(); + token = this.nextToken(); + if (token.type === Token.TYPE_BY) { + range_by = this.assertExpression(); + } else { + range_by = 0; + this.tokenizer.pushBack(token); } + return new Program.For(fortoken, iterator.identifier, range_from, range_to, range_by, this.parseSequence(fortoken)); + } else if (iterator instanceof Program.Variable) { + this.assert(Token.TYPE_IN, "Error expected keyword 'in'"); + list = this.assertExpression(); + return new Program.ForIn(fortoken, iterator.identifier, list, this.parseSequence(fortoken)); + } else { + return this.error("Malformed for loop"); } + }; - warningAssignmentCondition(expression) { - if (expression instanceof Program.Assignment) { - return this.warnings.push({ - type: "assignment_as_condition", - line: expression.token.line, - column: expression.token.column - }); - } - } + Parser.prototype.parseWhile = function(whiletoken) { + var condition; + condition = this.assertExpression(); + return new Program.While(whiletoken, condition, this.parseSequence(whiletoken)); + }; - parseIf(iftoken) { - var chain, current, line, token; - this.addTerminable(iftoken); - current = { - condition: this.assertExpression(), - sequence: [] - }; - this.warningAssignmentCondition(current.condition); - chain = []; + Parser.prototype.parseSequence = function(start_token) { + var line, sequence, token; + if (start_token != null) { + this.addTerminable(start_token); + } + this.nesting += 1; + sequence = []; + while (true) { token = this.nextToken(); - if (token.type !== Token.TYPE_THEN) { - return this.error("Expected 'then'"); - } - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_ELSIF) { - chain.push(current); - current = { - condition: this.assertExpression(), - sequence: [] - }; - this.warningAssignmentCondition(current.condition); - this.assert(Token.TYPE_THEN, "Expected 'then'"); - } else if (token.type === Token.TYPE_ELSE) { - current.else = []; - } else if (token.type === Token.TYPE_END) { - chain.push(current); + if (token.type === Token.TYPE_END) { + if (start_token != null) { this.endTerminable(); - return new Program.Condition(iftoken, chain); - } else { - this.tokenizer.pushBack(token); - line = this.parseLine(); - if (line == null) { - throw Error("Unexpected data while parsing if"); - } - if (current.else != null) { - current.else.push(line); - } else { - current.sequence.push(line); - } } + this.nesting -= 1; + return sequence; + } else { + this.tokenizer.pushBack(token); + line = this.parseLine(); + if (line == null) { + this.error("Unexpected data"); + } + sequence.push(line); } } + return sequence; + }; - assert(type, error) { - var token; - token = this.nextToken(); - if (token.type !== type) { - throw error; - } - return token; - } - - assertBroadIdentifier(error) { - var token; + Parser.prototype.parseObject = function(object) { + var exp, fields, token; + this.nesting += 1; + this.object_nesting += 1; + this.addTerminable(object); + fields = []; + while (true) { token = this.nextToken(); - if (token.type !== Token.TYPE_IDENTIFIER && token.reserved_keyword) { - token.type = Token.TYPE_IDENTIFIER; - } - if (token.type !== Token.TYPE_IDENTIFIER) { - throw error; - } - return token; - } - - error(text) { - throw text; - } - - parseFor(fortoken) { - var iterator, list, range_by, range_from, range_to, token; - iterator = this.assertExpression(); - if (iterator instanceof Program.Assignment) { - range_from = iterator.expression; - iterator = iterator.field; - token = this.nextToken(); - if (token.type !== Token.TYPE_TO) { - return this.error("Expected 'to'"); + if (token.type === Token.TYPE_END) { + this.nesting -= 1; + this.object_nesting -= 1; + this.endTerminable(); + return new Program.CreateObject(object, fields); + } else { + if (token.type !== Token.TYPE_IDENTIFIER && token.reserved_keyword) { + token.type = Token.TYPE_IDENTIFIER; } - range_to = this.assertExpression(); - token = this.nextToken(); - if (token.type === Token.TYPE_BY) { - range_by = this.assertExpression(); + if (token.type === Token.TYPE_STRING) { + token.type = Token.TYPE_IDENTIFIER; + } + if (token.type === Token.TYPE_IDENTIFIER) { + this.assert(Token.TYPE_EQUALS, "Expected '='"); + exp = this.assertExpression(); + fields.push({ + field: token.value, + value: exp + }); } else { - range_by = 0; - this.tokenizer.pushBack(token); + return this.error("Malformed object"); } - return new Program.For(fortoken, iterator.identifier, range_from, range_to, range_by, this.parseSequence(fortoken)); - } else if (iterator instanceof Program.Variable) { - this.assert(Token.TYPE_IN, "Error expected keyword 'in'"); - list = this.assertExpression(); - return new Program.ForIn(fortoken, iterator.identifier, list, this.parseSequence(fortoken)); - } else { - return this.error("Malformed for loop"); } } + }; - parseWhile(whiletoken) { - var condition; - condition = this.assertExpression(); - return new Program.While(whiletoken, condition, this.parseSequence(whiletoken)); + Parser.prototype.parseClass = function(object) { + var exp, ext, fields, token; + this.nesting += 1; + this.object_nesting += 1; + this.addTerminable(object); + fields = []; + token = this.nextToken(); + if (token.type === Token.TYPE_EXTENDS) { + ext = this.assertExpression(); + token = this.nextToken(); } - - parseSequence(start_token) { - var line, sequence, token; - if (start_token != null) { - this.addTerminable(start_token); - } - this.nesting += 1; - sequence = []; - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_END) { - if (start_token != null) { - this.endTerminable(); - } - this.nesting -= 1; - return sequence; - } else { - this.tokenizer.pushBack(token); - line = this.parseLine(); - if (line == null) { - this.error("Unexpected data"); - } - sequence.push(line); + while (true) { + if (token.type === Token.TYPE_END) { + this.nesting -= 1; + this.object_nesting -= 1; + this.endTerminable(); + return new Program.CreateClass(object, ext, fields); + } else { + if (token.type !== Token.TYPE_IDENTIFIER && token.reserved_keyword) { + token.type = Token.TYPE_IDENTIFIER; } - } - return sequence; - } - - parseObject(object) { - var exp, fields, token; - this.nesting += 1; - this.object_nesting += 1; - this.addTerminable(object); - fields = []; - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_END) { - this.nesting -= 1; - this.object_nesting -= 1; - this.endTerminable(); - return new Program.CreateObject(object, fields); + if (token.type === Token.TYPE_STRING) { + token.type = Token.TYPE_IDENTIFIER; + } + if (token.type === Token.TYPE_IDENTIFIER) { + this.assert(Token.TYPE_EQUALS, "Expected '='"); + exp = this.assertExpression(); + fields.push({ + field: token.value, + value: exp + }); } else { - if (token.type !== Token.TYPE_IDENTIFIER && token.reserved_keyword) { - token.type = Token.TYPE_IDENTIFIER; - } - if (token.type === Token.TYPE_STRING) { - token.type = Token.TYPE_IDENTIFIER; - } - if (token.type === Token.TYPE_IDENTIFIER) { - this.assert(Token.TYPE_EQUALS, "Expected '='"); - exp = this.assertExpression(); - fields.push({ - field: token.value, - value: exp - }); - } else { - return this.error("Malformed object"); - } + return this.error("Malformed object"); } } + token = this.nextToken(); } + }; - parseClass(object) { - var exp, ext, fields, token; - this.nesting += 1; - this.object_nesting += 1; - this.addTerminable(object); - fields = []; + Parser.prototype.parseNew = function(token) { + var exp; + exp = this.assertExpression(null, true); + return new Program.NewCall(token, exp); + }; + + Parser.prototype.multipliers = { + millisecond: 1, + milliseconds: 1, + second: 1000, + seconds: 1000, + minute: 60000, + minutes: 60000, + hour: 60000 * 60, + hours: 60000 * 60, + day: 60000 * 60 * 24, + days: 60000 * 60 * 24 + }; + + Parser.prototype.parseAfter = function(after) { + var delay, line, multiplier, sequence, token; + this.nesting += 1; + this.addTerminable(after); + delay = this.assertExpression(); + token = this.nextToken(); + multiplier = null; + if (token.type === Token.TYPE_IDENTIFIER && this.multipliers[token.value]) { + multiplier = this.multipliers[token.value]; token = this.nextToken(); - if (token.type === Token.TYPE_EXTENDS) { - ext = this.assertExpression(); - token = this.nextToken(); - } - while (true) { - if (token.type === Token.TYPE_END) { - this.nesting -= 1; - this.object_nesting -= 1; - this.endTerminable(); - return new Program.CreateClass(object, ext, fields); - } else { - if (token.type !== Token.TYPE_IDENTIFIER && token.reserved_keyword) { - token.type = Token.TYPE_IDENTIFIER; - } - if (token.type === Token.TYPE_STRING) { - token.type = Token.TYPE_IDENTIFIER; - } - if (token.type === Token.TYPE_IDENTIFIER) { - this.assert(Token.TYPE_EQUALS, "Expected '='"); - exp = this.assertExpression(); - fields.push({ - field: token.value, - value: exp - }); - } else { - return this.error("Malformed object"); - } - } - token = this.nextToken(); - } } - - parseNew(token) { - var exp; - exp = this.assertExpression(null, true); - return new Program.NewCall(token, exp); + if ((token == null) || token.type !== Token.TYPE_DO) { + this.error("Expected keyword 'do'"); } - - parseAfter(after) { - var delay, line, multiplier, sequence, token; - this.nesting += 1; - this.addTerminable(after); - delay = this.assertExpression(); + sequence = []; + while (true) { token = this.nextToken(); - multiplier = null; - if (token.type === Token.TYPE_IDENTIFIER && this.multipliers[token.value]) { - multiplier = this.multipliers[token.value]; - token = this.nextToken(); - } - if ((token == null) || token.type !== Token.TYPE_DO) { - this.error("Expected keyword 'do'"); - } - sequence = []; - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_END) { - this.nesting -= 1; - this.endTerminable(); - return new Program.After(after, delay, sequence, token, multiplier); + if (token.type === Token.TYPE_END) { + this.nesting -= 1; + this.endTerminable(); + return new Program.After(after, delay, sequence, token, multiplier); + } else { + this.tokenizer.pushBack(token); + line = this.parseLine(); + if (line != null) { + sequence.push(line); } else { - this.tokenizer.pushBack(token); - line = this.parseLine(); - if (line != null) { - sequence.push(line); - } else { - this.error("Unexpected data while parsing after"); - } + this.error("Unexpected data while parsing after"); } } } + }; - parseEvery(every) { - var delay, line, multiplier, sequence, token; - this.nesting += 1; - this.addTerminable(every); - delay = this.assertExpression(); + Parser.prototype.parseEvery = function(every) { + var delay, line, multiplier, sequence, token; + this.nesting += 1; + this.addTerminable(every); + delay = this.assertExpression(); + token = this.nextToken(); + multiplier = null; + if (token.type === Token.TYPE_IDENTIFIER && this.multipliers[token.value]) { + multiplier = this.multipliers[token.value]; token = this.nextToken(); - multiplier = null; - if (token.type === Token.TYPE_IDENTIFIER && this.multipliers[token.value]) { - multiplier = this.multipliers[token.value]; - token = this.nextToken(); - } - if ((token == null) || token.type !== Token.TYPE_DO) { - this.error("Expected keyword 'do'"); - } - sequence = []; - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_END) { - this.nesting -= 1; - this.endTerminable(); - return new Program.Every(every, delay, sequence, token, multiplier); - } else { - this.tokenizer.pushBack(token); - line = this.parseLine(); - if (line != null) { - sequence.push(line); - } else { - this.error("Unexpected data while parsing after"); - } - } - } } - - parseDo(do_token) { - var line, sequence, token; - this.nesting += 1; - this.addTerminable(do_token); - sequence = []; - while (true) { - token = this.nextToken(); - if (token.type === Token.TYPE_END) { - this.nesting -= 1; - this.endTerminable(); - return new Program.Do(do_token, sequence, token); + if ((token == null) || token.type !== Token.TYPE_DO) { + this.error("Expected keyword 'do'"); + } + sequence = []; + while (true) { + token = this.nextToken(); + if (token.type === Token.TYPE_END) { + this.nesting -= 1; + this.endTerminable(); + return new Program.Every(every, delay, sequence, token, multiplier); + } else { + this.tokenizer.pushBack(token); + line = this.parseLine(); + if (line != null) { + sequence.push(line); } else { - this.tokenizer.pushBack(token); - line = this.parseLine(); - if (line != null) { - sequence.push(line); - } else { - this.error("Unexpected data while parsing after"); - } + this.error("Unexpected data while parsing after"); } } } + }; - parseSleep(sleep) { - var delay, multiplier, token; - delay = this.assertExpression(); + Parser.prototype.parseDo = function(do_token) { + var line, sequence, token; + this.nesting += 1; + this.addTerminable(do_token); + sequence = []; + while (true) { token = this.nextToken(); - multiplier = null; - if (token != null) { - if (token.type === Token.TYPE_IDENTIFIER && this.multipliers[token.value]) { - multiplier = this.multipliers[token.value]; + if (token.type === Token.TYPE_END) { + this.nesting -= 1; + this.endTerminable(); + return new Program.Do(do_token, sequence, token); + } else { + this.tokenizer.pushBack(token); + line = this.parseLine(); + if (line != null) { + sequence.push(line); } else { - this.tokenizer.pushBack(token); + this.error("Unexpected data while parsing after"); } } - return new Program.Sleep(sleep, delay, multiplier); } + }; - parseDelete(del) { - var v; - v = this.parseExpression(); - if ((v == null) || (!(v instanceof Program.Variable) && !(v instanceof Program.Field))) { - return this.error("expecting variable name or property access after keyword `delete`"); + Parser.prototype.parseSleep = function(sleep) { + var delay, multiplier, token; + delay = this.assertExpression(); + token = this.nextToken(); + multiplier = null; + if (token != null) { + if (token.type === Token.TYPE_IDENTIFIER && this.multipliers[token.value]) { + multiplier = this.multipliers[token.value]; } else { - return new Program.Delete(del, v); + this.tokenizer.pushBack(token); } } - + return new Program.Sleep(sleep, delay, multiplier); }; - Parser.prototype.multipliers = { - millisecond: 1, - milliseconds: 1, - second: 1000, - seconds: 1000, - minute: 60000, - minutes: 60000, - hour: 60000 * 60, - hours: 60000 * 60, - day: 60000 * 60 * 24, - days: 60000 * 60 * 24 + Parser.prototype.parseDelete = function(del) { + var v; + v = this.parseExpression(); + if ((v == null) || (!(v instanceof Program.Variable) && !(v instanceof Program.Field))) { + return this.error("expecting variable name or property access after keyword `delete`"); + } else { + return new Program.Delete(del, v); + } }; return Parser; -}).call(this); +})(); diff --git a/static/js/languages/microscript/v2/processor.coffee b/static/js/languages/microscript/v2/processor.coffee index 92c048da..bc5c7550 100644 --- a/static/js/languages/microscript/v2/processor.coffee +++ b/static/js/languages/microscript/v2/processor.coffee @@ -47,7 +47,7 @@ class @Processor proc.stack[++proc.stack_index] = arguments.length if routine.uses_arguments - a = [...arguments] + a = structuredClone(arguments) for i in [0..a.length-1] by 1 if not a[i]? a[i] = 0 @@ -73,7 +73,7 @@ class @Processor proc.stack[++proc.stack_index] = arguments.length if routine.uses_arguments - a = [...arguments] + a = structuredClone(arguments) for i in [0..a.length-1] by 1 if not a[i]? a[i] = 0 diff --git a/static/js/languages/microscript/v2/processor.js b/static/js/languages/microscript/v2/processor.js index 553daf44..0c38a6e3 100644 --- a/static/js/languages/microscript/v2/processor.js +++ b/static/js/languages/microscript/v2/processor.js @@ -1,5 +1,5 @@ -this.Processor = class Processor { - constructor(runner) { +this.Processor = (function() { + function Processor(runner) { this.runner = runner; this.locals = []; this.stack = []; @@ -9,12 +9,12 @@ this.Processor = class Processor { this.done = true; } - load(routine1) { + Processor.prototype.load = function(routine1) { this.routine = routine1; return this.resetState(); - } + }; - resetState() { + Processor.prototype.resetState = function() { this.local_index = 0; this.stack_index = -1; this.op_index = 0; @@ -25,22 +25,22 @@ this.Processor = class Processor { this.call_super = null; this.call_supername = ""; return this.done = false; - } + }; - resolveParentClass(obj, global) { - if ((obj.class != null) && typeof obj.class === "string") { - if (global[obj.class] != null) { - obj.class = global[obj.class]; - return this.resolveParentClass(obj.class, global); + Processor.prototype.resolveParentClass = function(obj, global) { + if ((obj["class"] != null) && typeof obj["class"] === "string") { + if (global[obj["class"]] != null) { + obj["class"] = global[obj["class"]]; + return this.resolveParentClass(obj["class"], global); } - } else if (obj.class != null) { - return this.resolveParentClass(obj.class, global); + } else if (obj["class"] != null) { + return this.resolveParentClass(obj["class"], global); } - } + }; - applyFunction(args) {} + Processor.prototype.applyFunction = function(args) {}; - routineAsFunction(routine, context) { + Processor.prototype.routineAsFunction = function(routine, context) { var f, proc; proc = new Processor(this.runner); f = function() { @@ -52,7 +52,7 @@ this.Processor = class Processor { } proc.stack[++proc.stack_index] = arguments.length; if (routine.uses_arguments) { - a = [...arguments]; + a = structuredClone(arguments); for (i = k = 0, ref1 = a.length - 1; k <= ref1; i = k += 1) { if (a[i] == null) { a[i] = 0; @@ -62,11 +62,10 @@ this.Processor = class Processor { } return proc.run(context); }; - //res = proc.stack[0] return f; - } + }; - routineAsApplicableFunction(routine, context) { + Processor.prototype.routineAsApplicableFunction = function(routine, context) { var f, proc; proc = new Processor(this.runner); f = function() { @@ -79,7 +78,7 @@ this.Processor = class Processor { } proc.stack[++proc.stack_index] = arguments.length; if (routine.uses_arguments) { - a = [...arguments]; + a = structuredClone(arguments); for (i = k = 0, ref1 = a.length - 1; k <= ref1; i = k += 1) { if (a[i] == null) { a[i] = 0; @@ -91,9 +90,9 @@ this.Processor = class Processor { return res = proc.stack[0]; }; return f; - } + }; - argToNative(arg, context) { + Processor.prototype.argToNative = function(arg, context) { if (arg instanceof Routine) { return this.routineAsFunction(arg, context); } else { @@ -103,9 +102,9 @@ this.Processor = class Processor { return 0; } } - } + }; - modulo(context, a, b) { + Processor.prototype.modulo = function(context, a, b) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -124,8 +123,8 @@ this.Processor = class Processor { obj = a; } f = obj["%"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["%"]; } if (f == null) { @@ -140,9 +139,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - add(context, a, b, self) { + Processor.prototype.add = function(context, a, b, self) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -152,8 +151,8 @@ this.Processor = class Processor { obj = a; } f = obj["+"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["+"]; } if (f == null) { @@ -172,9 +171,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - sub(context, a, b, self) { + Processor.prototype.sub = function(context, a, b, self) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -193,8 +192,8 @@ this.Processor = class Processor { obj = a; } f = obj["-"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["-"]; } if (f == null) { @@ -213,9 +212,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - negate(context, a) { + Processor.prototype.negate = function(context, a) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -229,8 +228,8 @@ this.Processor = class Processor { obj = a; } f = obj["-"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["-"]; } if (f == null) { @@ -249,9 +248,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - mul(context, a, b, self) { + Processor.prototype.mul = function(context, a, b, self) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -270,8 +269,8 @@ this.Processor = class Processor { obj = a; } f = obj["*"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["*"]; } if (f == null) { @@ -290,9 +289,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - div(context, a, b, self) { + Processor.prototype.div = function(context, a, b, self) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -311,8 +310,8 @@ this.Processor = class Processor { obj = a; } f = obj["/"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["/"]; } if (f == null) { @@ -331,9 +330,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - band(context, a, b, self) { + Processor.prototype.band = function(context, a, b, self) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -352,8 +351,8 @@ this.Processor = class Processor { obj = a; } f = obj["&"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["&"]; } if (f == null) { @@ -372,9 +371,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - bor(context, a, b, self) { + Processor.prototype.bor = function(context, a, b, self) { var f, obj; if (Array.isArray(a)) { obj = context.global.List; @@ -393,8 +392,8 @@ this.Processor = class Processor { obj = a; } f = obj["|"]; - while ((f == null) && (obj.class != null)) { - obj = obj.class; + while ((f == null) && (obj["class"] != null)) { + obj = obj["class"]; f = obj["|"]; } if (f == null) { @@ -413,9 +412,9 @@ this.Processor = class Processor { } else { return 0; } - } + }; - run(context) { + Processor.prototype.run = function(context) { var a, arg1, args, argv, b, c, call_stack, call_stack_index, call_super, call_supername, con, cs, err, f, fc, field, global, i, i1, i2, id, index, ir, iter, iterator, j, k, key, l, len, length, local_index, locals, locals_offset, loop_by, loop_to, m, n, name, o, obj, object, op_count, op_index, opcodes, p, parent, q, r, rc, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, res, restore_op_index, routine, s, sleep_time, src, stack, stack_index, sup, t, token, u, v, value, w; routine = this.routine; opcodes = this.routine.opcodes; @@ -437,7 +436,7 @@ this.Processor = class Processor { restore_op_index = -1; while (op_index < length) { switch (opcodes[op_index]) { - case 1: // OPCODE_TYPE + case 1: v = stack[stack_index]; switch (typeof v) { case "number": @@ -460,7 +459,7 @@ this.Processor = class Processor { } op_index++; break; - case 2: // OPCODE_TYPE_VARIABLE + case 2: v = object[arg1[op_index]]; if (v == null) { v = global[arg1[op_index]]; @@ -490,7 +489,7 @@ this.Processor = class Processor { } op_index++; break; - case 3: // OPCODE_TYPE_PROPERTY + case 3: v = stack[stack_index - 1][stack[stack_index]]; if (v == null) { stack[--stack_index] = 0; @@ -517,30 +516,30 @@ this.Processor = class Processor { } op_index++; break; - case 4: // OPCODE_LOAD_IMPORT + case 4: stack[++stack_index] = routine.import_values[arg1[op_index++]]; break; - case 5: // OPCODE_LOAD_THIS + case 5: stack[++stack_index] = object; op_index++; break; - case 6: // OPCODE_LOAD_GLOBAL + case 6: stack[++stack_index] = global; op_index++; break; - case 10: // CODE_LOAD_VALUE + case 10: stack[++stack_index] = arg1[op_index++]; break; - case 11: // OPCODE_LOAD_LOCAL + case 11: stack[++stack_index] = locals[locals_offset + arg1[op_index++]]; break; - case 12: // OPCODE_LOAD_VARIABLE + case 12: name = arg1[op_index]; v = object[name]; - if ((v == null) && (object.class != null)) { + if ((v == null) && (object["class"] != null)) { obj = object; - while ((v == null) && (obj.class != null)) { - obj = obj.class; + while ((v == null) && (obj["class"] != null)) { + obj = obj["class"]; v = obj[name]; } } @@ -562,7 +561,7 @@ this.Processor = class Processor { stack[++stack_index] = v != null ? v : 0; op_index++; break; - case 13: // OPCODE_LOAD_LOCAL_OBJECT + case 13: o = locals[locals_offset + arg1[op_index]]; if (typeof o !== "object") { o = locals[locals_offset + arg1[op_index]] = {}; @@ -580,12 +579,12 @@ this.Processor = class Processor { stack[++stack_index] = o; op_index++; break; - case 14: // OPCODE_LOAD_VARIABLE_OBJECT + case 14: name = arg1[op_index]; obj = object; v = obj[name]; - while ((v == null) && (obj.class != null)) { - obj = obj.class; + while ((v == null) && (obj["class"] != null)) { + obj = obj["class"]; v = obj[name]; } if ((v == null) && (global[name] != null)) { @@ -608,22 +607,22 @@ this.Processor = class Processor { stack[++stack_index] = v; op_index++; break; - case 15: // OPCODE_POP + case 15: stack_index--; op_index++; break; - case 16: // OPCODE_LOAD_PROPERTY + case 16: obj = stack[stack_index - 1]; name = stack[stack_index]; v = obj[name]; - while ((v == null) && (obj.class != null)) { - obj = obj.class; + while ((v == null) && (obj["class"] != null)) { + obj = obj["class"]; v = obj[name]; } stack[--stack_index] = v != null ? v : 0; op_index++; break; - case 17: // OPCODE_LOAD_PROPERTY_OBJECT + case 17: v = stack[stack_index - 1][stack[stack_index]]; if (typeof v !== "object") { v = stack[stack_index - 1][stack[stack_index]] = {}; @@ -641,55 +640,54 @@ this.Processor = class Processor { stack[--stack_index] = v; op_index++; break; - case 18: // OPCODE_CREATE_OBJECT + case 18: stack[++stack_index] = {}; op_index++; break; - case 19: // OPCODE_MAKE_OBJECT + case 19: if (typeof stack[stack_index] !== "object") { stack[stack_index] = {}; } op_index++; break; - case 20: // OPCODE_CREATE_ARRAY + case 20: stack[++stack_index] = []; op_index++; break; - case 21: // OPCODE_STORE_LOCAL + case 21: locals[locals_offset + arg1[op_index]] = stack[stack_index]; op_index++; break; - case 22: // OPCODE_STORE_LOCAL_POP + case 22: locals[locals_offset + arg1[op_index]] = stack[stack_index--]; op_index++; break; - case 23: // OPCODE_STORE_VARIABLE + case 23: object[arg1[op_index++]] = stack[stack_index]; break; - case 24: // OPCODE_CREATE_PROPERTY + case 24: obj = stack[stack_index - 2]; field = stack[stack_index - 1]; obj[field] = stack[stack_index]; stack_index -= 2; op_index++; break; - case 25: // OPCODE_STORE_PROPERTY + case 25: obj = stack[stack_index - 2]; field = stack[stack_index - 1]; stack[stack_index - 2] = obj[field] = stack[stack_index]; stack_index -= 2; op_index++; break; - case 26: // OPCODE_DELETE + case 26: obj = stack[stack_index - 1]; field = stack[stack_index]; delete obj[field]; stack[stack_index -= 1] = 0; op_index++; break; - case 27: // OPCODE_UPDATE_CLASS + case 27: name = arg1[op_index]; - // TODO: set classname to variable name if ((object[name] != null) && typeof object[name] === "object") { obj = object[name]; src = stack[stack_index]; @@ -702,18 +700,18 @@ this.Processor = class Processor { } op_index++; break; - case 28: // OPCODE_CREATE_CLASS + case 28: res = {}; parent = stack[stack_index]; if (parent) { - res.class = parent; + res["class"] = parent; } else if (arg1[op_index]) { - res.class = arg1[op_index]; + res["class"] = arg1[op_index]; } stack[stack_index] = res; op_index++; break; - case 29: // OPCODE_NEW_CALL + case 29: c = stack[stack_index]; args = arg1[op_index]; if (typeof c === "function") { @@ -722,17 +720,16 @@ this.Processor = class Processor { a.push(stack[stack_index - args + i]); } stack_index -= args; - // NEW CALL is followed by a POP (to get rid of constructor return value) stack[stack_index - 1] = new c(...a); op_index++; } else { this.resolveParentClass(c, global); res = { - class: c + "class": c }; con = c.constructor; - while (!con && (c.class != null)) { - c = c.class; + while (!con && (c["class"] != null)) { + c = c["class"]; con = c.constructor; } if ((con != null) && con instanceof Routine) { @@ -742,7 +739,7 @@ this.Processor = class Processor { call_stack_index++; cs.routine = routine; cs.object = object; - cs.super = call_super; + cs["super"] = call_super; cs.supername = call_supername; cs.op_index = op_index + 1; locals_offset += routine.locals_size; @@ -775,7 +772,7 @@ this.Processor = class Processor { } } break; - case 30: // OPCODE_ADD + case 30: b = stack[stack_index--]; a = stack[stack_index]; if (typeof a === "number") { @@ -786,7 +783,7 @@ this.Processor = class Processor { } op_index++; break; - case 31: // OPCODE_SUB + case 31: b = stack[stack_index--]; a = stack[stack_index]; if (typeof a === "number") { @@ -797,7 +794,7 @@ this.Processor = class Processor { } op_index++; break; - case 32: // OPCODE_MUL + case 32: b = stack[stack_index--]; a = stack[stack_index]; if (typeof a === "number") { @@ -808,7 +805,7 @@ this.Processor = class Processor { } op_index++; break; - case 33: // OPCODE_DIV + case 33: b = stack[stack_index--]; a = stack[stack_index]; if (typeof a === "number") { @@ -819,7 +816,7 @@ this.Processor = class Processor { } op_index++; break; - case 34: // OPCODE_MODULO + case 34: b = stack[stack_index--]; a = stack[stack_index]; if (typeof a === "number" && typeof b === "number") { @@ -830,7 +827,7 @@ this.Processor = class Processor { } op_index++; break; - case 35: // OPCODE_BINARY_AND + case 35: b = stack[stack_index--]; a = stack[stack_index]; if (typeof a === "number") { @@ -841,7 +838,7 @@ this.Processor = class Processor { } op_index++; break; - case 36: // OPCODE_BINARY_OR + case 36: b = stack[stack_index--]; a = stack[stack_index]; if (typeof a === "number") { @@ -852,17 +849,17 @@ this.Processor = class Processor { } op_index++; break; - case 37: // OPCODE_SHIFT_LEFT + case 37: v = stack[stack_index - 1] << stack[stack_index]; stack[--stack_index] = isFinite(v) ? v : 0; op_index++; break; - case 38: // OPCODE_SHIFT_RIGHT + case 38: v = stack[stack_index - 1] >> stack[stack_index]; stack[--stack_index] = isFinite(v) ? v : 0; op_index++; break; - case 39: // OPCODE_NEGATE + case 39: a = stack[stack_index]; if (typeof a === "number") { stack[stack_index] = -a; @@ -871,58 +868,57 @@ this.Processor = class Processor { } op_index++; break; - case 50: // OPCODE_NOT + case 50: stack[stack_index] = stack[stack_index] ? 0 : 1; op_index++; break; - case 68: // OPCODE_LOAD_PROPERTY_ATOP + case 68: obj = stack[stack_index - 1]; name = stack[stack_index]; v = obj[name]; - while ((v == null) && (obj.class != null)) { - obj = obj.class; + while ((v == null) && (obj["class"] != null)) { + obj = obj["class"]; v = obj[name]; } stack[++stack_index] = v != null ? v : 0; op_index++; break; - case 40: // OPCODE_EQ + case 40: stack[stack_index - 1] = stack[stack_index] === stack[stack_index - 1] ? 1 : 0; stack_index--; op_index++; break; - case 41: // OPCODE_NEQ + case 41: stack[stack_index - 1] = stack[stack_index] !== stack[stack_index - 1] ? 1 : 0; stack_index--; op_index++; break; - case 42: // OPCODE_LT + case 42: stack[stack_index - 1] = stack[stack_index - 1] < stack[stack_index] ? 1 : 0; stack_index--; op_index++; break; - case 43: // OPCODE_GT + case 43: stack[stack_index - 1] = stack[stack_index - 1] > stack[stack_index] ? 1 : 0; stack_index--; op_index++; break; - case 44: // OPCODE_LTE + case 44: stack[stack_index - 1] = stack[stack_index - 1] <= stack[stack_index] ? 1 : 0; stack_index--; op_index++; break; - case 45: // OPCODE_GTE + case 45: stack[stack_index - 1] = stack[stack_index - 1] >= stack[stack_index] ? 1 : 0; stack_index--; op_index++; break; - case 95: // FORLOOP_INIT - // fix loop_by if not set + case 95: iter = arg1[op_index][0]; loop_to = locals[locals_offset + iter + 1] = stack[stack_index - 1]; loop_by = stack[stack_index]; iterator = locals[locals_offset + iter]; - stack[--stack_index] = 0; // unload 2 values and load default value + stack[--stack_index] = 0; if (loop_by === 0) { locals[locals_offset + iter + 2] = loop_to > iterator ? 1 : -1; op_index++; @@ -935,7 +931,7 @@ this.Processor = class Processor { } } break; - case 96: // FORLOOP_CONTROL + case 96: iter = arg1[op_index][0]; loop_by = locals[locals_offset + iter + 2]; loop_to = locals[locals_offset + iter + 1]; @@ -951,13 +947,13 @@ this.Processor = class Processor { op_count = 0; if (Date.now() > this.time_limit) { restore_op_index = op_index; - op_index = length; // stop the loop without adding a condition statement + op_index = length; } } break; - case 97: // FORIN_INIT + case 97: v = stack[stack_index]; - stack[stack_index] = 0; // default result + stack[stack_index] = 0; iterator = arg1[op_index][0]; if (typeof v === "object") { if (Array.isArray(v)) { @@ -974,19 +970,17 @@ this.Processor = class Processor { op_index = arg1[op_index][1]; } else { value = v[0]; - // value could be undefined if the array is sparse locals[locals_offset + arg1[op_index][0]] = value != null ? value : 0; locals[locals_offset + iterator + 2] = 0; op_index++; } break; - case 98: // FORIN_CONTROL + case 98: iterator = arg1[op_index][0]; index = locals[locals_offset + iterator + 2] += 1; v = locals[locals_offset + iterator + 1]; if (index < v.length) { value = v[index]; - // value could be undefined if the array is sparse locals[locals_offset + iterator] = value != null ? value : 0; op_index = arg1[op_index][1]; } else { @@ -996,49 +990,49 @@ this.Processor = class Processor { op_count = 0; if (Date.now() > this.time_limit) { restore_op_index = op_index; - op_index = length; // stop the loop without adding a condition statement + op_index = length; } } break; - case 80: // OPCODE_JUMP + case 80: op_index = arg1[op_index]; if (op_count++ > 100) { op_count = 0; if (Date.now() > this.time_limit) { restore_op_index = op_index; - op_index = length; // stop the loop without adding a condition statement + op_index = length; } } break; - case 81: // OPCODE_JUMPY + case 81: if (stack[stack_index--]) { op_index = arg1[op_index]; } else { op_index++; } break; - case 82: // OPCODE_JUMPN + case 82: if (!stack[stack_index--]) { op_index = arg1[op_index]; } else { op_index++; } break; - case 83: // OPCODE_JUMPY_NOPOP + case 83: if (stack[stack_index]) { op_index = arg1[op_index]; } else { op_index++; } break; - case 84: // OPCODE_JUMPN_NOPOP + case 84: if (!stack[stack_index]) { op_index = arg1[op_index]; } else { op_index++; } break; - case 89: // OPCODE_LOAD_ROUTINE + case 89: r = arg1[op_index++]; rc = r.clone(); ref3 = r.import_refs; @@ -1053,7 +1047,7 @@ this.Processor = class Processor { rc.object = object; stack[++stack_index] = rc; break; - case 90: // OPCODE_FUNCTION_CALL + case 90: args = arg1[op_index]; f = stack[stack_index]; if (f instanceof Routine) { @@ -1062,7 +1056,7 @@ this.Processor = class Processor { call_stack_index++; cs.routine = routine; cs.object = object; - cs.super = call_super; + cs["super"] = call_super; cs.supername = call_supername; cs.op_index = op_index + 1; locals_offset += routine.locals_size; @@ -1146,13 +1140,13 @@ this.Processor = class Processor { op_index++; } break; - case 91: // OPCODE_FUNCTION_APPLY_VARIABLE + case 91: name = stack[stack_index]; sup = obj = object; f = obj[name]; if (f == null) { - while ((f == null) && (sup.class != null)) { - sup = sup.class; + while ((f == null) && (sup["class"] != null)) { + sup = sup["class"]; f = sup[name]; } if (f == null) { @@ -1171,7 +1165,7 @@ this.Processor = class Processor { call_stack_index++; cs.routine = routine; cs.object = object; - cs.super = call_super; + cs["super"] = call_super; cs.supername = call_supername; cs.op_index = op_index + 1; locals_offset += routine.locals_size; @@ -1254,13 +1248,13 @@ this.Processor = class Processor { op_index++; } break; - case 92: // OPCODE_FUNCTION_APPLY_PROPERTY + case 92: obj = stack[stack_index - 1]; sup = obj; name = stack[stack_index]; f = obj[name]; - while ((f == null) && (sup.class != null)) { - sup = sup.class; + while ((f == null) && (sup["class"] != null)) { + sup = sup["class"]; f = sup[name]; } args = arg1[op_index]; @@ -1282,7 +1276,7 @@ this.Processor = class Processor { cs = call_stack[call_stack_index] || (call_stack[call_stack_index] = {}); call_stack_index++; cs.object = object; - cs.super = call_super; + cs["super"] = call_super; cs.supername = call_supername; cs.routine = routine; cs.op_index = op_index + 1; @@ -1367,12 +1361,12 @@ this.Processor = class Processor { op_index++; } break; - case 93: // OPCODE_SUPER_CALL + case 93: if ((call_super != null) && (call_supername != null)) { sup = call_super; f = null; - while ((f == null) && (sup.class != null)) { - sup = sup.class; + while ((f == null) && (sup["class"] != null)) { + sup = sup["class"]; f = sup[call_supername]; } if ((f != null) && f instanceof Routine) { @@ -1380,7 +1374,7 @@ this.Processor = class Processor { cs = call_stack[call_stack_index] || (call_stack[call_stack_index] = {}); call_stack_index++; cs.object = object; - cs.super = call_super; + cs["super"] = call_super; cs.supername = call_supername; cs.routine = routine; cs.op_index = op_index + 1; @@ -1418,14 +1412,14 @@ this.Processor = class Processor { op_index++; } break; - case 94: // OPCODE_RETURN + case 94: local_index -= arg1[op_index]; if (call_stack_index <= 0) { op_index = length; } else { cs = call_stack[--call_stack_index]; object = cs.object; - call_super = cs.super; + call_super = cs["super"]; call_supername = cs.supername; routine = cs.routine; op_index = cs.op_index; @@ -1435,47 +1429,44 @@ this.Processor = class Processor { length = opcodes.length; } break; - case 100: // OPCODE_UNARY_FUNC + case 100: v = arg1[op_index](stack[stack_index]); stack[stack_index] = isFinite(v) ? v : 0; op_index++; break; - case 101: // OPCODE_BINARY_FUNC + case 101: v = arg1[op_index](stack[stack_index - 1], stack[stack_index]); stack[--stack_index] = isFinite(v) ? v : 0; op_index++; break; - case 110: // OPCODE_AFTER + case 110: t = this.runner.createThread(stack[stack_index - 1], stack[stack_index], false); stack[--stack_index] = t; op_index += 1; break; - // add thread to the runner thread list - case 111: // OPCODE_EVERY + case 111: t = this.runner.createThread(stack[stack_index - 1], stack[stack_index], true); stack[--stack_index] = t; op_index += 1; break; - // add thread to the runner thread list - case 112: // OPCODE_DO + case 112: t = this.runner.createThread(stack[stack_index], 0, false); stack[stack_index] = t; op_index += 1; break; - // add thread to the runner thread list - case 113: // OPCODE_SLEEP + case 113: sleep_time = isFinite(stack[stack_index]) ? stack[stack_index] : 0; this.runner.sleep(sleep_time); op_index += 1; restore_op_index = op_index; - op_index = length; // stop the thread + op_index = length; break; - case 200: // COMPILED + case 200: stack_index = arg1[op_index](stack, stack_index, locals, locals_offset, object, global); op_index++; break; default: - throw `Unsupported operation: ${opcodes[op_index]}`; + throw "Unsupported operation: " + opcodes[op_index]; } } if (restore_op_index >= 0) { @@ -1497,14 +1488,14 @@ this.Processor = class Processor { this.routine.callback = null; } } - // console.info """stack_index: #{stack_index}""" - // console.info stack if (this.log) { console.info("total operations: " + op_count); - console.info(`stack_index: ${stack_index}`); - console.info(`result: ${stack[stack_index]}`); + console.info("stack_index: " + stack_index); + console.info("result: " + stack[stack_index]); } return stack[stack_index]; - } + }; + + return Processor; -}; +})(); diff --git a/static/js/languages/microscript/v2/program.js b/static/js/languages/microscript/v2/program.js index 784c1d66..507413c6 100644 --- a/static/js/languages/microscript/v2/program.js +++ b/static/js/languages/microscript/v2/program.js @@ -1,52 +1,57 @@ -this.Program = class Program { - constructor() { +this.Program = (function() { + function Program() { this.statements = []; } - add(statement) { + Program.prototype.add = function(statement) { return this.statements.push(statement); - } + }; - isAssignment() { + Program.prototype.isAssignment = function() { return this.statements.length > 0 && this.statements[this.statements.length - 1] instanceof Program.Assignment; - } + }; -}; + return Program; -this.Program.Expression = class Expression { - constructor() {} +})(); -}; +this.Program.Expression = (function() { + function Expression() {} + + return Expression; -this.Program.Assignment = class Assignment { - constructor(token1, field1, expression1, local) { +})(); + +this.Program.Assignment = (function() { + function Assignment(token1, field1, expression1, local) { this.token = token1; this.field = field1; this.expression = expression1; this.local = local; } -}; + return Assignment; -this.Program.SelfAssignment = class SelfAssignment { - constructor(token1, field1, operation, expression1) { +})(); + +this.Program.SelfAssignment = (function() { + function SelfAssignment(token1, field1, operation, expression1) { this.token = token1; this.field = field1; this.operation = operation; this.expression = expression1; } -}; + return SelfAssignment; -this.Program.Value = (function() { - class Value { - constructor(token1, type, value1) { - this.token = token1; - this.type = type; - this.value = value1; - } +})(); - }; +this.Program.Value = (function() { + function Value(token1, type, value1) { + this.token = token1; + this.type = type; + this.value = value1; + } Value.TYPE_NUMBER = 1; @@ -62,7 +67,7 @@ this.Program.Value = (function() { return Value; -}).call(this); +})(); this.Program.CreateFieldAccess = function(token, expression, field) { if (expression instanceof Program.Field) { @@ -73,27 +78,31 @@ this.Program.CreateFieldAccess = function(token, expression, field) { } }; -this.Program.Variable = class Variable { - constructor(token1, identifier) { +this.Program.Variable = (function() { + function Variable(token1, identifier) { this.token = token1; this.identifier = identifier; } -}; + return Variable; + +})(); -this.Program.Field = class Field { - constructor(token1, expression1, chain) { +this.Program.Field = (function() { + function Field(token1, expression1, chain) { this.token = token1; this.expression = expression1; this.chain = chain; this.token = this.expression.token; } - appendField(field) { + Field.prototype.appendField = function(field) { return this.chain.push(field); - } + }; -}; + return Field; + +})(); this.Program.BuildOperations = function(ops, terms) { var i, o, o1, o2, prec, t1, t2; @@ -117,58 +126,70 @@ this.Program.BuildOperations = function(ops, terms) { return new Program.Operation(ops[0].token, ops[0].operation, terms[0], terms[1]); }; -this.Program.Operation = class Operation { - constructor(token1, operation, term1, term2) { +this.Program.Operation = (function() { + function Operation(token1, operation, term1, term2) { this.token = token1; this.operation = operation; this.term1 = term1; this.term2 = term2; } -}; + return Operation; + +})(); -this.Program.Negate = class Negate { - constructor(token1, expression1) { +this.Program.Negate = (function() { + function Negate(token1, expression1) { this.token = token1; this.expression = expression1; } -}; + return Negate; + +})(); -this.Program.Not = class Not { - constructor(token1, expression1) { +this.Program.Not = (function() { + function Not(token1, expression1) { this.token = token1; this.expression = expression1; } -}; + return Not; + +})(); -this.Program.Braced = class Braced { - constructor(token1, expression1) { +this.Program.Braced = (function() { + function Braced(token1, expression1) { this.token = token1; this.expression = expression1; } -}; + return Braced; + +})(); -this.Program.Return = class Return { - constructor(token1, expression1) { +this.Program.Return = (function() { + function Return(token1, expression1) { this.token = token1; this.expression = expression1; } -}; + return Return; + +})(); -this.Program.Condition = class Condition { - constructor(token1, chain) { +this.Program.Condition = (function() { + function Condition(token1, chain) { this.token = token1; this.chain = chain; } -}; + return Condition; + +})(); -this.Program.For = class For { - constructor(token1, iterator, range_from, range_to, range_by, sequence) { +this.Program.For = (function() { + function For(token1, iterator, range_from, range_to, range_by, sequence) { this.token = token1; this.iterator = iterator; this.range_from = range_from; @@ -177,20 +198,27 @@ this.Program.For = class For { this.sequence = sequence; } -}; + return For; -this.Program.ForIn = class ForIn { - constructor(token1, iterator, list, sequence) { +})(); + +this.Program.ForIn = (function() { + function ForIn(token1, iterator, list, sequence) { this.token = token1; this.iterator = iterator; this.list = list; this.sequence = sequence; } -}; + return ForIn; -this.Program.toString = function(value, nesting = 0) { +})(); + +this.Program.toString = function(value, nesting) { var i, j, k, key, len, pref, ref, s, v; + if (nesting == null) { + nesting = 0; + } if (value instanceof Routine) { if (nesting === 0) { return value.source || "[function]"; @@ -200,7 +228,7 @@ this.Program.toString = function(value, nesting = 0) { } else if (typeof value === "function") { return "[native function]"; } else if (typeof value === "string") { - return `"${value}"`; + return "\"" + value + "\""; } else if (Array.isArray(value)) { if (nesting >= 1) { return "[list]"; @@ -222,76 +250,90 @@ this.Program.toString = function(value, nesting = 0) { } for (key in value) { v = value[key]; - s += pref + ` ${key} = ${Program.toString(v, nesting + 1)}\n`; + s += pref + (" " + key + " = " + (Program.toString(v, nesting + 1)) + "\n"); } return s + pref + "end"; } return value || 0; }; -this.Program.While = class While { - constructor(token1, condition, sequence) { +this.Program.While = (function() { + function While(token1, condition, sequence) { this.token = token1; this.condition = condition; this.sequence = sequence; } -}; + return While; + +})(); -this.Program.Break = class Break { - constructor(token1) { +this.Program.Break = (function() { + function Break(token1) { this.token = token1; this.nopop = true; } -}; + return Break; + +})(); -this.Program.Continue = class Continue { - constructor(token1) { +this.Program.Continue = (function() { + function Continue(token1) { this.token = token1; this.nopop = true; } -}; + return Continue; + +})(); -this.Program.Function = class Function { - constructor(token1, args, sequence, end) { +this.Program.Function = (function() { + function Function(token1, args, sequence, end) { this.token = token1; this.args = args; this.sequence = sequence; this.source = "function" + this.token.tokenizer.input.substring(this.token.index, end.index + 2); } -}; + return Function; + +})(); -this.Program.FunctionCall = class FunctionCall { - constructor(token1, expression1, args) { +this.Program.FunctionCall = (function() { + function FunctionCall(token1, expression1, args) { this.token = token1; this.expression = expression1; this.args = args; } -}; + return FunctionCall; + +})(); -this.Program.CreateObject = class CreateObject { - constructor(token1, fields) { +this.Program.CreateObject = (function() { + function CreateObject(token1, fields) { this.token = token1; this.fields = fields; } -}; + return CreateObject; + +})(); -this.Program.CreateClass = class CreateClass { - constructor(token1, ext, fields) { +this.Program.CreateClass = (function() { + function CreateClass(token1, ext, fields) { this.token = token1; this.ext = ext; this.fields = fields; } -}; + return CreateClass; + +})(); -this.Program.NewCall = class NewCall { - constructor(token1, expression1) { +this.Program.NewCall = (function() { + function NewCall(token1, expression1) { this.token = token1; this.expression = expression1; if (!(this.expression instanceof Program.FunctionCall)) { @@ -299,10 +341,12 @@ this.Program.NewCall = class NewCall { } } -}; + return NewCall; + +})(); -this.Program.After = class After { - constructor(token1, delay, sequence, end, multiplier) { +this.Program.After = (function() { + function After(token1, delay, sequence, end, multiplier) { this.token = token1; this.delay = delay; this.sequence = sequence; @@ -310,10 +354,12 @@ this.Program.After = class After { this.source = "after " + this.token.tokenizer.input.substring(this.token.index, end.index + 2); } -}; + return After; + +})(); -this.Program.Every = class Every { - constructor(token1, delay, sequence, end, multiplier) { +this.Program.Every = (function() { + function Every(token1, delay, sequence, end, multiplier) { this.token = token1; this.delay = delay; this.sequence = sequence; @@ -321,33 +367,41 @@ this.Program.Every = class Every { this.source = "every " + this.token.tokenizer.input.substring(this.token.index, end.index + 2); } -}; + return Every; + +})(); -this.Program.Do = class Do { - constructor(token1, sequence, end) { +this.Program.Do = (function() { + function Do(token1, sequence, end) { this.token = token1; this.sequence = sequence; this.source = "do " + this.token.tokenizer.input.substring(this.token.index, end.index + 2); } -}; + return Do; + +})(); -this.Program.Sleep = class Sleep { - constructor(token1, delay, multiplier) { +this.Program.Sleep = (function() { + function Sleep(token1, delay, multiplier) { this.token = token1; this.delay = delay; this.multiplier = multiplier; } -}; + return Sleep; + +})(); -this.Program.Delete = class Delete { - constructor(token1, field1) { +this.Program.Delete = (function() { + function Delete(token1, field1) { this.token = token1; this.field = field1; } -}; + return Delete; + +})(); this.Program.Precedence = { "^": 21, diff --git a/static/js/languages/microscript/v2/routine.js b/static/js/languages/microscript/v2/routine.js index 07f02e57..03e136eb 100644 --- a/static/js/languages/microscript/v2/routine.js +++ b/static/js/languages/microscript/v2/routine.js @@ -1,5 +1,5 @@ -this.Routine = class Routine { - constructor(num_args) { +this.Routine = (function() { + function Routine(num_args) { this.num_args = num_args; this.ops = []; this.opcodes = []; @@ -14,7 +14,7 @@ this.Routine = class Routine { this.import_self = -1; } - clone() { + Routine.prototype.clone = function() { var r; r = new Routine(this.num_args); r.opcodes = this.opcodes; @@ -23,24 +23,27 @@ this.Routine = class Routine { r.locals_size = this.locals_size; r.uses_arguments = this.uses_arguments; return r; - } + }; - createLabel(str = "label") { + Routine.prototype.createLabel = function(str) { var name; + if (str == null) { + str = "label"; + } return name = ":" + str + "_" + this.label_count++; - } + }; - setLabel(name) { + Routine.prototype.setLabel = function(name) { return this.labels[name] = this.opcodes.length; - } + }; - optimize() { + Routine.prototype.optimize = function() { if (this.transpile) { new Transpiler().transpile(this); } - } + }; - removeable(index) { + Routine.prototype.removeable = function(index) { var label, ref1, value; ref1 = this.labels; for (label in ref1) { @@ -50,9 +53,9 @@ this.Routine = class Routine { } } return true; - } + }; - remove(index) { + Routine.prototype.remove = function(index) { var label, ref1, value; ref1 = this.labels; for (label in ref1) { @@ -67,12 +70,12 @@ this.Routine = class Routine { this.arg1.splice(index, 1); this.ref.splice(index, 1); return true; - } + }; - resolveLabels() { + Routine.prototype.resolveLabels = function() { var i, j, ref1, ref2, ref3, results; results = []; - for (i = j = 0, ref1 = this.opcodes.length - 1; (0 <= ref1 ? j <= ref1 : j >= ref1); i = 0 <= ref1 ? ++j : --j) { + for (i = j = 0, ref1 = this.opcodes.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) { if ((ref2 = this.opcodes[i]) === OPCODES.JUMP || ref2 === OPCODES.JUMPY || ref2 === OPCODES.JUMPN || ref2 === OPCODES.JUMPY_NOPOP || ref2 === OPCODES.JUMPN_NOPOP) { if (this.labels[this.arg1[i]]) { results.push(this.arg1[i] = this.labels[this.arg1[i]]); @@ -90,16 +93,22 @@ this.Routine = class Routine { } } return results; - } + }; - OP(code, ref, v1 = 0) { + Routine.prototype.OP = function(code, ref, v1) { + if (v1 == null) { + v1 = 0; + } this.opcodes.push(code); this.arg1.push(v1); return this.ref.push(ref); - } + }; - OP_INSERT(code, ref, v1 = 0, index) { + Routine.prototype.OP_INSERT = function(code, ref, v1, index) { var label, ref1, value; + if (v1 == null) { + v1 = 0; + } this.opcodes.splice(index, 0, code); this.arg1.splice(index, 0, v1); this.ref.splice(index, 0, ref); @@ -110,261 +119,267 @@ this.Routine = class Routine { this.labels[label] += 1; } } - } + }; - TYPE(ref) { + Routine.prototype.TYPE = function(ref) { return this.OP(OPCODES.TYPE, ref); - } + }; - VARIABLE_TYPE(variable, ref) { + Routine.prototype.VARIABLE_TYPE = function(variable, ref) { return this.OP(OPCODES.VARIABLE_TYPE, ref, variable); - } + }; - PROPERTY_TYPE(ref) { + Routine.prototype.PROPERTY_TYPE = function(ref) { return this.OP(OPCODES.PROPERTY_TYPE, ref); - } + }; - LOAD_THIS(ref) { + Routine.prototype.LOAD_THIS = function(ref) { return this.OP(OPCODES.LOAD_THIS, ref); - } + }; - LOAD_GLOBAL(ref) { + Routine.prototype.LOAD_GLOBAL = function(ref) { return this.OP(OPCODES.LOAD_GLOBAL, ref); - } + }; - LOAD_VALUE(value, ref) { + Routine.prototype.LOAD_VALUE = function(value, ref) { return this.OP(OPCODES.LOAD_VALUE, ref, value); - } + }; - LOAD_LOCAL(index, ref) { + Routine.prototype.LOAD_LOCAL = function(index, ref) { return this.OP(OPCODES.LOAD_LOCAL, ref, index); - } + }; - LOAD_VARIABLE(variable, ref) { + Routine.prototype.LOAD_VARIABLE = function(variable, ref) { return this.OP(OPCODES.LOAD_VARIABLE, ref, variable); - } + }; - LOAD_LOCAL_OBJECT(index, ref) { + Routine.prototype.LOAD_LOCAL_OBJECT = function(index, ref) { return this.OP(OPCODES.LOAD_LOCAL_OBJECT, ref, index); - } + }; - LOAD_VARIABLE_OBJECT(variable, ref) { + Routine.prototype.LOAD_VARIABLE_OBJECT = function(variable, ref) { return this.OP(OPCODES.LOAD_VARIABLE_OBJECT, ref, variable); - } + }; - POP(ref) { + Routine.prototype.POP = function(ref) { return this.OP(OPCODES.POP, ref); - } + }; - LOAD_PROPERTY(ref) { + Routine.prototype.LOAD_PROPERTY = function(ref) { return this.OP(OPCODES.LOAD_PROPERTY, ref); - } + }; - LOAD_PROPERTY_OBJECT(ref) { + Routine.prototype.LOAD_PROPERTY_OBJECT = function(ref) { return this.OP(OPCODES.LOAD_PROPERTY_OBJECT, ref); - } + }; - CREATE_OBJECT(ref) { + Routine.prototype.CREATE_OBJECT = function(ref) { return this.OP(OPCODES.CREATE_OBJECT, ref); - } + }; - MAKE_OBJECT(ref) { + Routine.prototype.MAKE_OBJECT = function(ref) { return this.OP(OPCODES.MAKE_OBJECT, ref); - } + }; - CREATE_ARRAY(ref) { + Routine.prototype.CREATE_ARRAY = function(ref) { return this.OP(OPCODES.CREATE_ARRAY, ref); - } + }; - CREATE_CLASS(parent_var, ref) { + Routine.prototype.CREATE_CLASS = function(parent_var, ref) { return this.OP(OPCODES.CREATE_CLASS, ref, parent_var); - } + }; - UPDATE_CLASS(variable, ref) { + Routine.prototype.UPDATE_CLASS = function(variable, ref) { return this.OP(OPCODES.UPDATE_CLASS, ref, variable); - } + }; - NEW_CALL(args, ref) { + Routine.prototype.NEW_CALL = function(args, ref) { return this.OP(OPCODES.NEW_CALL, ref, args); - } + }; - ADD(ref, self = 0) { + Routine.prototype.ADD = function(ref, self) { + if (self == null) { + self = 0; + } return this.OP(OPCODES.ADD, ref, self); - } + }; - SUB(ref, self = 0) { + Routine.prototype.SUB = function(ref, self) { + if (self == null) { + self = 0; + } return this.OP(OPCODES.SUB, ref, self); - } + }; - MUL(ref) { + Routine.prototype.MUL = function(ref) { return this.OP(OPCODES.MUL, ref); - } + }; - DIV(ref) { + Routine.prototype.DIV = function(ref) { return this.OP(OPCODES.DIV, ref); - } + }; - MODULO(ref) { + Routine.prototype.MODULO = function(ref) { return this.OP(OPCODES.MODULO, ref); - } + }; - BINARY_AND(ref) { + Routine.prototype.BINARY_AND = function(ref) { return this.OP(OPCODES.BINARY_AND, ref); - } + }; - BINARY_OR(ref) { + Routine.prototype.BINARY_OR = function(ref) { return this.OP(OPCODES.BINARY_OR, ref); - } + }; - SHIFT_LEFT(ref) { + Routine.prototype.SHIFT_LEFT = function(ref) { return this.OP(OPCODES.SHIFT_LEFT, ref); - } + }; - SHIFT_RIGHT(ref) { + Routine.prototype.SHIFT_RIGHT = function(ref) { return this.OP(OPCODES.SHIFT_RIGHT, ref); - } + }; - NEGATE(ref) { + Routine.prototype.NEGATE = function(ref) { return this.OP(OPCODES.NEGATE, ref); - } + }; - LOAD_PROPERTY_ATOP(ref) { + Routine.prototype.LOAD_PROPERTY_ATOP = function(ref) { return this.OP(OPCODES.LOAD_PROPERTY_ATOP, ref); - } + }; - EQ(ref) { + Routine.prototype.EQ = function(ref) { return this.OP(OPCODES.EQ, ref); - } + }; - NEQ(ref) { + Routine.prototype.NEQ = function(ref) { return this.OP(OPCODES.NEQ, ref); - } + }; - LT(ref) { + Routine.prototype.LT = function(ref) { return this.OP(OPCODES.LT, ref); - } + }; - GT(ref) { + Routine.prototype.GT = function(ref) { return this.OP(OPCODES.GT, ref); - } + }; - LTE(ref) { + Routine.prototype.LTE = function(ref) { return this.OP(OPCODES.LTE, ref); - } + }; - GTE(ref) { + Routine.prototype.GTE = function(ref) { return this.OP(OPCODES.GTE, ref); - } + }; - NOT(ref) { + Routine.prototype.NOT = function(ref) { return this.OP(OPCODES.NOT, ref); - } + }; - FORLOOP_INIT(iterator, ref) { + Routine.prototype.FORLOOP_INIT = function(iterator, ref) { return this.OP(OPCODES.FORLOOP_INIT, ref, iterator); - } + }; - FORLOOP_CONTROL(args, ref) { + Routine.prototype.FORLOOP_CONTROL = function(args, ref) { return this.OP(OPCODES.FORLOOP_CONTROL, ref, args); - } + }; - FORIN_INIT(args, ref) { + Routine.prototype.FORIN_INIT = function(args, ref) { return this.OP(OPCODES.FORIN_INIT, ref, args); - } + }; - FORIN_CONTROL(args, ref) { + Routine.prototype.FORIN_CONTROL = function(args, ref) { return this.OP(OPCODES.FORIN_CONTROL, ref, args); - } + }; - JUMP(index, ref) { + Routine.prototype.JUMP = function(index, ref) { return this.OP(OPCODES.JUMP, ref, index); - } + }; - JUMPY(index, ref) { + Routine.prototype.JUMPY = function(index, ref) { return this.OP(OPCODES.JUMPY, ref, index); - } + }; - JUMPN(index, ref) { + Routine.prototype.JUMPN = function(index, ref) { return this.OP(OPCODES.JUMPN, ref, index); - } + }; - JUMPY_NOPOP(index, ref) { + Routine.prototype.JUMPY_NOPOP = function(index, ref) { return this.OP(OPCODES.JUMPY_NOPOP, ref, index); - } + }; - JUMPN_NOPOP(index, ref) { + Routine.prototype.JUMPN_NOPOP = function(index, ref) { return this.OP(OPCODES.JUMPN_NOPOP, ref, index); - } + }; - STORE_LOCAL(index, ref) { + Routine.prototype.STORE_LOCAL = function(index, ref) { return this.OP(OPCODES.STORE_LOCAL, ref, index); - } + }; - STORE_VARIABLE(field, ref) { + Routine.prototype.STORE_VARIABLE = function(field, ref) { return this.OP(OPCODES.STORE_VARIABLE, ref, field); - } + }; - CREATE_PROPERTY(ref) { + Routine.prototype.CREATE_PROPERTY = function(ref) { return this.OP(OPCODES.CREATE_PROPERTY, ref); - } + }; - STORE_PROPERTY(ref) { + Routine.prototype.STORE_PROPERTY = function(ref) { return this.OP(OPCODES.STORE_PROPERTY, ref); - } + }; - LOAD_ROUTINE(value, ref) { + Routine.prototype.LOAD_ROUTINE = function(value, ref) { return this.OP(OPCODES.LOAD_ROUTINE, ref, value); - } + }; - FUNCTION_CALL(args, ref) { + Routine.prototype.FUNCTION_CALL = function(args, ref) { return this.OP(OPCODES.FUNCTION_CALL, ref, args); - } + }; - FUNCTION_APPLY_VARIABLE(args, ref) { + Routine.prototype.FUNCTION_APPLY_VARIABLE = function(args, ref) { return this.OP(OPCODES.FUNCTION_APPLY_VARIABLE, ref, args); - } + }; - FUNCTION_APPLY_PROPERTY(args, ref) { + Routine.prototype.FUNCTION_APPLY_PROPERTY = function(args, ref) { return this.OP(OPCODES.FUNCTION_APPLY_PROPERTY, ref, args); - } + }; - SUPER_CALL(args, ref) { + Routine.prototype.SUPER_CALL = function(args, ref) { return this.OP(OPCODES.SUPER_CALL, ref, args); - } + }; - RETURN(ref) { + Routine.prototype.RETURN = function(ref) { return this.OP(OPCODES.RETURN, ref); - } + }; - AFTER(ref) { + Routine.prototype.AFTER = function(ref) { return this.OP(OPCODES.AFTER, ref); - } + }; - EVERY(ref) { + Routine.prototype.EVERY = function(ref) { return this.OP(OPCODES.EVERY, ref); - } + }; - DO(ref) { + Routine.prototype.DO = function(ref) { return this.OP(OPCODES.DO, ref); - } + }; - SLEEP(ref) { + Routine.prototype.SLEEP = function(ref) { return this.OP(OPCODES.SLEEP, ref); - } + }; - DELETE(ref) { + Routine.prototype.DELETE = function(ref) { return this.OP(OPCODES.DELETE, ref); - } + }; - UNARY_OP(f, ref) { + Routine.prototype.UNARY_OP = function(f, ref) { return this.OP(OPCODES.UNARY_OP, ref, f); - } + }; - BINARY_OP(f, ref) { + Routine.prototype.BINARY_OP = function(f, ref) { return this.OP(OPCODES.BINARY_OP, ref, f); - } + }; - toString() { + Routine.prototype.toString = function() { var i, j, len, op, ref1, s; s = ""; ref1 = this.opcodes; @@ -372,18 +387,19 @@ this.Routine = class Routine { op = ref1[i]; s += OPCODES[op]; if (this.arg1[i] != null) { - //if typeof @arg1[i] != "function" - s += ` ${this.arg1[i]}`; + s += " " + this.arg1[i]; } s += "\n"; } return s; - } + }; + + return Routine; -}; +})(); -this.OPCODES_CLASS = class OPCODES_CLASS { - constructor() { +this.OPCODES_CLASS = (function() { + function OPCODES_CLASS() { this.table = {}; this.set("TYPE", 1); this.set("VARIABLE_TYPE", 2); @@ -452,11 +468,13 @@ this.OPCODES_CLASS = class OPCODES_CLASS { this.set("SLEEP", 113); } - set(op, code) { + OPCODES_CLASS.prototype.set = function(op, code) { this[op] = code; return this[code] = op; - } + }; + + return OPCODES_CLASS; -}; +})(); this.OPCODES = new this.OPCODES_CLASS; diff --git a/static/js/languages/microscript/v2/runner.js b/static/js/languages/microscript/v2/runner.js index a4cde560..dbd83ccf 100644 --- a/static/js/languages/microscript/v2/runner.js +++ b/static/js/languages/microscript/v2/runner.js @@ -1,9 +1,9 @@ -this.Runner = class Runner { - constructor(microvm) { +this.Runner = (function() { + function Runner(microvm) { this.microvm = microvm; } - init() { + Runner.prototype.init = function() { this.initialized = true; this.system = this.microvm.context.global.system; this.system.preemptive = 1; @@ -27,19 +27,21 @@ this.Runner = class Runner { } }; this.microvm.context.global.List = { - sortList: (f) => { - var funk; - if ((f != null) && f instanceof Program.Function) { - funk = function(a, b) { - return f.call(this.microvm.context.global, [a, b], true); - }; - } else if ((f != null) && typeof f === "function") { - funk = f; - } - return this.sort(funk); - }, + sortList: (function(_this) { + return function(f) { + var funk; + if ((f != null) && f instanceof Program.Function) { + funk = function(a, b) { + return f.call(this.microvm.context.global, [a, b], true); + }; + } else if ((f != null) && typeof f === "function") { + funk = f; + } + return _this.sort(funk); + }; + })(this), "+": function(a, b, self) { - if (!self) { // not +=, clone array a + if (!self) { a = [...a]; } if (Array.isArray(b)) { @@ -51,7 +53,7 @@ this.Runner = class Runner { }, "-": function(a, b, self) { var index; - if (!self) { // not -=, clone array a + if (!self) { a = [...a]; } index = a.indexOf(b); @@ -87,9 +89,9 @@ this.Runner = class Runner { this.cpu_load = 0; this.microvm.context.meta.print("microScript 2.0"); return this.triggers_controls_update = true; - } + }; - run(src, filename, callback) { + Runner.prototype.run = function(src, filename, callback) { var compiler, err, id, j, len, parser, program, ref, result, w; if (!this.initialized) { this.init(); @@ -141,19 +143,19 @@ this.Runner = class Runner { this.main_thread.addCall(compiler.routine); this.tick(); return result; - } + }; - call(name, args) { + Runner.prototype.call = function(name, args) { var f, routine; if (name === "draw" || name === "update" || name === "serverUpdate") { if (this.microvm.context.global[name] != null) { - this.main_thread.addCall(`${name}()`); + this.main_thread.addCall(name + "()"); } return; } if (this.microvm.context.global[name] != null) { if ((args == null) || !args.length) { - return this.main_thread.addCall(`${name}()`); + return this.main_thread.addCall(name + "()"); } else { routine = this.microvm.context.global[name]; if (routine instanceof Routine) { @@ -166,21 +168,21 @@ this.Runner = class Runner { } else { return 0; } - } + }; - toString(obj) { + Runner.prototype.toString = function(obj) { return Program.toString(obj); - } + }; - process(thread, time_limit) { + Runner.prototype.process = function(thread, time_limit) { var processor; processor = thread.processor; processor.time_limit = time_limit; this.current_thread = thread; return processor.run(this.microvm.context); - } + }; - tick() { + Runner.prototype.tick = function() { var dt, frame_time, i, index, j, k, len, load, margin, processing, processor, ref, ref1, t, time, time_limit, time_out; if (this.system.fps != null) { this.fps = this.fps * .9 + this.system.fps * .1; @@ -193,7 +195,7 @@ this.Runner = class Runner { margin = Math.floor(1000 / this.fps * .8); } time = Date.now(); - time_limit = time + 100; // allow more time to prevent interrupting main_thread in the middle of a draw() + time_limit = time + 100; time_out = this.system.preemptive ? time_limit : 2e308; processor = this.main_thread.processor; if (!processor.done) { @@ -209,7 +211,7 @@ this.Runner = class Runner { while (processor.done && Date.now() < time_out && this.main_thread.loadNext()) { this.process(this.main_thread, time_out); } - time_limit = time + margin; // secondary threads get remaining time + time_limit = time + margin; time_out = this.system.preemptive ? time_limit : 2e308; processing = true; while (processing) { @@ -266,7 +268,7 @@ this.Runner = class Runner { t = this.threads[i]; if (t.terminated) { this.threads.splice(i, 1); - index = this.system.threads.indexOf(t.interface); + index = this.system.threads.indexOf(t["interface"]); if (index >= 0) { this.system.threads.splice(index, 1); } @@ -277,9 +279,9 @@ this.Runner = class Runner { load = t / dt * 100; this.cpu_load = this.cpu_load * .9 + load * .1; this.system.cpu_load = Math.min(100, Math.round(this.cpu_load)); - } + }; - createThread(routine, delay, repeat) { + Runner.prototype.createThread = function(routine, delay, repeat) { var i, j, ref, t; t = new Thread(this); t.routine = routine; @@ -289,52 +291,60 @@ this.Runner = class Runner { t.repeat = repeat; t.delay = delay; } - this.system.threads.push(t.interface); + this.system.threads.push(t["interface"]); for (i = j = 0, ref = routine.import_values.length - 1; j <= ref; i = j += 1) { if (routine.import_values[i] === routine) { - routine.import_values[i] = t.interface; + routine.import_values[i] = t["interface"]; } } - return t.interface; - } + return t["interface"]; + }; - sleep(value) { + Runner.prototype.sleep = function(value) { if (this.current_thread != null) { return this.current_thread.sleep_until = Date.now() + Math.max(0, value); } - } + }; -}; + return Runner; -this.Thread = class Thread { - constructor(runner) { +})(); + +this.Thread = (function() { + function Thread(runner) { this.runner = runner; this.loop = false; this.processor = new Processor(this.runner); this.paused = false; this.terminated = false; this.next_calls = []; - this.interface = { - pause: () => { - return this.pause(); - }, - resume: () => { - return this.resume(); - }, - stop: () => { - return this.stop(); - }, + this["interface"] = { + pause: (function(_this) { + return function() { + return _this.pause(); + }; + })(this), + resume: (function(_this) { + return function() { + return _this.resume(); + }; + })(this), + stop: (function(_this) { + return function() { + return _this.stop(); + }; + })(this), status: "running" }; } - addCall(call) { + Thread.prototype.addCall = function(call) { if (this.next_calls.indexOf(call) < 0) { return this.next_calls.push(call); } - } + }; - loadNext() { + Thread.prototype.loadNext = function() { var compiler, f, parser, program; if (this.next_calls.length > 0) { f = this.next_calls.splice(0, 1)[0]; @@ -354,32 +364,34 @@ this.Thread = class Thread { } else { return false; } - } + }; - pause() { - if (this.interface.status === "running") { - this.interface.status = "paused"; + Thread.prototype.pause = function() { + if (this["interface"].status === "running") { + this["interface"].status = "paused"; this.paused = true; return 1; } else { return 0; } - } + }; - resume() { - if (this.interface.status === "paused") { - this.interface.status = "running"; + Thread.prototype.resume = function() { + if (this["interface"].status === "paused") { + this["interface"].status = "running"; this.paused = false; return 1; } else { return 0; } - } + }; - stop() { - this.interface.status = "stopped"; + Thread.prototype.stop = function() { + this["interface"].status = "stopped"; this.terminated = true; return 1; - } + }; + + return Thread; -}; +})(); diff --git a/static/js/languages/microscript/v2/token.js b/static/js/languages/microscript/v2/token.js index e9d14b85..ad9d747d 100644 --- a/static/js/languages/microscript/v2/token.js +++ b/static/js/languages/microscript/v2/token.js @@ -1,5 +1,5 @@ -this.Token = class Token { - constructor(tokenizer, type, value, string_value) { +this.Token = (function() { + function Token(tokenizer, type, value, string_value) { this.tokenizer = tokenizer; this.type = type; this.value = value; @@ -16,11 +16,13 @@ this.Token = class Token { this.is_binary_operator = (this.type >= 30 && this.type <= 39) || (this.type >= 200 && this.type <= 201) || (this.type >= 2 && this.type <= 7); } - toString() { + Token.prototype.toString = function() { return this.value + " : " + this.type; - } + }; + + return Token; -}; +})(); this.Token.TYPE_EQUALS = 1; @@ -46,8 +48,6 @@ this.Token.TYPE_OPEN_BRACE = 20; this.Token.TYPE_CLOSED_BRACE = 21; -// @Token.TYPE_OPEN_CURLY_BRACE = 22 -// @Token.TYPE_CLOSED_CURLY_BRACE = 23 this.Token.TYPE_OPEN_BRACKET = 24; this.Token.TYPE_CLOSED_BRACKET = 25; diff --git a/static/js/languages/python/runner.js b/static/js/languages/python/runner.js index 215da013..a0b2221d 100644 --- a/static/js/languages/python/runner.js +++ b/static/js/languages/python/runner.js @@ -1,62 +1,69 @@ -this.Runner = class Runner { - constructor(microvm) { +this.Runner = (function() { + function Runner(microvm) { this.microvm = microvm; } - init() { + Runner.prototype.init = function() { var kd, key, src; this.initialized = true; window.ctx = this.microvm.context.global; src = ""; for (key in this.microvm.context.global) { kd = key; - src += `${kd} = window.ctx.${key}\n`; + src += kd + " = window.ctx." + key + "\n"; } window.stdout = { - write: (text) => { - return this.microvm.context.meta.print(text); - } + write: (function(_this) { + return function(text) { + return _this.microvm.context.meta.print(text); + }; + })(this) }; window.stderr = { - write: (text) => { - var f, file, i, len, line, t; - if (Array.isArray(text)) { - line = 1; - file = ""; - for (i = 0, len = text.length; i < len; i++) { - t = text[i]; - f = t.split("File"); - if (f[1] != null) { - f = f[1].split('"'); - if ((f[1] != null) && f[1].length > 0) { - file = f[1]; + write: (function(_this) { + return function(text) { + var f, file, i, len, line, t; + if (Array.isArray(text)) { + line = 1; + file = ""; + for (i = 0, len = text.length; i < len; i++) { + t = text[i]; + f = t.split("File"); + if (f[1] != null) { + f = f[1].split('"'); + if ((f[1] != null) && f[1].length > 0) { + file = f[1]; + } + } + t = t.split(" line "); + if (t[1] != null) { + line = t[1].split("\n")[0].split(",")[0]; } } - t = t.split(" line "); - if (t[1] != null) { - line = t[1].split("\n")[0].split(",")[0]; - } + _this.microvm.context.location = { + token: { + file: file, + line: line, + column: 0, + error_text: text[text.length - 1].replace("\n", "") + } + }; + throw text[text.length - 1].replace("\n", ""); + } else { + throw text; } - this.microvm.context.location = { - token: { - file: file, - line: line, - column: 0, - error_text: text[text.length - 1].replace("\n", "") - } - }; - throw text[text.length - 1].replace("\n", ""); - } else { - throw text; - } - } + }; + })(this) }; src += "import sys\n\nsys.stdout = window.stdout\n\nsys.stderr = window.stderr\n\n"; return this.run(src); - } + }; - run(program, name = "") { + Runner.prototype.run = function(program, name) { var err, res; + if (name == null) { + name = ""; + } if (!this.initialized) { this.init(); } @@ -69,9 +76,9 @@ this.Runner = class Runner { err = error; throw err.toString(); } - } + }; - call(name, args) { + Runner.prototype.call = function(name, args) { var err; if ((name === "draw" || name === "update" || name === "init" || name === "serverInit" || name === "serverUpdate") && typeof window[name] === "function") { try { @@ -83,14 +90,16 @@ this.Runner = class Runner { } else { } - } + }; - toString(obj) { + Runner.prototype.toString = function(obj) { if (obj != null) { return obj.toString(); } else { return "none"; } - } + }; + + return Runner; -}; +})(); diff --git a/static/js/mapeditor/mapeditor.js b/static/js/mapeditor/mapeditor.js index 7036d41c..a716e286 100644 --- a/static/js/mapeditor/mapeditor.js +++ b/static/js/mapeditor/mapeditor.js @@ -1,6 +1,11 @@ -this.MapEditor = class MapEditor extends Manager { - constructor(app) { - super(app); +var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +this.MapEditor = (function(superClass) { + extend(MapEditor, superClass); + + function MapEditor(app) { + MapEditor.__super__.constructor.call(this, app); this.folder = "maps"; this.item = "map"; this.list_change_event = "maplist"; @@ -17,103 +22,119 @@ this.MapEditor = class MapEditor extends Manager { document.getElementById("mapeditor-wrapper").appendChild(this.mapview.canvas); this.save_delay = 1000; this.save_time = 0; - setInterval((() => { - return this.checkSave(); - }), this.save_delay / 2); - this.app.appui.setAction("create-map-button", () => { - return this.createMap(); - }); + setInterval(((function(_this) { + return function() { + return _this.checkSave(); + }; + })(this)), this.save_delay / 2); + this.app.appui.setAction("create-map-button", (function(_this) { + return function() { + return _this.createMap(); + }; + })(this)); this.selected_map = null; - this.app.appui.setAction("undo-map", () => { - return this.undo(); - }); - this.app.appui.setAction("redo-map", () => { - return this.redo(); - }); - this.app.appui.setAction("copy-map", () => { - return this.copy(); - }); - this.app.appui.setAction("cut-map", () => { - return this.cut(); - }); - this.app.appui.setAction("paste-map", () => { - return this.paste(); - }); - document.addEventListener("keydown", (event) => { - if (document.getElementById("mapeditor").offsetParent == null) { - return; - } - //console.info event - if ((document.activeElement != null) && document.activeElement.tagName.toLowerCase() === "input") { - return; - } - if (event.metaKey || event.ctrlKey) { - switch (event.key) { - case "z": - this.undo(); - break; - case "Z": - this.redo(); - break; - default: - return; + this.app.appui.setAction("undo-map", (function(_this) { + return function() { + return _this.undo(); + }; + })(this)); + this.app.appui.setAction("redo-map", (function(_this) { + return function() { + return _this.redo(); + }; + })(this)); + this.app.appui.setAction("copy-map", (function(_this) { + return function() { + return _this.copy(); + }; + })(this)); + this.app.appui.setAction("cut-map", (function(_this) { + return function() { + return _this.cut(); + }; + })(this)); + this.app.appui.setAction("paste-map", (function(_this) { + return function() { + return _this.paste(); + }; + })(this)); + document.addEventListener("keydown", (function(_this) { + return function(event) { + if (document.getElementById("mapeditor").offsetParent == null) { + return; } - event.preventDefault(); - return event.stopPropagation(); - } - }); - this.background_color_picker = new BackgroundColorPicker(this, (color) => { - this.mapview.update(); - return document.getElementById("map-background-color").style.background = color; - }); + if ((document.activeElement != null) && document.activeElement.tagName.toLowerCase() === "input") { + return; + } + if (event.metaKey || event.ctrlKey) { + switch (event.key) { + case "z": + _this.undo(); + break; + case "Z": + _this.redo(); + break; + default: + return; + } + event.preventDefault(); + return event.stopPropagation(); + } + }; + })(this)); + this.background_color_picker = new BackgroundColorPicker(this, (function(_this) { + return function(color) { + _this.mapview.update(); + return document.getElementById("map-background-color").style.background = color; + }; + })(this)); this.map_underlay_select = document.getElementById("map-underlay-select"); - this.map_underlay_select.addEventListener("change", () => { - var name; - console.info(this.map_underlay_select.value); - name = this.map_underlay_select.value.replace(/\//g, "-"); - this.map_underlay = name; - return this.mapview.update(); - }); - document.getElementById("map-background-color").addEventListener("mousedown", (event) => { - if (this.background_color_picker.shown) { - return this.background_color_picker.hide(); - } else { - this.background_color_picker.show(); - return event.stopPropagation(); - } - }); - // @map_name_validator = new InputValidator document.getElementById("map-name"), - // document.getElementById("map-name-button"), - // null, - // (value)=> - // return if @app.project.isLocked("maps/#{@selected_map}.json") - // @app.project.lockFile("maps/#{@selected_map}.json") - // @saveNameChange(value[0]) - - // @map_name_validator.regex = RegexLib.filename - this.map_size_validator = new InputValidator([document.getElementById("map-width"), document.getElementById("map-height")], document.getElementById("map-size-button"), null, (value) => { - if (this.app.project.isLocked(`maps/${this.selected_map}.json`)) { - return; - } - this.app.project.lockFile(`maps/${this.selected_map}.json`); - return this.saveDimensionChange(); - }); - this.map_blocksize_validator = new InputValidator([document.getElementById("map-block-width"), document.getElementById("map-block-height")], document.getElementById("map-blocksize-button"), null, (value) => { - if (this.app.project.isLocked(`maps/${this.selected_map}.json`)) { - return; - } - this.app.project.lockFile(`maps/${this.selected_map}.json`); - return this.saveDimensionChange(); - }); + this.map_underlay_select.addEventListener("change", (function(_this) { + return function() { + var name; + console.info(_this.map_underlay_select.value); + name = _this.map_underlay_select.value.replace(/\//g, "-"); + _this.map_underlay = name; + return _this.mapview.update(); + }; + })(this)); + document.getElementById("map-background-color").addEventListener("mousedown", (function(_this) { + return function(event) { + if (_this.background_color_picker.shown) { + return _this.background_color_picker.hide(); + } else { + _this.background_color_picker.show(); + return event.stopPropagation(); + } + }; + })(this)); + this.map_size_validator = new InputValidator([document.getElementById("map-width"), document.getElementById("map-height")], document.getElementById("map-size-button"), null, (function(_this) { + return function(value) { + if (_this.app.project.isLocked("maps/" + _this.selected_map + ".json")) { + return; + } + _this.app.project.lockFile("maps/" + _this.selected_map + ".json"); + return _this.saveDimensionChange(); + }; + })(this)); + this.map_blocksize_validator = new InputValidator([document.getElementById("map-block-width"), document.getElementById("map-block-height")], document.getElementById("map-blocksize-button"), null, (function(_this) { + return function(value) { + if (_this.app.project.isLocked("maps/" + _this.selected_map + ".json")) { + return; + } + _this.app.project.lockFile("maps/" + _this.selected_map + ".json"); + return _this.saveDimensionChange(); + }; + })(this)); this.map_code_tip = new CodeSnippetField(this.app, "#map-code-tip"); } - mapChanged() { + MapEditor.prototype.mapChanged = function() { var map; if (this.ignore_changes) { return; } - this.app.project.lockFile(`maps/${this.selected_map}.json`); + this.app.project.lockFile("maps/" + this.selected_map + ".json"); this.save_time = Date.now(); this.app.project.addPendingChange(this); map = this.app.project.getMap(this.selected_map); @@ -122,37 +143,40 @@ this.MapEditor = class MapEditor extends Manager { map.updateCanvases(); return this.app.runwindow.updateMap(this.selected_map); } - } + }; - checkSave(immediate = false, callback) { + MapEditor.prototype.checkSave = function(immediate, callback) { + if (immediate == null) { + immediate = false; + } if (this.save_time > 0 && (immediate || Date.now() > this.save_time + this.save_delay)) { this.saveMap(callback); return this.save_time = 0; } - } + }; - forceSave(callback) { + MapEditor.prototype.forceSave = function(callback) { return this.checkSave(true, callback); - } + }; - projectOpened() { - super.projectOpened(); + MapEditor.prototype.projectOpened = function() { + MapEditor.__super__.projectOpened.call(this); this.app.project.addListener(this); return this.setSelectedMap(null); - } + }; - update() { - super.update(); + MapEditor.prototype.update = function() { + MapEditor.__super__.update.call(this); if (this.mapeditor_splitbar.position > 90) { this.mapeditor_splitbar.setPosition(80); } this.mapeditor_splitbar.update(); return this.mapview.windowResized(); - } + }; - projectUpdate(change) { + MapEditor.prototype.projectUpdate = function(change) { var c, name; - super.projectUpdate(change); + MapEditor.__super__.projectUpdate.call(this, change); switch (change) { case "spritelist": this.rebuildSpriteList(); @@ -163,29 +187,29 @@ this.MapEditor = class MapEditor extends Manager { } if (change instanceof ProjectSprite) { name = change.name; - c = document.querySelector(`#map-sprite-image-${name}`); + c = document.querySelector("#map-sprite-image-" + name); if ((c != null) && (c.updateSprite != null)) { return c.updateSprite(); } } - } + }; - updateCurrentFileLock() { + MapEditor.prototype.updateCurrentFileLock = function() { var lock, user; if (this.selected_map != null) { - this.mapview.editable = !this.app.project.isLocked(`maps/${this.selected_map}.json`); + this.mapview.editable = !this.app.project.isLocked("maps/" + this.selected_map + ".json"); } lock = document.getElementById("map-editor-locked"); - if ((this.selected_map != null) && this.app.project.isLocked(`maps/${this.selected_map}.json`)) { - user = this.app.project.isLocked(`maps/${this.selected_map}.json`).user; - lock.style = `display: block; background: ${this.app.appui.createFriendColor(user)}`; - return lock.innerHTML = ` Locked by ${user}`; + if ((this.selected_map != null) && this.app.project.isLocked("maps/" + this.selected_map + ".json")) { + user = this.app.project.isLocked("maps/" + this.selected_map + ".json").user; + lock.style = "display: block; background: " + (this.app.appui.createFriendColor(user)); + return lock.innerHTML = " Locked by " + user; } else { return lock.style = "display: none"; } - } + }; - saveMap(callback) { + MapEditor.prototype.saveMap = function(callback) { var cells, data, map, saved; if ((this.selected_map == null) || !this.mapview.map) { return; @@ -198,35 +222,44 @@ this.MapEditor = class MapEditor extends Manager { this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `maps/${this.selected_map}.json`, + file: "maps/" + this.selected_map + ".json", content: data, cells: cells - }, (msg) => { - saved = true; - if (this.save_time === 0) { - this.app.project.removePendingChange(this); - } - map.size = msg.size; - if (callback != null) { - return callback(); - } - }); - return setTimeout((() => { - if (!saved) { - this.save_time = Date.now(); - return console.info("retrying map save..."); - } - }), 10000); - } + }, (function(_this) { + return function(msg) { + saved = true; + if (_this.save_time === 0) { + _this.app.project.removePendingChange(_this); + } + map.size = msg.size; + if (callback != null) { + return callback(); + } + }; + })(this)); + return setTimeout(((function(_this) { + return function() { + if (!saved) { + _this.save_time = Date.now(); + return console.info("retrying map save..."); + } + }; + })(this)), 10000); + }; - fileDropped(file, folder) {} + MapEditor.prototype.fileDropped = function(file, folder) {}; - // required to enable moving maps to the root folder - createAsset(folder, name = "map", content = "") { + MapEditor.prototype.createAsset = function(folder, name, content) { var map; + if (name == null) { + name = "map"; + } + if (content == null) { + content = ""; + } this.checkSave(true); if (folder != null) { - name = folder.getFullDashPath() + `-${name}`; + name = folder.getFullDashPath() + ("-" + name); folder.setOpen(true); } map = this.app.project.createMap(name); @@ -235,21 +268,23 @@ this.MapEditor = class MapEditor extends Manager { return this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `maps/${name}.json`, + file: "maps/" + name + ".json", properties: {}, content: map.save() - }, (msg) => { - this.app.project.updateMapList(); - return this.setSelectedItem(name); - }); - } + }, (function(_this) { + return function(msg) { + _this.app.project.updateMapList(); + return _this.setSelectedItem(name); + }; + })(this)); + }; - setSelectedItem(name) { + MapEditor.prototype.setSelectedItem = function(name) { this.setSelectedMap(name); - return super.setSelectedItem(name); - } + return MapEditor.__super__.setSelectedItem.call(this, name); + }; - setSelectedMap(map) { + MapEditor.prototype.setSelectedMap = function(map) { var e, m; this.selected_map = map; if (this.selected_map != null) { @@ -276,9 +311,9 @@ this.MapEditor = class MapEditor extends Manager { this.tilepicker.update(); this.setCoordinates(-1, -1); return this.updateCodeTip(); - } + }; - setMap(data) { + MapEditor.prototype.setMap = function(data) { var map; map = MicroMap.loadMap(data, this.app.project.sprite_table); this.mapview.setMap(map); @@ -288,11 +323,11 @@ this.MapEditor = class MapEditor extends Manager { this.map_size_validator.update(); this.map_blocksize_validator.update(); return this.tilepicker.update(); - } + }; - rebuildList() { + MapEditor.prototype.rebuildList = function() { var i, len, m, option, ref, select; - super.rebuildList(); + MapEditor.__super__.rebuildList.call(this); if ((this.selected_map != null) && (this.app.project.getMap(this.selected_map) == null)) { this.setSelectedItem(null); } @@ -315,29 +350,31 @@ this.MapEditor = class MapEditor extends Manager { if (this.map_underlay != null) { select.value = this.map_underlay; } - } + }; - setCoordinates(x, y) { + MapEditor.prototype.setCoordinates = function(x, y) { var e; e = document.getElementById("map-coordinates"); if (x < 0 || y < 0) { return e.innerText = ""; } else { - return e.innerText = `${x} , ${y}`; + return e.innerText = x + " , " + y; } - } + }; - openMap(s) { + MapEditor.prototype.openMap = function(s) { if (this.map_name_change != null) { - return this.saveNameChange(() => { - return this.openMap(s); - }); + return this.saveNameChange((function(_this) { + return function() { + return _this.openMap(s); + }; + })(this)); } this.checkSave(true); return this.setSelectedMap(s); - } + }; - saveDimensionChange() { + MapEditor.prototype.saveDimensionChange = function() { var bh, bw, err, h, w; this.map_dimension_change = null; w = document.getElementById("map-width").value; @@ -379,55 +416,59 @@ this.MapEditor = class MapEditor extends Manager { this.map_size_validator.update(); return this.map_blocksize_validator.update(); } - } + }; - rebuildSpriteList() { + MapEditor.prototype.rebuildSpriteList = function() { var ProjectSpriteClone, folder, i, len, manager, ref, s; if (this.sprite_folder_view == null) { manager = { folder: "sprites", item: "sprite", - openItem: (item) => { - this.mapview.sprite = item; - this.sprite_folder_view.setSelectedItem(item); - return this.tilepicker.update(); - } + openItem: (function(_this) { + return function(item) { + _this.mapview.sprite = item; + _this.sprite_folder_view.setSelectedItem(item); + return _this.tilepicker.update(); + }; + })(this) }; this.sprite_folder_view = new FolderView(manager, document.querySelector("#map-sprite-list")); this.sprite_folder_view.editable = false; } folder = new ProjectFolder(null, "sprites"); - ProjectSpriteClone = class ProjectSpriteClone { - constructor(project_sprite) { + ProjectSpriteClone = (function() { + function ProjectSpriteClone(project_sprite) { this.project_sprite = project_sprite; this.name = this.project_sprite.name; this.shortname = this.project_sprite.shortname; } - getThumbnailElement() { + ProjectSpriteClone.prototype.getThumbnailElement = function() { return this.project_sprite.getThumbnailElement(); - } + }; - canBeRenamed() { + ProjectSpriteClone.prototype.canBeRenamed = function() { return false; - } + }; - }; + return ProjectSpriteClone; + + })(); ref = this.app.project.sprite_list; for (i = 0, len = ref.length; i < len; i++) { s = ref[i]; folder.push(new ProjectSpriteClone(s), s.name); } this.sprite_folder_view.rebuildList(folder); - } + }; - currentMapUpdated() { + MapEditor.prototype.currentMapUpdated = function() { this.mapview.update(); this.mapview.windowResized(); return this.updateSizeFields(); - } + }; - updateSizeFields() { + MapEditor.prototype.updateSizeFields = function() { if (this.mapview.map != null) { document.getElementById("map-width").value = this.mapview.map.width; document.getElementById("map-height").value = this.mapview.map.height; @@ -436,32 +477,34 @@ this.MapEditor = class MapEditor extends Manager { this.map_size_validator.update(); return this.map_blocksize_validator.update(); } - } + }; - undo() { + MapEditor.prototype.undo = function() { var s; - if (this.app.project.isLocked(`maps/${this.selected_map}.json`)) { + if (this.app.project.isLocked("maps/" + this.selected_map + ".json")) { return; } - this.app.project.lockFile(`maps/${this.selected_map}.json`); + this.app.project.lockFile("maps/" + this.selected_map + ".json"); if (this.mapview.map && (this.mapview.map.undo != null)) { - s = this.mapview.map.undo.undo(() => { - return this.mapview.map.clone(); - }); + s = this.mapview.map.undo.undo((function(_this) { + return function() { + return _this.mapview.map.clone(); + }; + })(this)); if (s != null) { this.mapview.map.copyFrom(s); this.currentMapUpdated(); return this.mapChanged(); } } - } + }; - redo() { + MapEditor.prototype.redo = function() { var s; - if (this.app.project.isLocked(`maps/${this.selected_map}.json`)) { + if (this.app.project.isLocked("maps/" + this.selected_map + ".json")) { return; } - this.app.project.lockFile(`maps/${this.selected_map}.json`); + this.app.project.lockFile("maps/" + this.selected_map + ".json"); if (this.mapview.map && (this.mapview.map.undo != null)) { s = this.mapview.map.undo.redo(); if (s != null) { @@ -470,17 +513,17 @@ this.MapEditor = class MapEditor extends Manager { return this.mapChanged(); } } - } + }; - copy() { + MapEditor.prototype.copy = function() { return this.clipboard = this.mapview.map.clone(); - } + }; - cut() { - if (this.app.project.isLocked(`maps/${this.selected_map}.json`)) { + MapEditor.prototype.cut = function() { + if (this.app.project.isLocked("maps/" + this.selected_map + ".json")) { return; } - this.app.project.lockFile(`maps/${this.selected_map}.json`); + this.app.project.lockFile("maps/" + this.selected_map + ".json"); this.clipboard = this.mapview.map.clone(); if (this.mapview.map.undo == null) { this.mapview.map.undo = new Undo(); @@ -492,13 +535,13 @@ this.MapEditor = class MapEditor extends Manager { this.mapview.map.undo.pushState(this.mapview.map.clone()); this.currentMapUpdated(); return this.mapChanged(); - } + }; - paste() { - if (this.app.project.isLocked(`maps/${this.selected_map}.json`)) { + MapEditor.prototype.paste = function() { + if (this.app.project.isLocked("maps/" + this.selected_map + ".json")) { return; } - this.app.project.lockFile(`maps/${this.selected_map}.json`); + this.app.project.lockFile("maps/" + this.selected_map + ".json"); if (this.clipboard != null) { if (this.mapview.map.undo == null) { this.mapview.map.undo = new Undo(); @@ -511,9 +554,9 @@ this.MapEditor = class MapEditor extends Manager { this.currentMapUpdated(); return this.mapChanged(); } - } + }; - updateCodeTip() { + MapEditor.prototype.updateCodeTip = function() { var code, h, map, w; if ((this.selected_map != null) && (this.app.project.getMap(this.selected_map) != null)) { map = this.app.project.getMap(this.selected_map); @@ -524,57 +567,63 @@ this.MapEditor = class MapEditor extends Manager { w = 200; h = Math.round(map.height / map.width * 200); } - code = `screen.drawMap( "${this.selected_map.replace(/-/g, "/")}", 0, 0, ${w}, ${h} )`; + code = "screen.drawMap( \"" + (this.selected_map.replace(/-/g, "/")) + "\", 0, 0, " + w + ", " + h + " )"; } else { code = ""; } return this.map_code_tip.set(code); - } + }; + + return MapEditor; -}; +})(Manager); -this.BackgroundColorPicker = class BackgroundColorPicker { - constructor(editor, callback1, editorid = "map") { +this.BackgroundColorPicker = (function() { + function BackgroundColorPicker(editor, callback1, editorid) { this.editor = editor; this.callback = callback1; - this.editorid = editorid; + this.editorid = editorid != null ? editorid : "map"; this.tool = document.createElement("div"); this.tool.classList.add("value-tool"); this.color = [0, 0, 0]; this.picker = new ColorPicker(this); this.tool.appendChild(this.picker.canvas); this.picker.colorPicked([0, 0, 0]); - document.getElementById(`${this.editorid}s-section`).appendChild(this.tool); + document.getElementById(this.editorid + "s-section").appendChild(this.tool); this.started = true; this.tool.addEventListener("mousedown", function(event) { return event.stopPropagation(); }); - document.addEventListener("mousedown", (event) => { - return this.hide(); - }); + document.addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.hide(); + }; + })(this)); this.hide(); } - setColor(color1) { + BackgroundColorPicker.prototype.setColor = function(color1) { this.color = color1; return this.callback(this.color); - } + }; - hide() { + BackgroundColorPicker.prototype.hide = function() { this.tool.style.display = "none"; return this.shown = false; - } + }; - show() { + BackgroundColorPicker.prototype.show = function() { var e; e = document.getElementById(this.editorid + "-background-color"); this.y = e.getBoundingClientRect().y; this.x = e.getBoundingClientRect().x + e.getBoundingClientRect().width / 2; this.y = Math.max(0, this.y - 100) + document.querySelector("#editor-view .ace_content").getBoundingClientRect().y; this.x = Math.max(0, this.x + 25) + document.querySelector("#editor-view .ace_content").getBoundingClientRect().x; - this.tool.style = `z-index: 20;top:${this.y - 200}px;left:${this.x - 75}px;`; + this.tool.style = "z-index: 20;top:" + (this.y - 200) + "px;left:" + (this.x - 75) + "px;"; this.tool.style.display = "block"; return this.shown = true; - } + }; + + return BackgroundColorPicker; -}; +})(); diff --git a/static/js/music/musiceditor.js b/static/js/music/musiceditor.js index 7c310dde..a5becebe 100644 --- a/static/js/music/musiceditor.js +++ b/static/js/music/musiceditor.js @@ -1,6 +1,11 @@ -this.MusicEditor = class MusicEditor extends Manager { - constructor(app) { - super(app); +var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +this.MusicEditor = (function(superClass) { + extend(MusicEditor, superClass); + + function MusicEditor(app) { + MusicEditor.__super__.constructor.call(this, app); this.folder = "music"; this.item = "music"; this.list_change_event = "musiclist"; @@ -11,87 +16,93 @@ this.MusicEditor = class MusicEditor extends Manager { this.init(); } - openItem(name) { + MusicEditor.prototype.openItem = function(name) { var music; - super.openItem(name); + MusicEditor.__super__.openItem.call(this, name); music = this.app.project.getMusic(name); if (music != null) { return music.play(); } - } + }; - createAsset(folder) { + MusicEditor.prototype.createAsset = function(folder) { var input; input = document.createElement("input"); input.type = "file"; input.accept = ".mp3,.ogg,.flac"; - input.addEventListener("change", (event) => { - var f, files, i, len; - files = event.target.files; - if (files.length >= 1) { - for (i = 0, len = files.length; i < len; i++) { - f = files[i]; - this.fileDropped(f, folder); + input.addEventListener("change", (function(_this) { + return function(event) { + var f, files, i, len; + files = event.target.files; + if (files.length >= 1) { + for (i = 0, len = files.length; i < len; i++) { + f = files[i]; + _this.fileDropped(f, folder); + } } - } - }); + }; + })(this)); return input.click(); - } + }; - fileDropped(file, folder) { + MusicEditor.prototype.fileDropped = function(file, folder) { var reader; - console.info(`processing ${file.name}`); + console.info("processing " + file.name); reader = new FileReader(); - reader.addEventListener("load", () => { - var audioContext, file_size; - file_size = reader.result.byteLength; - console.info("file read, size = " + file_size); - if (file_size > 30000000) { // client-side limit to 30 Mb - this.app.appui.showNotification(this.app.translator.get("Music file is too heavy")); - return; - } - audioContext = new AudioContext(); - return audioContext.decodeAudioData(reader.result, (decoded) => { - var ext, music, name, r2, thumbnailer; - console.info(decoded); - thumbnailer = new SoundThumbnailer(decoded, 192, 64, "hsl(200,80%,60%)"); - name = file.name.split(".")[0]; - ext = file.name.split(".")[1].toLowerCase(); - name = this.findNewFilename(name, "getMusic", folder); - if (folder != null) { - name = folder.getFullDashPath() + "-" + name; + reader.addEventListener("load", (function(_this) { + return function() { + var audioContext, file_size; + file_size = reader.result.byteLength; + console.info("file read, size = " + file_size); + if (file_size > 30000000) { + _this.app.appui.showNotification(_this.app.translator.get("Music file is too heavy")); + return; } - if (folder != null) { - folder.setOpen(true); - } - music = this.app.project.createMusic(name, thumbnailer.canvas.toDataURL(), file_size); - music.uploading = true; - this.setSelectedItem(name); - r2 = new FileReader(); - r2.addEventListener("load", () => { - var data; - music.local_url = r2.result; - data = r2.result.split(",")[1]; - this.app.project.addPendingChange(this); - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: `music/${name}.${ext}`, - properties: {}, - content: data, - thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] - }, (msg) => { - console.info(msg); - this.app.project.removePendingChange(this); - music.uploading = false; - this.app.project.updateMusicList(); - return this.checkNameFieldActivation(); + audioContext = new AudioContext(); + return audioContext.decodeAudioData(reader.result, function(decoded) { + var ext, music, name, r2, thumbnailer; + console.info(decoded); + thumbnailer = new SoundThumbnailer(decoded, 192, 64, "hsl(200,80%,60%)"); + name = file.name.split(".")[0]; + ext = file.name.split(".")[1].toLowerCase(); + name = _this.findNewFilename(name, "getMusic", folder); + if (folder != null) { + name = folder.getFullDashPath() + "-" + name; + } + if (folder != null) { + folder.setOpen(true); + } + music = _this.app.project.createMusic(name, thumbnailer.canvas.toDataURL(), file_size); + music.uploading = true; + _this.setSelectedItem(name); + r2 = new FileReader(); + r2.addEventListener("load", function() { + var data; + music.local_url = r2.result; + data = r2.result.split(",")[1]; + _this.app.project.addPendingChange(_this); + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "music/" + name + "." + ext, + properties: {}, + content: data, + thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] + }, function(msg) { + console.info(msg); + _this.app.project.removePendingChange(_this); + music.uploading = false; + _this.app.project.updateMusicList(); + return _this.checkNameFieldActivation(); + }); }); + return r2.readAsDataURL(file); }); - return r2.readAsDataURL(file); - }); - }); + }; + })(this)); return reader.readAsArrayBuffer(file); - } + }; + + return MusicEditor; -}; +})(Manager); diff --git a/static/js/options/options.js b/static/js/options/options.js index 4d522846..a0622268 100644 --- a/static/js/options/options.js +++ b/static/js/options/options.js @@ -1,68 +1,93 @@ var DEFAULT_CODE; -this.Options = class Options { - constructor(app) { - var advanced, input, j, len, list; +this.Options = (function() { + function Options(app) { + var advanced, fn, input, j, len, list; this.app = app; - this.textInput("projectoption-name", (value) => { - return this.optionChanged("title", value); - }); - this.project_slug_validator = new InputValidator(document.getElementById("projectoption-slug"), document.getElementById("project-slug-button"), null, (value) => { - return this.optionChanged("slug", value[0]); - }); - this.project_code_validator = new InputValidator(document.getElementById("projectoption-code"), document.getElementById("project-code-button"), null, (value) => { - return this.optionChanged("code", value[0]); - }); - this.selectInput("projectoption-orientation", (value) => { - return this.orientationChanged(value); - }); - this.selectInput("projectoption-aspect", (value) => { - return this.aspectChanged(value); - }); - this.selectInput("projectoption-type", (value) => { - return this.typeChanged(value); - }); - this.selectInput("projectoption-graphics", (value) => { - return this.graphicsChanged(value); - }); - this.selectInput("projectoption-graphics-version", (value) => { - return this.graphicsChanged(value); - }); - this.selectInput("projectoption-language", (value) => { - return this.languageChanged(value); - }); - this.checkInput("projectoption-networking", (value) => { - return this.networkingChanged(value); - }); + this.textInput("projectoption-name", (function(_this) { + return function(value) { + return _this.optionChanged("title", value); + }; + })(this)); + this.project_slug_validator = new InputValidator(document.getElementById("projectoption-slug"), document.getElementById("project-slug-button"), null, (function(_this) { + return function(value) { + return _this.optionChanged("slug", value[0]); + }; + })(this)); + this.project_code_validator = new InputValidator(document.getElementById("projectoption-code"), document.getElementById("project-code-button"), null, (function(_this) { + return function(value) { + return _this.optionChanged("code", value[0]); + }; + })(this)); + this.selectInput("projectoption-orientation", (function(_this) { + return function(value) { + return _this.orientationChanged(value); + }; + })(this)); + this.selectInput("projectoption-aspect", (function(_this) { + return function(value) { + return _this.aspectChanged(value); + }; + })(this)); + this.selectInput("projectoption-type", (function(_this) { + return function(value) { + return _this.typeChanged(value); + }; + })(this)); + this.selectInput("projectoption-graphics", (function(_this) { + return function(value) { + return _this.graphicsChanged(value); + }; + })(this)); + this.selectInput("projectoption-graphics-version", (function(_this) { + return function(value) { + return _this.graphicsChanged(value); + }; + })(this)); + this.selectInput("projectoption-language", (function(_this) { + return function(value) { + return _this.languageChanged(value); + }; + })(this)); + this.checkInput("projectoption-networking", (function(_this) { + return function(value) { + return _this.networkingChanged(value); + }; + })(this)); advanced = document.getElementById("advanced-project-options-button"); - advanced.addEventListener("click", () => { - if (advanced.classList.contains("open")) { - advanced.classList.remove("open"); - document.getElementById("advanced-project-options").style.display = "none"; - return advanced.childNodes[1].innerText = this.app.translator.get("Show advanced options"); - } else { - advanced.classList.add("open"); - document.getElementById("advanced-project-options").style.display = "block"; - return advanced.childNodes[1].innerText = this.app.translator.get("Hide advanced options"); - } - }); - this.app.appui.setAction("add-project-user", () => { - return this.addProjectUser(); - }); - document.getElementById("add-project-user-nick").addEventListener("keyup", (event) => { - if (event.keyCode === 13) { - return this.addProjectUser(); - } - }); + advanced.addEventListener("click", (function(_this) { + return function() { + if (advanced.classList.contains("open")) { + advanced.classList.remove("open"); + document.getElementById("advanced-project-options").style.display = "none"; + return advanced.childNodes[1].innerText = _this.app.translator.get("Show advanced options"); + } else { + advanced.classList.add("open"); + document.getElementById("advanced-project-options").style.display = "block"; + return advanced.childNodes[1].innerText = _this.app.translator.get("Hide advanced options"); + } + }; + })(this)); + this.app.appui.setAction("add-project-user", (function(_this) { + return function() { + return _this.addProjectUser(); + }; + })(this)); + document.getElementById("add-project-user-nick").addEventListener("keyup", (function(_this) { + return function(event) { + if (event.keyCode === 13) { + return _this.addProjectUser(); + } + }; + })(this)); list = document.querySelectorAll("#project-option-libs input"); - for (j = 0, len = list.length; j < len; j++) { - input = list[j]; - ((input) => { + fn = (function(_this) { + return function(input) { var id, key, option, ref, value, version_e; id = input.id.split("-"); id = id[id.length - 1]; if (ms_optional_libs[id] != null) { - version_e = document.getElementById(`project-option-lib-${id}-version`); + version_e = document.getElementById("project-option-lib-" + id + "-version"); if (ms_optional_libs[id].versions != null) { ref = ms_optional_libs[id].versions; for (key in ref) { @@ -72,58 +97,67 @@ this.Options = class Options { option.innerText = value.name; version_e.appendChild(option); } - this.selectInput(version_e.id, (value) => { - this.addLib(value); - return this.libsChanged(); + _this.selectInput(version_e.id, function(value) { + _this.addLib(value); + return _this.libsChanged(); }); } else { version_e.style.display = "none"; } } - return input.addEventListener("change", () => { + return input.addEventListener("change", function() { if (input.checked) { - this.addLib(id); - return this.libsChanged(); + _this.addLib(id); + return _this.libsChanged(); } else { - this.removeLib(id); - return this.libsChanged(); + _this.removeLib(id); + return _this.libsChanged(); } }); - })(input); + }; + })(this); + for (j = 0, len = list.length; j < len; j++) { + input = list[j]; + fn(input); } this.library_tip = document.querySelector("#project-option-type .library"); } - textInput(element, action) { + Options.prototype.textInput = function(element, action) { var e; e = document.getElementById(element); - return e.addEventListener("input", (event) => { - return action(e.value); - }); - } + return e.addEventListener("input", (function(_this) { + return function(event) { + return action(e.value); + }; + })(this)); + }; - selectInput(element, action) { + Options.prototype.selectInput = function(element, action) { var e; e = document.getElementById(element); - return e.addEventListener("change", (event) => { - return action(e.options[e.selectedIndex].value); - }); - } + return e.addEventListener("change", (function(_this) { + return function(event) { + return action(e.options[e.selectedIndex].value); + }; + })(this)); + }; - checkInput(element, action) { + Options.prototype.checkInput = function(element, action) { var e; e = document.getElementById(element); - return e.addEventListener("change", (event) => { - return action(e.checked); - }); - } + return e.addEventListener("change", (function(_this) { + return function(event) { + return action(e.checked); + }; + })(this)); + }; - projectOpened() { + Options.prototype.projectOpened = function() { document.getElementById("projectoptions-icon").src = this.app.project.getFullURL() + "icon.png"; - //document.getElementById("projectoptions-icon").setAttribute("src","#{@app.project.getFullURL()}icon.png") document.getElementById("projectoption-name").value = this.app.project.title; this.project_slug_validator.set(this.app.project.slug); - document.getElementById("projectoption-slugprefix").innerText = location.origin.replace(".dev", ".io") + `/${this.app.project.owner.nick}/`; + document.getElementById("projectoption-slugprefix").innerText = location.origin.replace(".dev", ".io") + ("/" + this.app.project.owner.nick + "/"); document.getElementById("projectoption-orientation").value = this.app.project.orientation; document.getElementById("projectoption-aspect").value = this.app.project.aspect; document.getElementById("projectoption-type").value = this.app.project.type || "app"; @@ -141,9 +175,9 @@ this.Options = class Options { document.querySelector("#projectoptions-users-content").style.display = "block"; } return this.updateGraphicsVersion(); - } + }; - updateGraphicsVersion() { + Options.prototype.updateGraphicsVersion = function() { var e, full_id, graphics, id, key, option, ref, ref1, v; e = document.getElementById("projectoption-graphics-version"); full_id = this.app.project.graphics || "M1"; @@ -178,9 +212,9 @@ this.Options = class Options { } else { return e.style.display = "none"; } - } + }; - updateOptionalLibs() { + Options.prototype.updateOptionalLibs = function() { var checked, e, id, input, j, k, key, len, len1, lib, list, optlib, ref, results, v, value, version; list = document.querySelectorAll("#project-option-libs input"); results = []; @@ -190,8 +224,8 @@ this.Options = class Options { id = input.id; id = id.split("-"); id = id[id.length - 1]; - e = document.getElementById(`project-option-lib-${id}`); - v = document.getElementById(`project-option-lib-${id}-version`); + e = document.getElementById("project-option-lib-" + id); + v = document.getElementById("project-option-lib-" + id + "-version"); checked = false; version = null; optlib = null; @@ -230,14 +264,14 @@ this.Options = class Options { } } return results; - } + }; - updateSecretCodeLine() { + Options.prototype.updateSecretCodeLine = function() { this.project_code_validator.set(this.app.project.code); - return document.getElementById("projectoption-codeprefix").innerText = location.origin.replace(".dev", ".io") + `/${this.app.project.owner.nick}/${this.app.project.slug}/`; - } + return document.getElementById("projectoption-codeprefix").innerText = location.origin.replace(".dev", ".io") + ("/" + this.app.project.owner.nick + "/" + this.app.project.slug + "/"); + }; - projectUpdate(name) { + Options.prototype.projectUpdate = function(name) { var icon; if (name === "spritelist") { icon = this.app.project.getSprite("icon"); @@ -245,15 +279,15 @@ this.Options = class Options { return icon.addImage(document.getElementById("projectoptions-icon"), 160); } } - } + }; - update() { + Options.prototype.update = function() { var storage; storage = this.app.appui.displayByteSize(this.app.project.getSize()); return document.getElementById("projectoption-storage-used").innerText = storage; - } + }; - optionChanged(name, value) { + Options.prototype.optionChanged = function(name, value) { if ((value.trim != null) && value.trim().length === 0) { return; } @@ -280,42 +314,48 @@ this.Options = class Options { project: this.app.project.id, option: name, value: value - }, (msg) => { - if (msg.name === "error" && (msg.value != null)) { - switch (name) { - case "title": - document.getElementById("projectoption-name").value = msg.value; - return this.app.project.setTitle(msg.value); - case "slug": - this.project_slug_validator.set(msg.value); - this.app.project.setSlug(msg.value); - return this.updateSecretCodeLine(); + }, (function(_this) { + return function(msg) { + if (msg.name === "error" && (msg.value != null)) { + switch (name) { + case "title": + document.getElementById("projectoption-name").value = msg.value; + return _this.app.project.setTitle(msg.value); + case "slug": + _this.project_slug_validator.set(msg.value); + _this.app.project.setSlug(msg.value); + return _this.updateSecretCodeLine(); + } } - } - }); - } + }; + })(this)); + }; - orientationChanged(value) { + Options.prototype.orientationChanged = function(value) { this.app.project.setOrientation(value); return this.app.client.sendRequest({ name: "set_project_option", project: this.app.project.id, option: "orientation", value: value - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - aspectChanged(value) { + Options.prototype.aspectChanged = function(value) { this.app.project.setAspect(value); return this.app.client.sendRequest({ name: "set_project_option", project: this.app.project.id, option: "aspect", value: value - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - typeChanged(value) { + Options.prototype.typeChanged = function(value) { this.app.project.setType(value); this.library_tip.style.display = value === "library" ? "block" : "none"; this.app.client.sendRequest({ @@ -323,12 +363,14 @@ this.Options = class Options { project: this.app.project.id, option: "type", value: value - }, (msg) => {}); + }, (function(_this) { + return function(msg) {}; + })(this)); this.app.tab_manager.resetPlugins(); return this.app.lib_manager.resetLibs(); - } + }; - graphicsChanged(value) { + Options.prototype.graphicsChanged = function(value) { var graphics, id, key, ref, v; id = value.split("_")[0]; if (id === value) { @@ -337,7 +379,7 @@ this.Options = class Options { ref = graphics.versions; for (key in ref) { v = ref[key]; - if (v.default) { + if (v["default"]) { value = key.toUpperCase(); break; } @@ -352,29 +394,31 @@ this.Options = class Options { project: this.app.project.id, option: "graphics", value: value - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - fixLib(lib) { + Options.prototype.fixLib = function(lib) { var key, ref, value; if ((ms_optional_libs[lib] != null) && ms_optional_libs[lib].versions) { ref = ms_optional_libs[lib].versions; for (key in ref) { value = ref[key]; - if (value.default) { + if (value["default"]) { return key; } } } return lib; - } + }; - addLib(lib) { + Options.prototype.addLib = function(lib) { this.removeLib(lib); return this.app.project.libs.push(this.fixLib(lib)); - } + }; - removeLib(lib) { + Options.prototype.removeLib = function(lib) { var i, id, j, l, ref, results; id = lib.split("_")[0]; results = []; @@ -387,39 +431,43 @@ this.Options = class Options { } } return results; - } + }; - libsChanged() { + Options.prototype.libsChanged = function() { this.optionChanged("libs", this.app.project.libs); return this.updateOptionalLibs(); - } + }; - languageChanged(value) { + Options.prototype.languageChanged = function(value) { if (value !== this.app.project.language) { if (this.app.project.source_list.length === 1 && this.app.project.source_list[0].content.split("\n").length < 20) { if (!this.app.project.language.startsWith("microscript") || !value.startsWith("microscript")) { - ConfirmDialog.confirm(this.app.translator.get("Your current code will be overwritten. Do you wish to proceed?"), this.app.translator.get("OK"), this.app.translator.get("Cancel"), (() => { - this.app.project.setLanguage(value); - this.app.editor.updateLanguage(); - this.app.debug.updateDebuggerVisibility(); - if (DEFAULT_CODE[value] != null) { - this.app.editor.setCode(DEFAULT_CODE[value]); - } else { - this.app.editor.setCode(DEFAULT_CODE["microscript"]); - } - this.app.editor.editorContentsChanged(); - return this.setLanguage(value); - }), (() => { - return document.getElementById("projectoption-language").value = this.app.project.language; - })); + ConfirmDialog.confirm(this.app.translator.get("Your current code will be overwritten. Do you wish to proceed?"), this.app.translator.get("OK"), this.app.translator.get("Cancel"), ((function(_this) { + return function() { + _this.app.project.setLanguage(value); + _this.app.editor.updateLanguage(); + _this.app.debug.updateDebuggerVisibility(); + if (DEFAULT_CODE[value] != null) { + _this.app.editor.setCode(DEFAULT_CODE[value]); + } else { + _this.app.editor.setCode(DEFAULT_CODE["microscript"]); + } + _this.app.editor.editorContentsChanged(); + return _this.setLanguage(value); + }; + })(this)), ((function(_this) { + return function() { + return document.getElementById("projectoption-language").value = _this.app.project.language; + }; + })(this))); return; } } return this.setLanguage(value); } - } + }; - setLanguage(value) { + Options.prototype.setLanguage = function(value) { this.app.project.setLanguage(value); this.app.editor.updateLanguage(); this.app.debug.updateDebuggerVisibility(); @@ -428,10 +476,12 @@ this.Options = class Options { project: this.app.project.id, option: "language", value: value - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - networkingChanged(value) { + Options.prototype.networkingChanged = function(value) { this.app.project.networking = value; this.app.runwindow.updateServerBar(); this.app.publish.updateServerExport(); @@ -440,23 +490,27 @@ this.Options = class Options { project: this.app.project.id, option: "networking", value: value - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - setType(type) { + Options.prototype.setType = function(type) { if (type !== this.app.project.type) { - console.info(`setting type to ${type}`); + console.info("setting type to " + type); this.app.project.setType(type); return this.app.client.sendRequest({ name: "set_project_option", project: this.app.project.id, option: "type", value: type - }, (msg) => {}); + }, (function(_this) { + return function(msg) {}; + })(this)); } - } + }; - addProjectUser() { + Options.prototype.addProjectUser = function() { var nick; nick = document.getElementById("add-project-user-nick").value; if (nick.trim().length > 0) { @@ -464,21 +518,22 @@ this.Options = class Options { name: "invite_to_project", project: this.app.project.id, user: nick - }, (msg) => { - return console.info(msg); - }); + }, (function(_this) { + return function(msg) { + return console.info(msg); + }; + })(this)); return document.getElementById("add-project-user-nick").value = ""; } - } + }; - updateUserList() { - var div, j, len, ref, user; + Options.prototype.updateUserList = function() { + var div, fn, j, len, ref, user; div = document.getElementById("project-user-list"); div.innerHTML = ""; ref = this.app.project.users; - for (j = 0, len = ref.length; j < len; j++) { - user = ref[j]; - ((user) => { + fn = (function(_this) { + return function(user) { var e, name, remove; e = document.createElement("div"); e.classList.add("user"); @@ -488,21 +543,27 @@ this.Options = class Options { remove = document.createElement("div"); remove.classList.add("remove"); remove.innerHTML = " Remove"; - remove.addEventListener("click", (event) => { - return this.app.client.sendRequest({ + remove.addEventListener("click", function(event) { + return _this.app.client.sendRequest({ name: "remove_project_user", - project: this.app.project.id, + project: _this.app.project.id, user: user.nick }); }); e.appendChild(remove); e.appendChild(name); return div.appendChild(e); - })(user); + }; + })(this); + for (j = 0, len = ref.length; j < len; j++) { + user = ref[j]; + fn(user); } - } + }; -}; + return Options; + +})(); DEFAULT_CODE = { python: "def init():\n pass\n\ndef update():\n pass\n\ndef draw():\n pass", diff --git a/static/js/options/tabmanager.js b/static/js/options/tabmanager.js index 5c0f2668..d7805760 100644 --- a/static/js/options/tabmanager.js +++ b/static/js/options/tabmanager.js @@ -1,224 +1,235 @@ this.TabManager = (function() { - class TabManager { - constructor(app) { - this.app = app; - this.initProjectTabSelection(); - this.known_plugins = {}; - this.plugin_views = {}; - } + function TabManager(app) { + this.app = app; + this.initProjectTabSelection(); + this.known_plugins = {}; + this.plugin_views = {}; + } - projectOpened() { - this.updateProjectTabSelection(); - return this.updatePluginSelection(); - } + TabManager.prototype.projectOpened = function() { + this.updateProjectTabSelection(); + return this.updatePluginSelection(); + }; - isTabActive(t) { - var p, tabs; - p = this.app.project; - if (!p) { - return false; - } - tabs = p.tabs || {}; - if (tabs[t] != null) { - return tabs[t]; - } else { - return TabManager.DEFAULT_TABS[t]; - } + TabManager.prototype.isTabActive = function(t) { + var p, tabs; + p = this.app.project; + if (!p) { + return false; + } + tabs = p.tabs || {}; + if (tabs[t] != null) { + return tabs[t]; + } else { + return TabManager.DEFAULT_TABS[t]; } + }; - setTabActive(t, active) { - var p; - p = this.app.project; - if (p.tabs == null) { - p.tabs = {}; - } - p.tabs[t] = active; - this.updateProjectTabs(); - return this.app.client.sendRequest({ - name: "set_project_option", - project: this.app.project.id, - option: "tabs", - value: p.tabs - }, (msg) => {}); + TabManager.prototype.setTabActive = function(t, active) { + var p; + p = this.app.project; + if (p.tabs == null) { + p.tabs = {}; } + p.tabs[t] = active; + this.updateProjectTabs(); + return this.app.client.sendRequest({ + name: "set_project_option", + project: this.app.project.id, + option: "tabs", + value: p.tabs + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - updateProjectTabSelection() { - var element, tab; - for (tab in TabManager.DEFAULT_TABS) { - element = document.getElementById(`project-option-active-tab-${tab}`); - if (element != null) { - element.checked = this.isTabActive(tab); - } + TabManager.prototype.updateProjectTabSelection = function() { + var element, tab; + for (tab in TabManager.DEFAULT_TABS) { + element = document.getElementById("project-option-active-tab-" + tab); + if (element != null) { + element.checked = this.isTabActive(tab); } } + }; - updateProjectTabs() { - var element, i, id, len, list, plugins, tab, value; - for (tab in TabManager.DEFAULT_TABS) { - element = document.getElementById(`menuitem-${tab}`); - if (element != null) { - element.style.display = this.isTabActive(tab) ? "block" : "none"; - } + TabManager.prototype.updateProjectTabs = function() { + var element, i, id, len, list, plugins, tab, value; + for (tab in TabManager.DEFAULT_TABS) { + element = document.getElementById("menuitem-" + tab); + if (element != null) { + element.style.display = this.isTabActive(tab) ? "block" : "none"; } - plugins = this.app.project.plugins || {}; - list = document.querySelectorAll(".menuitem-plugin"); - for (i = 0, len = list.length; i < len; i++) { - element = list[i]; - id = element.id.split("-")[1] * 1; - if (plugins[id] == null) { - element.parentNode.removeChild(element); - if (this.plugin_views[id] != null) { - this.plugin_views[id].close(); - delete this.plugin_views[id]; - } - this.app.documentation.removePlugin(id); - } - } - for (id in plugins) { - value = plugins[id]; - element = document.getElementById(`menuitem-${id}`); - if (!element) { - this.createPluginUI(id); + } + plugins = this.app.project.plugins || {}; + list = document.querySelectorAll(".menuitem-plugin"); + for (i = 0, len = list.length; i < len; i++) { + element = list[i]; + id = element.id.split("-")[1] * 1; + if (plugins[id] == null) { + element.parentNode.removeChild(element); + if (this.plugin_views[id] != null) { + this.plugin_views[id].close(); + delete this.plugin_views[id]; } + this.app.documentation.removePlugin(id); } } - - initProjectTabSelection() { - var tab; - for (tab in TabManager.DEFAULT_TABS) { - ((tab) => { - var element; - element = document.getElementById(`project-option-active-tab-${tab}`); - return element.addEventListener("change", () => { - return this.setTabActive(tab, !this.isTabActive(tab)); - }); - })(tab); + for (id in plugins) { + value = plugins[id]; + element = document.getElementById("menuitem-" + id); + if (!element) { + this.createPluginUI(id); } } + }; - createPluginBox(project) { - var desc, div, e, i, id, len, list, nick, path, plugins, user; - console.info(project); - nick = typeof project.owner === "string" ? project.owner : project.owner.nick; - id = project.id; - path = `/${nick}/${project.slug}`; - if (project.code != null) { - path += `/${project.code}`; - } - this.known_plugins[id] = { - nick: nick, - slug: project.slug, - title: project.title, - code: project.code, - url: `${location.origin}${path}/` + TabManager.prototype.initProjectTabSelection = function() { + var fn, tab; + fn = (function(_this) { + return function(tab) { + var element; + element = document.getElementById("project-option-active-tab-" + tab); + return element.addEventListener("change", function() { + return _this.setTabActive(tab, !_this.isTabActive(tab)); + }); }; - div = document.createElement("div"); - div.classList.add("plugin-box"); - div.dataset.id = id; - desc = project.description; - if (desc.length > 300) { - desc = desc.substring(0, 300) + " (...)"; - } - div.innerHTML = `\n
\n
\n

${project.title}

\n

${DOMPurify.sanitize(marked(desc))}

\n
\n
\n
\n This plugin file access will be restricted to the specified folder (or to the root folder if left blank).\n
\n \n
`; - list = div.getElementsByTagName("a"); - for (i = 0, len = list.length; i < len; i++) { - e = list[i]; - e.target = "_blank"; - } - if (project.owner_info) { - user = this.app.appui.createUserTag(nick, project.owner_info.tier, project.owner_info.profile_image, 20); - } else if (project.owner.nick === this.app.user.nick) { - user = this.app.appui.createUserTag(this.app.user.nick, this.app.user.flags.tier || "", this.app.user.flags.profile_image, 20); - } else { - user = this.app.appui.createUserTag(project.owner.nick, "", false, 20); - } - div.querySelector(".plugin-author").appendChild(user); - div.id = `plugin-box-${id}`; - plugins = this.app.project.plugins || {}; - if ((plugins[id] != null) && (plugins[id].folder != null)) { - div.querySelector("input").value = plugins[id].folder; - } - div.querySelector("input").addEventListener("keydown", (event) => { + })(this); + for (tab in TabManager.DEFAULT_TABS) { + fn(tab); + } + }; + + TabManager.prototype.createPluginBox = function(project) { + var desc, div, e, i, id, len, list, nick, path, plugins, user; + console.info(project); + nick = typeof project.owner === "string" ? project.owner : project.owner.nick; + id = project.id; + path = "/" + nick + "/" + project.slug; + if (project.code != null) { + path += "/" + project.code; + } + this.known_plugins[id] = { + nick: nick, + slug: project.slug, + title: project.title, + code: project.code, + url: "" + location.origin + path + "/" + }; + div = document.createElement("div"); + div.classList.add("plugin-box"); + div.dataset.id = id; + desc = project.description; + if (desc.length > 300) { + desc = desc.substring(0, 300) + " (...)"; + } + div.innerHTML = "\n
\n
\n

" + project.title + "

\n

" + (DOMPurify.sanitize(marked(desc))) + "

\n
\n
\n
\n This plugin file access will be restricted to the specified folder (or to the root folder if left blank).\n
\n \n
"; + list = div.getElementsByTagName("a"); + for (i = 0, len = list.length; i < len; i++) { + e = list[i]; + e.target = "_blank"; + } + if (project.owner_info) { + user = this.app.appui.createUserTag(nick, project.owner_info.tier, project.owner_info.profile_image, 20); + } else if (project.owner.nick === this.app.user.nick) { + user = this.app.appui.createUserTag(this.app.user.nick, this.app.user.flags.tier || "", this.app.user.flags.profile_image, 20); + } else { + user = this.app.appui.createUserTag(project.owner.nick, "", false, 20); + } + div.querySelector(".plugin-author").appendChild(user); + div.id = "plugin-box-" + id; + plugins = this.app.project.plugins || {}; + if ((plugins[id] != null) && (plugins[id].folder != null)) { + div.querySelector("input").value = plugins[id].folder; + } + div.querySelector("input").addEventListener("keydown", (function(_this) { + return function(event) { var prop; if (event.key === "Enter") { - prop = `input_validation_${id}`; - if (this[prop]) { - clearTimeout(this[prop]); + prop = "input_validation_" + id; + if (_this[prop]) { + clearTimeout(_this[prop]); } - this.updatePluginFolder(id); + _this.updatePluginFolder(id); return div.querySelector("input").blur(); } - }); - div.querySelector("input").addEventListener("input", () => { + }; + })(this)); + div.querySelector("input").addEventListener("input", (function(_this) { + return function() { var prop; - prop = `input_validation_${id}`; - if (this[prop]) { - clearTimeout(this[prop]); + prop = "input_validation_" + id; + if (_this[prop]) { + clearTimeout(_this[prop]); } - return this[prop] = setTimeout((() => { - this.updatePluginFolder(id); + return _this[prop] = setTimeout((function() { + _this.updatePluginFolder(id); return div.querySelector("input").blur(); }), 2000); - }); - div.addEventListener("click", () => { + }; + })(this)); + div.addEventListener("click", (function(_this) { + return function() { if (div.querySelector("input") !== document.activeElement) { - return this.togglePlugin(id); + return _this.togglePlugin(id); } - }); - return div; - } + }; + })(this)); + return div; + }; - togglePlugin(id) { - var folder; - if (this.isPluginActive(id)) { - return this.setPluginActive(id, false); - } else { - folder = RegexLib.fixFilePath(document.querySelector(`#plugin-box-${id} input`).value); - return this.setPluginActive(id, true, folder); - } + TabManager.prototype.togglePlugin = function(id) { + var folder; + if (this.isPluginActive(id)) { + return this.setPluginActive(id, false); + } else { + folder = RegexLib.fixFilePath(document.querySelector("#plugin-box-" + id + " input").value); + return this.setPluginActive(id, true, folder); } + }; - updatePluginFolder(id) { - var e; - if (this.isPluginActive(id)) { - e = document.querySelector(`#plugin-box-${id} input`); - e.value = RegexLib.fixFilePath(e.value); - this.setPluginActive(id, true, e.value); - if (this.plugin_views[id] != null) { - return this.plugin_views[id].setFolder(e.value); - } + TabManager.prototype.updatePluginFolder = function(id) { + var e; + if (this.isPluginActive(id)) { + e = document.querySelector("#plugin-box-" + id + " input"); + e.value = RegexLib.fixFilePath(e.value); + this.setPluginActive(id, true, e.value); + if (this.plugin_views[id] != null) { + return this.plugin_views[id].setFolder(e.value); } } + }; - resetPlugins() { - return this.plugins_fetched = false; - } + TabManager.prototype.resetPlugins = function() { + return this.plugins_fetched = false; + }; - fetchAvailablePlugins(callback) { - var box, i, len, p, ref, your_list, your_plugins; - if (this.plugins_fetched) { - return callback(); - } - this.plugins_fetched = true; - your_plugins = document.querySelector("#project-tabs-your-plugins"); - your_list = document.querySelector("#project-tabs-your-plugins .plugin-list"); - your_list.innerHTML = ""; - ref = this.app.projects; - for (i = 0, len = ref.length; i < len; i++) { - p = ref[i]; - if (p.type === "plugin") { - box = this.createPluginBox(p); - your_list.appendChild(box); - } - } - if (your_list.childNodes.length === 0) { - your_plugins.style.display = "none"; - } else { - your_plugins.style.display = "block"; + TabManager.prototype.fetchAvailablePlugins = function(callback) { + var box, i, len, p, ref, your_list, your_plugins; + if (this.plugins_fetched) { + return callback(); + } + this.plugins_fetched = true; + your_plugins = document.querySelector("#project-tabs-your-plugins"); + your_list = document.querySelector("#project-tabs-your-plugins .plugin-list"); + your_list.innerHTML = ""; + ref = this.app.projects; + for (i = 0, len = ref.length; i < len; i++) { + p = ref[i]; + if (p.type === "plugin") { + box = this.createPluginBox(p); + your_list.appendChild(box); } - return this.app.client.sendRequest({ - name: "get_public_plugins" - }, (msg) => { + } + if (your_list.childNodes.length === 0) { + your_plugins.style.display = "none"; + } else { + your_plugins.style.display = "block"; + } + return this.app.client.sendRequest({ + name: "get_public_plugins" + }, (function(_this) { + return function(msg) { var j, len1, public_list, public_plugins, ref1; console.info(msg.list); public_plugins = document.querySelector("#project-tabs-public-plugins"); @@ -226,8 +237,8 @@ this.TabManager = (function() { ref1 = msg.list; for (j = 0, len1 = ref1.length; j < len1; j++) { p = ref1[j]; - if (this.known_plugins[p.id] == null) { - box = this.createPluginBox(p); + if (_this.known_plugins[p.id] == null) { + box = _this.createPluginBox(p); public_list.appendChild(box); } } @@ -237,14 +248,16 @@ this.TabManager = (function() { public_plugins.style.display = "block"; } return callback(); - }); - } + }; + })(this)); + }; - updatePluginSelection() { - return this.fetchAvailablePlugins(() => { + TabManager.prototype.updatePluginSelection = function() { + return this.fetchAvailablePlugins((function(_this) { + return function() { var e, i, len, list, plugins; list = document.querySelectorAll(".plugin-box"); - plugins = this.app.project.plugins || {}; + plugins = _this.app.project.plugins || {}; for (i = 0, len = list.length; i < len; i++) { e = list[i]; if (plugins[e.dataset.id]) { @@ -253,109 +266,115 @@ this.TabManager = (function() { e.classList.remove("selected"); } } - this.updateProjectTabs(); - }); + _this.updateProjectTabs(); + }; + })(this)); + }; + + TabManager.prototype.isPluginActive = function(id) { + var p, plugins; + p = this.app.project; + if (!p) { + return false; } + plugins = p.plugins || {}; + return plugins[id] != null; + }; - isPluginActive(id) { - var p, plugins; - p = this.app.project; - if (!p) { - return false; - } - plugins = p.plugins || {}; - return plugins[id] != null; + TabManager.prototype.setPluginActive = function(id, active, folder) { + var p; + if (folder == null) { + folder = "plugin"; + } + p = this.app.project; + if (p.plugins == null) { + p.plugins = {}; + } + if (active) { + p.plugins[id] = { + folder: folder + }; + } else { + delete p.plugins[id]; } + this.updatePluginSelection(); + this.updateProjectTabs(); + return this.app.client.sendRequest({ + name: "set_project_option", + project: this.app.project.id, + option: "plugins", + value: p.plugins + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - setPluginActive(id, active, folder = "plugin") { - var p; - p = this.app.project; - if (p.plugins == null) { - p.plugins = {}; - } - if (active) { - p.plugins[id] = { - folder: folder - }; - } else { - delete p.plugins[id]; - } - this.updatePluginSelection(); - this.updateProjectTabs(); - return this.app.client.sendRequest({ - name: "set_project_option", - project: this.app.project.id, - option: "plugins", - value: p.plugins - }, (msg) => {}); + TabManager.prototype.createPluginUI = function(id) { + var data, doc_url, last, li, parent, path; + data = this.known_plugins[id]; + if (data == null) { + return; } + if (data.code != null) { + path = data.nick + "/" + data.slug + "/" + data.code; + } else { + path = data.nick + "/" + data.slug; + } + li = document.createElement("li"); + li.classList.add("menuitem-plugin"); + li.id = "menuitem-" + id; + li.innerHTML = "\n
\n" + data.title + ""; + parent = document.querySelector("#sidemenu ul"); + last = document.getElementById("menuitem-tabs"); + li.addEventListener("click", (function(_this) { + return function() { + return _this.app.appui.setSection(id); + }; + })(this)); + parent.insertBefore(li, last); + doc_url = location.origin + "/" + path + "/doc/doc.md"; + return this.app.documentation.addPlugin(id, data.title, doc_url); + }; - createPluginUI(id) { - var data, doc_url, last, li, parent, path; + TabManager.prototype.setTabView = function(id) { + var data, ref, settings, view, viewid; + ref = this.plugin_views; + for (viewid in ref) { + view = ref[viewid]; + if (viewid !== id) { + view.hide(); + } + } + view = this.plugin_views[id]; + if (view == null) { data = this.known_plugins[id]; if (data == null) { return; } - if (data.code != null) { - path = `${data.nick}/${data.slug}/${data.code}`; - } else { - path = `${data.nick}/${data.slug}`; + settings = this.app.project.plugins[id]; + if (settings == null) { + return; } - li = document.createElement("li"); - li.classList.add("menuitem-plugin"); - li.id = `menuitem-${id}`; - li.innerHTML = `\n
\n${data.title}`; - parent = document.querySelector("#sidemenu ul"); - last = document.getElementById("menuitem-tabs"); - li.addEventListener("click", () => { - return this.app.appui.setSection(id); - }); - parent.insertBefore(li, last); - doc_url = `${location.origin}/${path}/doc/doc.md`; - return this.app.documentation.addPlugin(id, data.title, doc_url); + data.folder = settings.folder; + this.plugin_views[id] = view = new PluginView(this.app, data); } + return view.show(); + }; - setTabView(id) { - var data, ref, settings, view, viewid; - ref = this.plugin_views; - for (viewid in ref) { - view = ref[viewid]; - if (viewid !== id) { - view.hide(); - } - } - view = this.plugin_views[id]; - if (view == null) { - data = this.known_plugins[id]; - if (data == null) { - return; - } - settings = this.app.project.plugins[id]; - if (settings == null) { - return; - } - data.folder = settings.folder; - this.plugin_views[id] = view = new PluginView(this.app, data); - } - return view.show(); + TabManager.prototype.projectClosed = function() { + var element, i, id, len, list, ref, view; + ref = this.plugin_views; + for (id in ref) { + view = ref[id]; + view.close(); } - - projectClosed() { - var element, i, id, len, list, ref, view; - ref = this.plugin_views; - for (id in ref) { - view = ref[id]; - view.close(); - } - list = document.querySelectorAll(".menuitem-plugin"); - for (i = 0, len = list.length; i < len; i++) { - element = list[i]; - element.parentNode.removeChild(element); - } - this.plugin_views = {}; - this.app.documentation.removeAllPlugins(); + list = document.querySelectorAll(".menuitem-plugin"); + for (i = 0, len = list.length; i < len; i++) { + element = list[i]; + element.parentNode.removeChild(element); } - + this.plugin_views = {}; + this.app.documentation.removeAllPlugins(); }; TabManager.DEFAULT_TABS = { @@ -372,4 +391,4 @@ this.TabManager = (function() { return TabManager; -}).call(this); +})(); diff --git a/static/js/play/playerclient.js b/static/js/play/playerclient.js index b0b2fbb2..3327642f 100644 --- a/static/js/play/playerclient.js +++ b/static/js/play/playerclient.js @@ -1,5 +1,5 @@ -this.PlayerClient = class PlayerClient { - constructor(player) { +this.PlayerClient = (function() { + function PlayerClient(player) { var err; this.player = player; this.pending_requests = {}; @@ -13,137 +13,135 @@ this.PlayerClient = class PlayerClient { err = error; console.error(err); } - setInterval((() => { - if (this.socket != null) { - return this.sendRequest({ - name: "ping" - }); - } - }), 30000); + setInterval(((function(_this) { + return function() { + if (_this.socket != null) { + return _this.sendRequest({ + name: "ping" + }); + } + }; + })(this)), 30000); } } - connect() { + PlayerClient.prototype.connect = function() { this.socket = new WebSocket(window.location.origin.replace("http", "ws")); - this.socket.onmessage = (msg) => { - var err; - console.info("received: " + msg.data); - try { - msg = JSON.parse(msg.data); - if (msg.request_id != null) { - if (this.pending_requests[msg.request_id] != null) { - this.pending_requests[msg.request_id](msg); - delete this.pending_requests[msg.request_id]; + this.socket.onmessage = (function(_this) { + return function(msg) { + var err; + console.info("received: " + msg.data); + try { + msg = JSON.parse(msg.data); + if (msg.request_id != null) { + if (_this.pending_requests[msg.request_id] != null) { + _this.pending_requests[msg.request_id](msg); + delete _this.pending_requests[msg.request_id]; + } } + if (msg.name === "project_file_updated") { + _this.player.runtime.projectFileUpdated(msg.type, msg.file, msg.version, msg.data, msg.properties); + } + if (msg.name === "project_file_deleted") { + _this.player.runtime.projectFileDeleted(msg.type, msg.file); + } + if (msg.name === "project_options_updated") { + return _this.player.runtime.projectOptionsUpdated(msg); + } + } catch (error) { + err = error; + return console.error(err); } - //if msg.name == "code_updated" - // @player.runtime.updateSource(msg.file,msg.code,true) - - //if msg.name == "sprite_updated" - // @player.runtime.updateSprite(msg.sprite) - if (msg.name === "project_file_updated") { - this.player.runtime.projectFileUpdated(msg.type, msg.file, msg.version, msg.data, msg.properties); - } - if (msg.name === "project_file_deleted") { - this.player.runtime.projectFileDeleted(msg.type, msg.file); - } - if (msg.name === "project_options_updated") { - return this.player.runtime.projectOptionsUpdated(msg); - } - } catch (error) { - err = error; - return console.error(err); - } - }; - this.socket.onopen = () => { - var i, j, k, l, len, len1, len2, len3, m, maps, project, ref, ref1, ref2, ref3, s, sources, sprites, user; - //console.info "socket opened" - this.reconnect_delay = 1000; - user = location.pathname.split("/")[1]; - project = location.pathname.split("/")[2]; - if (this.buffer != null) { - ref = this.buffer; - for (i = 0, len = ref.length; i < len; i++) { - m = ref[i]; - this.send(m); - } - delete this.buffer; - } - this.send({ - name: "listen_to_project", - user: user, - project: project - }); - if (!this.version_checked) { - this.version_checked = true; - sprites = {}; - maps = {}; - sources = {}; - ref1 = this.player.resources.images; - for (j = 0, len1 = ref1.length; j < len1; j++) { - s = ref1[j]; - sprites[s.file.split(".")[0]] = s.version; - } - ref2 = this.player.resources.maps; - for (k = 0, len2 = ref2.length; k < len2; k++) { - s = ref2[k]; - maps[s.file.split(".")[0]] = s.version; - } - ref3 = this.player.resources.sources; - for (l = 0, len3 = ref3.length; l < len3; l++) { - s = ref3[l]; - sources[s.file.split(".")[0]] = s.version; + }; + })(this); + this.socket.onopen = (function(_this) { + return function() { + var i, j, k, l, len, len1, len2, len3, m, maps, project, ref, ref1, ref2, ref3, s, sources, sprites, user; + _this.reconnect_delay = 1000; + user = location.pathname.split("/")[1]; + project = location.pathname.split("/")[2]; + if (_this.buffer != null) { + ref = _this.buffer; + for (i = 0, len = ref.length; i < len; i++) { + m = ref[i]; + _this.send(m); + } + delete _this.buffer; } - return this.sendRequest({ - name: "get_file_versions", + _this.send({ + name: "listen_to_project", user: user, project: project - }, (msg) => { - var info, name, ref4, ref5, ref6, results, v; - ref4 = msg.data.sources; - for (name in ref4) { - info = ref4[name]; - v = sources[name]; - if ((v == null) || v !== info.version) { - //console.info "updating #{name} to version #{version}" - this.player.runtime.projectFileUpdated("ms", name, info.version, null, info.properties); - } + }); + if (!_this.version_checked) { + _this.version_checked = true; + sprites = {}; + maps = {}; + sources = {}; + ref1 = _this.player.resources.images; + for (j = 0, len1 = ref1.length; j < len1; j++) { + s = ref1[j]; + sprites[s.file.split(".")[0]] = s.version; } - ref5 = msg.data.sprites; - for (name in ref5) { - info = ref5[name]; - v = sprites[name]; - if ((v == null) || v !== info.version) { - //console.info "updating #{name} to version #{version}" - this.player.runtime.projectFileUpdated("sprites", name, info.version, null, info.properties); - } + ref2 = _this.player.resources.maps; + for (k = 0, len2 = ref2.length; k < len2; k++) { + s = ref2[k]; + maps[s.file.split(".")[0]] = s.version; } - ref6 = msg.data.maps; - results = []; - for (name in ref6) { - info = ref6[name]; - v = maps[name]; - if ((v == null) || v !== info.version) { - //console.info "updating #{name} to version #{version}" - results.push(this.player.runtime.projectFileUpdated("maps", name, info.version, null, info.properties)); - } else { - results.push(void 0); - } + ref3 = _this.player.resources.sources; + for (l = 0, len3 = ref3.length; l < len3; l++) { + s = ref3[l]; + sources[s.file.split(".")[0]] = s.version; } - return results; - }); - } - }; - return this.socket.onclose = () => { - //console.info "socket closed" - setTimeout((() => { - return this.connect(); - }), this.reconnect_delay); - return this.reconnect_delay += 1000; - }; - } + return _this.sendRequest({ + name: "get_file_versions", + user: user, + project: project + }, function(msg) { + var info, name, ref4, ref5, ref6, results, v; + ref4 = msg.data.sources; + for (name in ref4) { + info = ref4[name]; + v = sources[name]; + if ((v == null) || v !== info.version) { + _this.player.runtime.projectFileUpdated("ms", name, info.version, null, info.properties); + } + } + ref5 = msg.data.sprites; + for (name in ref5) { + info = ref5[name]; + v = sprites[name]; + if ((v == null) || v !== info.version) { + _this.player.runtime.projectFileUpdated("sprites", name, info.version, null, info.properties); + } + } + ref6 = msg.data.maps; + results = []; + for (name in ref6) { + info = ref6[name]; + v = maps[name]; + if ((v == null) || v !== info.version) { + results.push(_this.player.runtime.projectFileUpdated("maps", name, info.version, null, info.properties)); + } else { + results.push(void 0); + } + } + return results; + }); + } + }; + })(this); + return this.socket.onclose = (function(_this) { + return function() { + setTimeout((function() { + return _this.connect(); + }), _this.reconnect_delay); + return _this.reconnect_delay += 1000; + }; + })(this); + }; - send(data) { + PlayerClient.prototype.send = function(data) { if (this.socket.readyState !== 1) { if (this.buffer == null) { this.buffer = []; @@ -152,12 +150,14 @@ this.PlayerClient = class PlayerClient { } else { return this.socket.send(JSON.stringify(data)); } - } + }; - sendRequest(msg, callback) { + PlayerClient.prototype.sendRequest = function(msg, callback) { msg.request_id = this.request_id++; this.pending_requests[msg.request_id] = callback; return this.send(msg); - } + }; + + return PlayerClient; -}; +})(); diff --git a/static/js/play/server.js b/static/js/play/server.js index b8577362..bdfec194 100644 --- a/static/js/play/server.js +++ b/static/js/play/server.js @@ -1,8 +1,7 @@ -this.Player = class Player { - constructor(listener) { +this.Player = (function() { + function Player(listener) { var i, len, ref, source; this.listener = listener; - //src = document.getElementById("code").innerText this.source_count = 0; this.sources = {}; this.resources = resources; @@ -20,36 +19,40 @@ this.Player = class Player { } } - loadSource(source) { + Player.prototype.loadSource = function(source) { var req; req = new XMLHttpRequest(); - req.onreadystatechange = (event) => { - var name; - if (req.readyState === XMLHttpRequest.DONE) { - if (req.status === 200) { - name = source.file.split(".")[0]; - this.sources[name] = req.responseText; - this.source_count++; - if (this.source_count >= resources.sources.length && (this.runtime == null)) { - return this.start(); + req.onreadystatechange = (function(_this) { + return function(event) { + var name; + if (req.readyState === XMLHttpRequest.DONE) { + if (req.status === 200) { + name = source.file.split(".")[0]; + _this.sources[name] = req.responseText; + _this.source_count++; + if (_this.source_count >= resources.sources.length && (_this.runtime == null)) { + return _this.start(); + } } } - } - }; - req.open("GET", location.origin + location.pathname + `ms/${source.file}?v=${source.version}`); + }; + })(this); + req.open("GET", location.origin + location.pathname + ("ms/" + source.file + "?v=" + source.version)); return req.send(); - } + }; - start() { - window.addEventListener("message", (msg) => { - return this.messageReceived(msg); - }); + Player.prototype.start = function() { + window.addEventListener("message", (function(_this) { + return function(msg) { + return _this.messageReceived(msg); + }; + })(this)); return this.postMessage({ name: "get_token" }); - } + }; - serverStart() { + Player.prototype.serverStart = function() { this.runtime = new Runtime((window.exported_project ? "" : location.origin + location.pathname), this.sources, resources, this); this.client = new PlayerClient(this); this.terminal = new Terminal(this); @@ -58,43 +61,45 @@ this.Player = class Player { return this.postMessage({ name: "focus" }); - } + }; - runCommand(cmd) { + Player.prototype.runCommand = function(cmd) { if (cmd.trim().length === 0) { return; } - return this.runtime.runCommand(cmd, (res) => { - if (!cmd.trim().startsWith("print")) { - return this.terminal.echo(res); - } - }); - } + return this.runtime.runCommand(cmd, (function(_this) { + return function(res) { + if (!cmd.trim().startsWith("print")) { + return _this.terminal.echo(res); + } + }; + })(this)); + }; - reportError(err) { + Player.prototype.reportError = function(err) { return this.postMessage({ name: "error", data: err }); - } + }; - log(text) { + Player.prototype.log = function(text) { return this.terminal.echo(text); - } + }; - codePaused() { + Player.prototype.codePaused = function() { return this.postMessage({ name: "code_paused" }); - } + }; - exit() { + Player.prototype.exit = function() { return this.postMessage({ name: "exit" }); - } + }; - messageReceived(msg) { + Player.prototype.messageReceived = function(msg) { var code, data, err, file; data = msg.data; try { @@ -104,15 +109,17 @@ this.Player = class Player { window.ms_server_token = data.token; return this.serverStart(); case "command": - return this.runtime.runCommand(data.line, (res) => { - if (!data.line.trim().startsWith("print")) { - return this.postMessage({ - name: "output", - data: res, - id: data.id - }); - } - }); + return this.runtime.runCommand(data.line, (function(_this) { + return function(res) { + if (!data.line.trim().startsWith("print")) { + return _this.postMessage({ + name: "output", + data: res, + id: data.id + }); + } + }; + })(this)); case "pause": return this.runtime.stop(); case "step_forward": @@ -150,27 +157,27 @@ this.Player = class Player { err = error; return console.error(err); } - } + }; - call(name, args) { + Player.prototype.call = function(name, args) { if ((this.runtime != null) && (this.runtime.vm != null)) { return this.runtime.vm.call(name, args); } - } + }; - setGlobal(name, value) { + Player.prototype.setGlobal = function(name, value) { if ((this.runtime != null) && (this.runtime.vm != null)) { return this.runtime.vm.context.global[name] = value; } - } + }; - exec(command, callback) { + Player.prototype.exec = function(command, callback) { if (this.runtime != null) { return this.runtime.runCommand(command, callback); } - } + }; - postMessage(data) { + Player.prototype.postMessage = function(data) { var err; if (window !== window.parent) { window.parent.postMessage(JSON.stringify(data), "*"); @@ -183,12 +190,14 @@ this.Player = class Player { return console.error(err); } } - } + }; - postRequest(data, callback) { + Player.prototype.postRequest = function(data, callback) { data.request_id = this.request_id; this.pending_requests[this.request_id++] = callback; return this.postMessage(data); - } + }; + + return Player; -}; +})(); diff --git a/static/js/play/server_export/mpserver.js b/static/js/play/server_export/mpserver.js index 8a6e6aa4..1d4d9df1 100644 --- a/static/js/play/server_export/mpserver.js +++ b/static/js/play/server_export/mpserver.js @@ -2,8 +2,8 @@ var WebSocket; WebSocket = require("ws"); -this.MPServer = class MPServer { - constructor() { +this.MPServer = (function() { + function MPServer() { var impl; impl = new MPServerImpl(this); this.send = function(data) { @@ -33,12 +33,14 @@ this.MPServer = class MPServer { player.runtime.addServer(impl); } -}; + return MPServer; -this.MPServerImpl = class MPServerImpl { - constructor(_interface) { - this.interface = _interface; - this.interface.status = "starting"; +})(); + +this.MPServerImpl = (function() { + function MPServerImpl(_interface) { + this["interface"] = _interface; + this["interface"].status = "starting"; this.reconnect_delay = 1000; this.clients = {}; this.clients_connected = []; @@ -47,30 +49,32 @@ this.MPServerImpl = class MPServerImpl { this.start(); } - start() { + MPServerImpl.prototype.start = function() { var err; try { this.server = new WebSocket.Server({ port: server_port }); - return this.server.on("connection", (socket, request) => { - return this.clientConnected(socket); - }); + return this.server.on("connection", (function(_this) { + return function(socket, request) { + return _this.clientConnected(socket); + }; + })(this)); } catch (error) { err = error; return console.error(err); } - } + }; - clientConnected(socket) { + MPServerImpl.prototype.clientConnected = function(socket) { var client; client = new MPClient(this, socket, this.client_id); this.clients_connected.push(client); this.clients[this.client_id] = client; return this.client_id++; - } + }; - clientMessage(msg) { + MPServerImpl.prototype.clientMessage = function(msg) { var client; if (msg.client_id == null) { return; @@ -79,43 +83,43 @@ this.MPServerImpl = class MPServerImpl { if (client != null) { return client.message(msg.data); } - } + }; - clientDisconnected(client) { + MPServerImpl.prototype.clientDisconnected = function(client) { delete this.clients[client.client_id]; return this.clients_disconnected[client.client_id] = true; - } + }; - sendMessage(data) { + MPServerImpl.prototype.sendMessage = function(data) { return this.send({ name: "mp_server_message", data: data }); - } + }; - send(data) { + MPServerImpl.prototype.send = function(data) { return this.socket.send(JSON.stringify(data)); - } + }; - update() { + MPServerImpl.prototype.update = function() { var c, client, closed_connections, connection, i, id, j, k, l, len, len1, len2, m, messages, n, new_connections, ref, ref1, ref2, ref3, ref4; new_connections = []; closed_connections = []; - for (i = j = ref = this.interface.active_connections.length - 1; j >= 0; i = j += -1) { - c = this.interface.active_connections[i]; + for (i = j = ref = this["interface"].active_connections.length - 1; j >= 0; i = j += -1) { + c = this["interface"].active_connections[i]; if (this.clients_disconnected[c.id]) { - this.interface.active_connections.splice(i, 1); + this["interface"].active_connections.splice(i, 1); closed_connections.push(c); } } ref1 = this.clients_connected; for (k = 0, len = ref1.length; k < len; k++) { c = ref1[k]; - new_connections.push(c.interface); - this.interface.active_connections.push(c.interface); + new_connections.push(c["interface"]); + this["interface"].active_connections.push(c["interface"]); } - this.interface.new_connections = new_connections; - this.interface.closed_connections = closed_connections; + this["interface"].new_connections = new_connections; + this["interface"].closed_connections = closed_connections; this.clients_disconnected = {}; this.clients_connected = []; ref2 = this.clients; @@ -124,7 +128,7 @@ this.MPServerImpl = class MPServerImpl { client.update(); } messages = []; - ref3 = this.interface.active_connections; + ref3 = this["interface"].active_connections; for (l = 0, len1 = ref3.length; l < len1; l++) { connection = ref3[l]; ref4 = connection.messages; @@ -133,65 +137,74 @@ this.MPServerImpl = class MPServerImpl { messages.push(m); } } - this.interface.messages = messages; - } + this["interface"].messages = messages; + }; - close() { + MPServerImpl.prototype.close = function() { return this.socket.close(); - } + }; + + return MPServerImpl; -}; +})(); -this.MPClient = class MPClient { - constructor(server, socket1, client_id) { +this.MPClient = (function() { + function MPClient(server, socket1, client_id) { this.server = server; this.socket = socket1; this.client_id = client_id; - this.interface = { + this["interface"] = { id: this.client_id, status: "connected", messages: [], - send: (data) => { - return this.sendMessage(data); - }, - disconnect: () => { - return this.disconnect(); - } + send: (function(_this) { + return function(data) { + return _this.sendMessage(data); + }; + })(this), + disconnect: (function(_this) { + return function() { + return _this.disconnect(); + }; + })(this) }; this.message_buffer = []; - this.socket.onmessage = (msg) => { - var err; - try { - // console.info msg.data - msg = JSON.parse(msg.data); - switch (msg.name) { - case "mp_update": - this.interface.status = "running"; - return player.runtime.timer(); - case "mp_client_connection": - return this.clientConnected(msg); - case "mp_client_message": - return this.clientMessage(msg); - case "mp_client_disconnected": - return this.disconnected(); + this.socket.onmessage = (function(_this) { + return function(msg) { + var err; + try { + msg = JSON.parse(msg.data); + switch (msg.name) { + case "mp_update": + _this["interface"].status = "running"; + return player.runtime.timer(); + case "mp_client_connection": + return _this.clientConnected(msg); + case "mp_client_message": + return _this.clientMessage(msg); + case "mp_client_disconnected": + return _this.disconnected(); + } + } catch (error) { + err = error; + return console.error(err); } - } catch (error) { - err = error; - return console.error(err); - } - }; - this.socket.onclose = () => { - return this.server.clientDisconnected(this); - }; + }; + })(this); + this.socket.onclose = (function(_this) { + return function() { + return _this.server.clientDisconnected(_this); + }; + })(this); } - clientConnected(msg) {} + MPClient.prototype.clientConnected = function(msg) {}; - clientMessage(msg) { + MPClient.prototype.clientMessage = function(msg) { return this.message_buffer.push(msg.data); - } + }; - sendMessage(data) { + MPClient.prototype.sendMessage = function(data) { var err; try { return this.socket.send(JSON.stringify({ @@ -202,9 +215,9 @@ this.MPClient = class MPClient { err = error; return console.error(err); } - } + }; - disconnect() { + MPClient.prototype.disconnect = function() { var err; try { return this.socket.close(); @@ -212,29 +225,31 @@ this.MPClient = class MPClient { err = error; return console.error(err); } - } + }; - message(msg) { + MPClient.prototype.message = function(msg) { return this.message_buffer.push(msg.data); - } + }; - disconnected() { - return this.interface.status = "disconnected"; - } + MPClient.prototype.disconnected = function() { + return this["interface"].status = "disconnected"; + }; - update() { + MPClient.prototype.update = function() { var j, len, m, messages, ref; messages = []; ref = this.message_buffer; for (j = 0, len = ref.length; j < len; j++) { m = ref[j]; messages.push({ - connection: this.interface, + connection: this["interface"], data: m }); } - this.interface.messages = messages; + this["interface"].messages = messages; return this.message_buffer = []; - } + }; + + return MPClient; -}; +})(); diff --git a/static/js/play/server_export/server.js b/static/js/play/server_export/server.js index 9c0c9c5c..87146a5c 100644 --- a/static/js/play/server_export/server.js +++ b/static/js/play/server_export/server.js @@ -1,85 +1,96 @@ -this.Player = class Player { - constructor(listener) { +this.Player = (function() { + function Player(listener) { this.listener = listener; - //src = document.getElementById("code").innerText this.source_count = 0; this.sources = {}; this.resources = resources; this.request_id = 1; this.pending_requests = {}; this.sources.main = server_code; - // player = new Player() must return before the server is started - // to ensure global.player is defined - setTimeout((() => { - return this.start(); - }), 1); + setTimeout(((function(_this) { + return function() { + return _this.start(); + }; + })(this)), 1); } - start() { + Player.prototype.start = function() { this.runtime = new Runtime("", this.sources, resources, this); this.terminal = new Terminal(this); this.terminal.start(); this.runtime.start(); - return setInterval((() => { - return this.runtime.clock(); - }), 16); - } + return setInterval(((function(_this) { + return function() { + return _this.runtime.clock(); + }; + })(this)), 16); + }; - runCommand(cmd) {} + Player.prototype.runCommand = function(cmd) {}; - reportError(err) { + Player.prototype.reportError = function(err) { return this.terminal.error(err); - } + }; - log(text) { + Player.prototype.log = function(text) { return this.terminal.echo(text); - } + }; - exit() {} + Player.prototype.exit = function() {}; - call(name, args) { + Player.prototype.call = function(name, args) { if ((this.runtime != null) && (this.runtime.vm != null)) { return this.runtime.vm.call(name, args); } - } + }; - setGlobal(name, value) { + Player.prototype.setGlobal = function(name, value) { if ((this.runtime != null) && (this.runtime.vm != null)) { return this.runtime.vm.context.global[name] = value; } - } + }; - exec(command, callback) { + Player.prototype.exec = function(command, callback) { if (this.runtime != null) { return this.runtime.runCommand(command, callback); } - } + }; - postMessage(message) { + Player.prototype.postMessage = function(message) { return console.info(JSON.stringify(message)); - } + }; -}; + return Player; -this.Terminal = class Terminal { - constructor(runwindow) { +})(); + +this.Terminal = (function() { + function Terminal(runwindow) { this.runwindow = runwindow; } - start() {} + Terminal.prototype.start = function() {}; - validateLine(v) {} + Terminal.prototype.validateLine = function(v) {}; - setTrailingCaret() {} + Terminal.prototype.setTrailingCaret = function() {}; - echo(text, scroll = false, classname) { + Terminal.prototype.echo = function(text, scroll, classname) { + if (scroll == null) { + scroll = false; + } return console.info(text); - } + }; - error(text, scroll = false) { + Terminal.prototype.error = function(text, scroll) { + if (scroll == null) { + scroll = false; + } return console.error(text); - } + }; + + Terminal.prototype.clear = function() {}; - clear() {} + return Terminal; -}; +})(); diff --git a/static/js/play/serverclient.js b/static/js/play/serverclient.js index 8cd80229..a7344fdd 100644 --- a/static/js/play/serverclient.js +++ b/static/js/play/serverclient.js @@ -1,5 +1,5 @@ -this.PlayerClient = class PlayerClient { - constructor(player) { +this.PlayerClient = (function() { + function PlayerClient(player) { var err; this.player = player; this.pending_requests = {}; @@ -13,137 +13,135 @@ this.PlayerClient = class PlayerClient { err = error; console.error(err); } - setInterval((() => { - if (this.socket != null) { - return this.sendRequest({ - name: "ping" - }); - } - }), 30000); + setInterval(((function(_this) { + return function() { + if (_this.socket != null) { + return _this.sendRequest({ + name: "ping" + }); + } + }; + })(this)), 30000); } } - connect() { + PlayerClient.prototype.connect = function() { this.socket = new WebSocket(window.location.origin.replace("http", "ws")); - this.socket.onmessage = (msg) => { - var err; - console.info("received: " + msg.data); - try { - msg = JSON.parse(msg.data); - if (msg.request_id != null) { - if (this.pending_requests[msg.request_id] != null) { - this.pending_requests[msg.request_id](msg); - delete this.pending_requests[msg.request_id]; + this.socket.onmessage = (function(_this) { + return function(msg) { + var err; + console.info("received: " + msg.data); + try { + msg = JSON.parse(msg.data); + if (msg.request_id != null) { + if (_this.pending_requests[msg.request_id] != null) { + _this.pending_requests[msg.request_id](msg); + delete _this.pending_requests[msg.request_id]; + } } + if (msg.name === "project_file_updated") { + _this.player.runtime.projectFileUpdated(msg.type, msg.file, msg.version, msg.data, msg.properties); + } + if (msg.name === "project_file_deleted") { + _this.player.runtime.projectFileDeleted(msg.type, msg.file); + } + if (msg.name === "project_options_updated") { + return _this.player.runtime.projectOptionsUpdated(msg); + } + } catch (error) { + err = error; + return console.error(err); } - //if msg.name == "code_updated" - // @player.runtime.updateSource(msg.file,msg.code,true) - - //if msg.name == "sprite_updated" - // @player.runtime.updateSprite(msg.sprite) - if (msg.name === "project_file_updated") { - this.player.runtime.projectFileUpdated(msg.type, msg.file, msg.version, msg.data, msg.properties); - } - if (msg.name === "project_file_deleted") { - this.player.runtime.projectFileDeleted(msg.type, msg.file); - } - if (msg.name === "project_options_updated") { - return this.player.runtime.projectOptionsUpdated(msg); - } - } catch (error) { - err = error; - return console.error(err); - } - }; - this.socket.onopen = () => { - var i, j, k, l, len, len1, len2, len3, m, maps, project, ref, ref1, ref2, ref3, s, sources, sprites, user; - //console.info "socket opened" - this.reconnect_delay = 1000; - user = location.pathname.split("/")[1]; - project = location.pathname.split("/")[2]; - if (this.buffer != null) { - ref = this.buffer; - for (i = 0, len = ref.length; i < len; i++) { - m = ref[i]; - this.send(m); - } - delete this.buffer; - } - this.send({ - name: "listen_to_project", - user: user, - project: project - }); - if (!this.version_checked) { - this.version_checked = true; - sprites = {}; - maps = {}; - sources = {}; - ref1 = this.player.resources.images; - for (j = 0, len1 = ref1.length; j < len1; j++) { - s = ref1[j]; - sprites[s.file.split(".")[0]] = s.version; - } - ref2 = this.player.resources.maps; - for (k = 0, len2 = ref2.length; k < len2; k++) { - s = ref2[k]; - maps[s.file.split(".")[0]] = s.version; - } - ref3 = this.player.resources.sources; - for (l = 0, len3 = ref3.length; l < len3; l++) { - s = ref3[l]; - sources[s.file.split(".")[0]] = s.version; + }; + })(this); + this.socket.onopen = (function(_this) { + return function() { + var i, j, k, l, len, len1, len2, len3, m, maps, project, ref, ref1, ref2, ref3, s, sources, sprites, user; + _this.reconnect_delay = 1000; + user = location.pathname.split("/")[1]; + project = location.pathname.split("/")[2]; + if (_this.buffer != null) { + ref = _this.buffer; + for (i = 0, len = ref.length; i < len; i++) { + m = ref[i]; + _this.send(m); + } + delete _this.buffer; } - return this.sendRequest({ - name: "get_file_versions", + _this.send({ + name: "listen_to_project", user: user, project: project - }, (msg) => { - var info, name, ref4, ref5, ref6, results, v; - ref4 = msg.data.sources; - for (name in ref4) { - info = ref4[name]; - v = sources[name]; - if ((v == null) || v !== info.version) { - //console.info "updating #{name} to version #{version}" - this.player.runtime.projectFileUpdated("ms", name, info.version, null, info.properties); - } + }); + if (!_this.version_checked) { + _this.version_checked = true; + sprites = {}; + maps = {}; + sources = {}; + ref1 = _this.player.resources.images; + for (j = 0, len1 = ref1.length; j < len1; j++) { + s = ref1[j]; + sprites[s.file.split(".")[0]] = s.version; } - ref5 = msg.data.sprites; - for (name in ref5) { - info = ref5[name]; - v = sprites[name]; - if ((v == null) || v !== info.version) { - //console.info "updating #{name} to version #{version}" - this.player.runtime.projectFileUpdated("sprites", name, info.version, null, info.properties); - } + ref2 = _this.player.resources.maps; + for (k = 0, len2 = ref2.length; k < len2; k++) { + s = ref2[k]; + maps[s.file.split(".")[0]] = s.version; } - ref6 = msg.data.maps; - results = []; - for (name in ref6) { - info = ref6[name]; - v = maps[name]; - if ((v == null) || v !== info.version) { - //console.info "updating #{name} to version #{version}" - results.push(this.player.runtime.projectFileUpdated("maps", name, info.version, null, info.properties)); - } else { - results.push(void 0); - } + ref3 = _this.player.resources.sources; + for (l = 0, len3 = ref3.length; l < len3; l++) { + s = ref3[l]; + sources[s.file.split(".")[0]] = s.version; } - return results; - }); - } - }; - return this.socket.onclose = () => { - //console.info "socket closed" - setTimeout((() => { - return this.connect(); - }), this.reconnect_delay); - return this.reconnect_delay += 1000; - }; - } + return _this.sendRequest({ + name: "get_file_versions", + user: user, + project: project + }, function(msg) { + var info, name, ref4, ref5, ref6, results, v; + ref4 = msg.data.sources; + for (name in ref4) { + info = ref4[name]; + v = sources[name]; + if ((v == null) || v !== info.version) { + _this.player.runtime.projectFileUpdated("ms", name, info.version, null, info.properties); + } + } + ref5 = msg.data.sprites; + for (name in ref5) { + info = ref5[name]; + v = sprites[name]; + if ((v == null) || v !== info.version) { + _this.player.runtime.projectFileUpdated("sprites", name, info.version, null, info.properties); + } + } + ref6 = msg.data.maps; + results = []; + for (name in ref6) { + info = ref6[name]; + v = maps[name]; + if ((v == null) || v !== info.version) { + results.push(_this.player.runtime.projectFileUpdated("maps", name, info.version, null, info.properties)); + } else { + results.push(void 0); + } + } + return results; + }); + } + }; + })(this); + return this.socket.onclose = (function(_this) { + return function() { + setTimeout((function() { + return _this.connect(); + }), _this.reconnect_delay); + return _this.reconnect_delay += 1000; + }; + })(this); + }; - send(data) { + PlayerClient.prototype.send = function(data) { if (this.socket.readyState !== 1) { if (this.buffer == null) { this.buffer = []; @@ -152,12 +150,14 @@ this.PlayerClient = class PlayerClient { } else { return this.socket.send(JSON.stringify(data)); } - } + }; - sendRequest(msg, callback) { + PlayerClient.prototype.sendRequest = function(msg, callback) { msg.request_id = this.request_id++; this.pending_requests[msg.request_id] = callback; return this.send(msg); - } + }; + + return PlayerClient; -}; +})(); diff --git a/static/js/project/project.js b/static/js/project/project.js index 37e6d262..0be9934c 100644 --- a/static/js/project/project.js +++ b/static/js/project/project.js @@ -1,13 +1,15 @@ -this.Project = class Project { - constructor(app, data) { +var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; + +this.Project = (function() { + function Project(app, data) { var f, k, len1, ref; - this.setSourceList = this.setSourceList.bind(this); - this.setSpriteList = this.setSpriteList.bind(this); - this.setMapList = this.setMapList.bind(this); - this.setSoundList = this.setSoundList.bind(this); - this.setMusicList = this.setMusicList.bind(this); - this.setAssetList = this.setAssetList.bind(this); this.app = app; + this.setAssetList = bind(this.setAssetList, this); + this.setMusicList = bind(this.setMusicList, this); + this.setSoundList = bind(this.setSoundList, this); + this.setMapList = bind(this.setMapList, this); + this.setSpriteList = bind(this.setSpriteList, this); + this.setSourceList = bind(this.setSourceList, this); this.id = data.id; this.owner = data.owner; this.accepted = data.accepted; @@ -16,7 +18,7 @@ this.Project = class Project { this.title = data.title; this.description = data.description; this.tags = data.tags; - this.public = data.public; + this["public"] = data["public"]; this.unlisted = data.unlisted; this.platforms = data.platforms; this.controls = data.controls; @@ -37,44 +39,46 @@ this.Project = class Project { ref = this.file_types; for (k = 0, len1 = ref.length; k < len1; k++) { f = ref[k]; - this[`${f}_list`] = []; - this[`${f}_table`] = {}; - this[`${f}_folder`] = new ProjectFolder(null, f); + this[f + "_list"] = []; + this[f + "_table"] = {}; + this[f + "_folder"] = new ProjectFolder(null, f); } this.locks = {}; this.lock_time = {}; this.friends = {}; - this.url = location.origin + `/${this.owner.nick}/${this.slug}/`; + this.url = location.origin + ("/" + this.owner.nick + "/" + this.slug + "/"); this.listeners = []; - setInterval((() => { - return this.checkLocks(); - }), 1000); + setInterval(((function(_this) { + return function() { + return _this.checkLocks(); + }; + })(this)), 1000); this.pending_changes = []; this.onbeforeunload = null; } - getFullURL() { - if (this.public) { + Project.prototype.getFullURL = function() { + if (this["public"]) { return this.url; } else { - return location.origin + `/${this.owner.nick}/${this.slug}/${this.code}/`; + return location.origin + ("/" + this.owner.nick + "/" + this.slug + "/" + this.code + "/"); } - } + }; - addListener(lis) { + Project.prototype.addListener = function(lis) { return this.listeners.push(lis); - } + }; - notifyListeners(change) { + Project.prototype.notifyListeners = function(change) { var k, len1, lis, ref; ref = this.listeners; for (k = 0, len1 = ref.length; k < len1; k++) { lis = ref[k]; lis.projectUpdate(change); } - } + }; - load() { + Project.prototype.load = function() { this.updateSourceList(); this.updateSpriteList(); this.updateMapList(); @@ -82,74 +86,80 @@ this.Project = class Project { this.updateMusicList(); this.updateAssetList(); return this.loadDoc(); - } + }; - loadDoc() { + Project.prototype.loadDoc = function() { this.app.doc_editor.setDoc(""); - return this.app.readProjectFile(this.id, "doc/doc.md", (content) => { - return this.app.doc_editor.setDoc(content); - }); - } + return this.app.readProjectFile(this.id, "doc/doc.md", (function(_this) { + return function(content) { + return _this.app.doc_editor.setDoc(content); + }; + })(this)); + }; - updateFileList(folder, callback) { + Project.prototype.updateFileList = function(folder, callback) { return this.app.client.sendRequest({ name: "list_project_files", project: this.app.project.id, folder: folder - }, (msg) => { - return this[callback](msg.files); - }); - } + }, (function(_this) { + return function(msg) { + return _this[callback](msg.files); + }; + })(this)); + }; - updateSourceList() { + Project.prototype.updateSourceList = function() { return this.updateFileList("ms", "setSourceList"); - } + }; - updateSpriteList() { + Project.prototype.updateSpriteList = function() { return this.updateFileList("sprites", "setSpriteList"); - } + }; - updateMapList() { + Project.prototype.updateMapList = function() { return this.updateFileList("maps", "setMapList"); - } + }; - updateSoundList() { + Project.prototype.updateSoundList = function() { return this.updateFileList("sounds", "setSoundList"); - } + }; - updateMusicList() { + Project.prototype.updateMusicList = function() { return this.updateFileList("music", "setMusicList"); - } + }; - updateAssetList() { + Project.prototype.updateAssetList = function() { return this.updateFileList("assets", "setAssetList"); - } + }; - lockFile(file) { + Project.prototype.lockFile = function(file) { var lock; lock = this.lock_time[file]; if ((lock != null) && Date.now() < lock) { return; } this.lock_time[file] = Date.now() + 2000; - console.info(`locking file ${file}`); + console.info("locking file " + file); return this.app.client.sendRequest({ name: "lock_project_file", project: this.id, file: file - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - fileLocked(msg) { + Project.prototype.fileLocked = function(msg) { this.locks[msg.file] = { user: msg.user, time: Date.now() + 10000 }; this.friends[msg.user] = Date.now() + 120000; return this.notifyListeners("locks"); - } + }; - isLocked(file) { + Project.prototype.isLocked = function(file) { var lock; lock = this.locks[file]; if ((lock != null) && Date.now() < lock.time) { @@ -157,9 +167,9 @@ this.Project = class Project { } else { return false; } - } + }; - checkLocks() { + Project.prototype.checkLocks = function() { var change, file, lock, ref, ref1, time, user; change = false; ref = this.locks; @@ -181,9 +191,9 @@ this.Project = class Project { if (change) { return this.notifyListeners("locks"); } - } + }; - changeSpriteName(old, name) { + Project.prototype.changeSpriteName = function(old, name) { var changed, i, j, k, l, len1, map, n, ref, ref1, ref2, s; old = old.replace(/-/g, "/"); ref = this.map_list; @@ -210,19 +220,21 @@ this.Project = class Project { this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `maps/${map.name}.json`, + file: "maps/" + map.name + ".json", content: map.save() - }, (msg) => {}); + }, (function(_this) { + return function(msg) {}; + })(this)); } } - } + }; - changeMapName(old, name) { + Project.prototype.changeMapName = function(old, name) { this.map_table[name] = this.map_table[old]; return delete this.map_table[old]; - } + }; - fileUpdated(msg) { + Project.prototype.fileUpdated = function(msg) { var name; if (msg.file.indexOf("ms/") === 0) { name = msg.file.substring("ms/".length, msg.file.indexOf(".ms")); @@ -242,11 +254,13 @@ this.Project = class Project { this.sprite_table[name].fps = msg.properties.fps; } } - return this.sprite_table[name].reload(() => { - if (name === this.app.sprite_editor.selected_sprite) { - return this.app.sprite_editor.currentSpriteUpdated(); - } - }); + return this.sprite_table[name].reload((function(_this) { + return function() { + if (name === _this.app.sprite_editor.selected_sprite) { + return _this.app.sprite_editor.currentSpriteUpdated(); + } + }; + })(this)); } else { return this.updateSpriteList(); } @@ -273,9 +287,9 @@ this.Project = class Project { return this.updateAssetList(); } } - } + }; - fileDeleted(msg) { + Project.prototype.fileDeleted = function(msg) { if (msg.file.indexOf("ms/") === 0) { return this.updateSourceList(); } else if (msg.file.indexOf("sprites/") === 0) { @@ -287,38 +301,41 @@ this.Project = class Project { } else if (msg.file.indexOf("music/") === 0) { return this.updateMusicList(); } - } + }; - optionsUpdated(data) { + Project.prototype.optionsUpdated = function(data) { this.slug = data.slug; this.title = data.title; - this.public = data.public; + this["public"] = data["public"]; this.platforms = data.platforms; this.controls = data.controls; this.type = data.type; this.orientation = data.orientation; return this.aspect = data.aspect; - } + }; - addSprite(sprite) { + Project.prototype.addSprite = function(sprite) { var s; s = new ProjectSprite(this, sprite.file, null, null, sprite.properties, sprite.size); this.sprite_table[s.name] = s; this.sprite_list.push(s); this.sprite_folder.push(s); return s; - } + }; - getSprite(name) { + Project.prototype.getSprite = function(name) { return this.sprite_table[name]; - } + }; - createSprite(width, height, name = "sprite") { + Project.prototype.createSprite = function(width, height, name) { var count, filename, sprite; + if (name == null) { + name = "sprite"; + } if (this.getSprite(name)) { count = 2; while (true) { - filename = `${name}${count++}`; + filename = "" + name + (count++); if (this.getSprite(filename) == null) { break; } @@ -332,27 +349,30 @@ this.Project = class Project { this.sprite_folder.push(sprite); this.notifyListeners("spritelist"); return sprite; - } + }; - addSource(file) { + Project.prototype.addSource = function(file) { var s; s = new ProjectSource(this, file.file, file.size); this.source_table[s.name] = s; this.source_list.push(s); this.source_folder.push(s); return s; - } + }; - getSource(name) { + Project.prototype.getSource = function(name) { return this.source_table[name]; - } + }; - createSource(basename = "source") { + Project.prototype.createSource = function(basename) { var count, filename, source; + if (basename == null) { + basename = "source"; + } count = 2; filename = basename; while (this.getSource(filename) != null) { - filename = `${basename}${count++}`; + filename = "" + basename + (count++); } source = new ProjectSource(this, filename + ".ms"); source.fetched = true; @@ -361,9 +381,9 @@ this.Project = class Project { this.source_folder.push(source); this.notifyListeners("sourcelist"); return source; - } + }; - getFullSource() { + Project.prototype.getFullSource = function() { var k, len1, ref, res, s; res = ""; ref = this.source_list; @@ -372,9 +392,9 @@ this.Project = class Project { res += s + "\n"; } return res; - } + }; - setFileList(list, target_list, target_table, get, add, item_id) { + Project.prototype.setFileList = function(list, target_list, target_table, get, add, item_id) { var f, folder, i, k, l, len1, len2, li, n, notification, ref, s; notification = item_id + "list"; li = []; @@ -384,7 +404,6 @@ this.Project = class Project { } folder = this[item_id + "_folder"]; folder.removeNoMatch(li); -//@[item_id+"_folder"] = new ProjectFolder(null,item_id) for (i = l = ref = target_list.length - 1; l >= 0; i = l += -1) { s = target_list[i]; if (li.indexOf(s.filename) < 0) { @@ -401,64 +420,67 @@ this.Project = class Project { folder.removeEmptyFolders(); folder.sort(); return this.notifyListeners(notification); - } + }; - setSourceList(list) { + Project.prototype.setSourceList = function(list) { return this.setFileList(list, this.source_list, this.source_table, "getSource", "addSource", "source"); - } + }; - setSpriteList(list) { + Project.prototype.setSpriteList = function(list) { return this.setFileList(list, this.sprite_list, this.sprite_table, "getSprite", "addSprite", "sprite"); - } + }; - setMapList(list) { + Project.prototype.setMapList = function(list) { return this.setFileList(list, this.map_list, this.map_table, "getMap", "addMap", "map"); - } + }; - setSoundList(list) { + Project.prototype.setSoundList = function(list) { return this.setFileList(list, this.sound_list, this.sound_table, "getSound", "addSound", "sound"); - } + }; - setMusicList(list) { + Project.prototype.setMusicList = function(list) { return this.setFileList(list, this.music_list, this.music_table, "getMusic", "addMusic", "music"); - } + }; - setAssetList(list) { + Project.prototype.setAssetList = function(list) { return this.setFileList(list, this.asset_list, this.asset_table, "getAsset", "addAsset", "asset"); - } + }; - addMap(file) { + Project.prototype.addMap = function(file) { var m; m = new ProjectMap(this, file.file, file.size); this.map_table[m.name] = m; this.map_list.push(m); this.map_folder.push(m); return m; - } + }; - getMap(name) { + Project.prototype.getMap = function(name) { return this.map_table[name]; - } + }; - addAsset(file) { + Project.prototype.addAsset = function(file) { var m; m = new ProjectAsset(this, file.file, file.size); this.asset_table[m.name] = m; this.asset_list.push(m); this.asset_folder.push(m); return m; - } + }; - getAsset(name) { + Project.prototype.getAsset = function(name) { return this.asset_table[name]; - } + }; - createMap(basename = "map") { + Project.prototype.createMap = function(basename) { var count, m, name; + if (basename == null) { + basename = "map"; + } name = basename; count = 2; while (this.getMap(name)) { - name = `${basename}${count++}`; + name = "" + basename + (count++); } m = this.addMap({ file: name + ".json", @@ -466,14 +488,17 @@ this.Project = class Project { }); this.notifyListeners("maplist"); return m; - } + }; - createSound(name = "sound", thumbnail, size) { + Project.prototype.createSound = function(name, thumbnail, size) { var count, filename, sound; + if (name == null) { + name = "sound"; + } if (this.getSound(name)) { count = 2; while (true) { - filename = `${name}${count++}`; + filename = "" + name + (count++); if (this.getSound(filename) == null) { break; } @@ -490,27 +515,30 @@ this.Project = class Project { this.sound_folder.push(sound); this.notifyListeners("soundlist"); return sound; - } + }; - addSound(file) { + Project.prototype.addSound = function(file) { var m; m = new ProjectSound(this, file.file, file.size); this.sound_table[m.name] = m; this.sound_list.push(m); this.sound_folder.push(m); return m; - } + }; - getSound(name) { + Project.prototype.getSound = function(name) { return this.sound_table[name]; - } + }; - createMusic(name = "music", thumbnail, size) { + Project.prototype.createMusic = function(name, thumbnail, size) { var count, filename, music; + if (name == null) { + name = "music"; + } if (this.getMusic(name)) { count = 2; while (true) { - filename = `${name}${count++}`; + filename = "" + name + (count++); if (this.getMusic(filename) == null) { break; } @@ -527,27 +555,30 @@ this.Project = class Project { this.music_folder.push(music); this.notifyListeners("musiclist"); return music; - } + }; - addMusic(file) { + Project.prototype.addMusic = function(file) { var m; m = new ProjectMusic(this, file.file, file.size); this.music_table[m.name] = m; this.music_list.push(m); this.music_folder.push(m); return m; - } + }; - getMusic(name) { + Project.prototype.getMusic = function(name) { return this.music_table[name]; - } + }; - createAsset(name = "asset", thumbnail, size, ext) { + Project.prototype.createAsset = function(name, thumbnail, size, ext) { var asset, count, filename; + if (name == null) { + name = "asset"; + } if (this.getAsset(name)) { count = 2; while (true) { - filename = `${name}${count++}`; + filename = "" + name + (count++); if (this.getAsset(filename) == null) { break; } @@ -555,7 +586,7 @@ this.Project = class Project { } else { filename = name; } - asset = new ProjectAsset(this, filename + `.${ext}`, size); + asset = new ProjectAsset(this, filename + ("." + ext), size); if (thumbnail) { asset.thumbnail_url = thumbnail; } @@ -564,63 +595,61 @@ this.Project = class Project { this.asset_folder.push(asset); this.notifyListeners("assetlist"); return asset; - } + }; - setTitle(title) { + Project.prototype.setTitle = function(title) { this.title = title; return this.notifyListeners("title"); - } + }; - setSlug(slug) { + Project.prototype.setSlug = function(slug) { this.slug = slug; return this.notifyListeners("slug"); - } + }; - setCode(code) { + Project.prototype.setCode = function(code) { this.code = code; return this.notifyListeners("code"); - } + }; - setType(type1) { + Project.prototype.setType = function(type1) { this.type = type1; - } + }; - setOrientation(orientation) { + Project.prototype.setOrientation = function(orientation) { this.orientation = orientation; - } + }; - //window.dispatchEvent(new Event('resize')) - setAspect(aspect) { + Project.prototype.setAspect = function(aspect) { this.aspect = aspect; - } + }; - //window.dispatchEvent(new Event('resize')) - setGraphics(graphics) { + Project.prototype.setGraphics = function(graphics) { this.graphics = graphics; - } + }; - //window.dispatchEvent(new Event('resize')) - setLanguage(language) { + Project.prototype.setLanguage = function(language) { this.language = language; - } + }; - //window.dispatchEvent(new Event('resize')) - addPendingChange(item) { + Project.prototype.addPendingChange = function(item) { if (this.pending_changes.indexOf(item) < 0) { this.pending_changes.push(item); } if (this.onbeforeunload == null) { - this.onbeforeunload = (event) => { - event.preventDefault(); - event.returnValue = "You have pending unsaved changed."; - this.savePendingChanges(); - return event.returnValue; - }; + this.onbeforeunload = (function(_this) { + return function(event) { + event.preventDefault(); + event.returnValue = "You have pending unsaved changed."; + _this.savePendingChanges(); + return event.returnValue; + }; + })(this); return window.addEventListener("beforeunload", this.onbeforeunload); } - } + }; - removePendingChange(item) { + Project.prototype.removePendingChange = function(item) { var index; index = this.pending_changes.indexOf(item); if (index >= 0) { @@ -632,42 +661,44 @@ this.Project = class Project { return this.onbeforeunload = null; } } - } + }; - savePendingChanges(callback) { + Project.prototype.savePendingChanges = function(callback) { var save; if (this.pending_changes.length > 0) { save = this.pending_changes.splice(0, 1)[0]; - return save.forceSave(() => { - return this.savePendingChanges(callback); - }); + return save.forceSave((function(_this) { + return function() { + return _this.savePendingChanges(callback); + }; + })(this)); } else { if (callback != null) { return callback(); } } - } + }; - getSize() { + Project.prototype.getSize = function() { var k, l, len1, len2, ref, s, size, t, type; size = 0; ref = this.file_types; for (k = 0, len1 = ref.length; k < len1; k++) { type = ref[k]; - t = this[`${type}_list`]; + t = this[type + "_list"]; for (l = 0, len2 = t.length; l < len2; l++) { s = t[l]; size += s.size; } } return size; - } + }; - writeFile(name, content, options) { + Project.prototype.writeFile = function(name, content, options) { var folder, i, k, ref; name = name.split("/"); folder = name[0]; - for (i = k = 0, ref = name.length - 1; (0 <= ref ? k <= ref : k >= ref); i = 0 <= ref ? ++k : --k) { + for (i = k = 0, ref = name.length - 1; 0 <= ref ? k <= ref : k >= ref; i = 0 <= ref ? ++k : --k) { name[i] = RegexLib.fixFilename(name[i]); } name = name.slice(1).join("-"); @@ -685,20 +716,22 @@ this.Project = class Project { case "assets": return this.writeAssetFile(name, content, options.ext); } - } + }; - writeSourceFile(name, content) { + Project.prototype.writeSourceFile = function(name, content) { return this.app.client.sendRequest({ name: "write_project_file", project: this.id, - file: `ms/${name}.ms`, + file: "ms/" + name + ".ms", content: content - }, (msg) => { - return this.updateSourceList(); - }); - } + }, (function(_this) { + return function(msg) { + return _this.updateSourceList(); + }; + })(this)); + }; - writeSoundFile(name, content) { + Project.prototype.writeSoundFile = function(name, content) { var audioContext, base64ToArrayBuffer; base64ToArrayBuffer = function(base64) { var binary_string, bytes, i, k, len, ref; @@ -711,25 +744,27 @@ this.Project = class Project { return bytes.buffer; }; audioContext = new AudioContext(); - return audioContext.decodeAudioData(base64ToArrayBuffer(content), (decoded) => { - var thumbnailer; - console.info(decoded); - thumbnailer = new SoundThumbnailer(decoded, 96, 64); - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.id, - file: `sounds/${name}.wav`, - properties: {}, - content: content, - thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] - }, (msg) => { - console.info(msg); - return this.updateSoundList(); - }); - }); - } + return audioContext.decodeAudioData(base64ToArrayBuffer(content), (function(_this) { + return function(decoded) { + var thumbnailer; + console.info(decoded); + thumbnailer = new SoundThumbnailer(decoded, 96, 64); + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.id, + file: "sounds/" + name + ".wav", + properties: {}, + content: content, + thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] + }, function(msg) { + console.info(msg); + return _this.updateSoundList(); + }); + }; + })(this)); + }; - writeMusicFile(name, content) { + Project.prototype.writeMusicFile = function(name, content) { var audioContext, base64ToArrayBuffer; base64ToArrayBuffer = function(base64) { var binary_string, bytes, i, k, len, ref; @@ -742,61 +777,66 @@ this.Project = class Project { return bytes.buffer; }; audioContext = new AudioContext(); - return audioContext.decodeAudioData(base64ToArrayBuffer(content), (decoded) => { - var thumbnailer; - console.info(decoded); - thumbnailer = new SoundThumbnailer(decoded, 192, 64, "hsl(200,80%,60%)"); - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.id, - file: `music/${name}.mp3`, - properties: {}, - content: content, - thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] - }, (msg) => { - console.info(msg); - return this.updateMusicList(); - }); - }); - } + return audioContext.decodeAudioData(base64ToArrayBuffer(content), (function(_this) { + return function(decoded) { + var thumbnailer; + console.info(decoded); + thumbnailer = new SoundThumbnailer(decoded, 192, 64, "hsl(200,80%,60%)"); + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.id, + file: "music/" + name + ".mp3", + properties: {}, + content: content, + thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] + }, function(msg) { + console.info(msg); + return _this.updateMusicList(); + }); + }; + })(this)); + }; - writeSpriteFile(name, content, frames, fps) { + Project.prototype.writeSpriteFile = function(name, content, frames, fps) { return this.app.client.sendRequest({ name: "write_project_file", project: this.id, - file: `sprites/${name}.png`, + file: "sprites/" + name + ".png", properties: { frames: frames, fps: fps }, content: content - }, (msg) => { - return this.fileUpdated({ - file: `sprites/${name}.png`, - properties: { - frames: frames, - fps: fps - } - }); - }); - } + }, (function(_this) { + return function(msg) { + return _this.fileUpdated({ + file: "sprites/" + name + ".png", + properties: { + frames: frames, + fps: fps + } + }); + }; + })(this)); + }; - // @updateSpriteList() - writeMapFile(name, content) { + Project.prototype.writeMapFile = function(name, content) { return this.app.client.sendRequest({ name: "write_project_file", project: this.id, - file: `maps/${name}.json`, + file: "maps/" + name + ".json", content: content - }, (msg) => { - this.fileUpdated({ - file: `maps/${name}.json` - }); - return this.updateMapList(); - }); - } + }, (function(_this) { + return function(msg) { + _this.fileUpdated({ + file: "maps/" + name + ".json" + }); + return _this.updateMapList(); + }; + })(this)); + }; - writeAssetFile(name, content, ext) { + Project.prototype.writeAssetFile = function(name, content, ext) { var send, thumbnail; if (ext === "json") { content = JSON.stringify(content); @@ -809,26 +849,32 @@ this.Project = class Project { if (ext === "obj") { content = btoa(content); } - send = () => { - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.id, - file: `assets/${name}.${ext}`, - content: content, - thumbnail: thumbnail - }, (msg) => { - return this.updateAssetList(); - }); - }; + send = (function(_this) { + return function() { + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.id, + file: "assets/" + name + "." + ext, + content: content, + thumbnail: thumbnail + }, function(msg) { + return _this.updateAssetList(); + }); + }; + })(this); if (ext === "png" || ext === "jpg") { - this.app.assets_manager.image_viewer.createThumbnail(content, (canvas) => { - thumbnail = canvas.toDataURL().split(",")[1]; - content = content.split(",")[1]; - return send(); - }); + this.app.assets_manager.image_viewer.createThumbnail(content, (function(_this) { + return function(canvas) { + thumbnail = canvas.toDataURL().split(",")[1]; + content = content.split(",")[1]; + return send(); + }; + })(this)); return; } return send(); - } + }; + + return Project; -}; +})(); diff --git a/static/js/project/projectfolder.js b/static/js/project/projectfolder.js index f8fc1840..16b841d6 100644 --- a/static/js/project/projectfolder.js +++ b/static/js/project/projectfolder.js @@ -1,5 +1,5 @@ -this.ProjectFolder = class ProjectFolder { - constructor(parent, name1) { +this.ProjectFolder = (function() { + function ProjectFolder(parent, name1) { this.parent = parent; this.name = name1; this.subfolders = []; @@ -7,8 +7,11 @@ this.ProjectFolder = class ProjectFolder { this.open = false; } - push(item, path = item.name) { + ProjectFolder.prototype.push = function(item, path) { var f, fold, folders; + if (path == null) { + path = item.name; + } folders = path.split("-"); if (folders.length > 1) { f = folders.splice(0, 1)[0]; @@ -22,17 +25,9 @@ this.ProjectFolder = class ProjectFolder { item.parent = this; } return item; - } - - // add:(file,path)-> - // if not path? - // path = file.name.split["-"] + }; - // if file instanceof ProjectFolder - // @subfolders.push file - // else - // @files.push file - getSubFolder(name) { + ProjectFolder.prototype.getSubFolder = function(name) { var f, j, len, ref; ref = this.subfolders; for (j = 0, len = ref.length; j < len; j++) { @@ -42,9 +37,9 @@ this.ProjectFolder = class ProjectFolder { } } return null; - } + }; - isAncestorOf(f) { + ProjectFolder.prototype.isAncestorOf = function(f) { if (this.subfolders.indexOf(f) >= 0) { return true; } @@ -53,9 +48,9 @@ this.ProjectFolder = class ProjectFolder { } else { return false; } - } + }; - getAllFiles() { + ProjectFolder.prototype.getAllFiles = function() { var f, j, len, list, ref; list = []; list = list.concat(this.files); @@ -65,16 +60,16 @@ this.ProjectFolder = class ProjectFolder { list = list.concat(f.getAllFiles()); } return list; - } + }; - createSubFolder(name) { + ProjectFolder.prototype.createSubFolder = function(name) { var f; f = new ProjectFolder(this, name); this.subfolders.push(f); return f; - } + }; - containsFiles() { + ProjectFolder.prototype.containsFiles = function() { var f, j, len, ref; if (this.files.length > 0) { return true; @@ -88,55 +83,55 @@ this.ProjectFolder = class ProjectFolder { } } return false; - } + }; - delete() { + ProjectFolder.prototype["delete"] = function() { if (this.parent != null) { this.parent.removeFolder(this); } if ((this.element != null) && (this.element.parentNode != null)) { return this.element.parentNode.removeChild(this.element); } - } + }; - addFolder(f) { + ProjectFolder.prototype.addFolder = function(f) { if (f.parent != null) { f.parent.removeFolder(f); } this.subfolders.push(f); return f.parent = this; - } + }; - removeFolder(f) { + ProjectFolder.prototype.removeFolder = function(f) { var index; index = this.subfolders.indexOf(f); if (index >= 0) { return this.subfolders.splice(index, 1); } - } + }; - createEmptyFolder() { + ProjectFolder.prototype.createEmptyFolder = function() { var count, f, name; count = 1; name = "folder"; while (this.getSubFolder(name) != null) { count += 1; - name = `folder${count}`; + name = "folder" + count; } f = new ProjectFolder(this, name); this.subfolders.push(f); return f; - } + }; - getFullDashPath() { + ProjectFolder.prototype.getFullDashPath = function() { if ((this.parent != null) && (this.parent.parent != null)) { return this.parent.getFullDashPath() + "-" + this.name; } else { return this.name; } - } + }; - removeNoMatch(list) { + ProjectFolder.prototype.removeNoMatch = function(list) { var f, i, j, k, len, ref, ref1; ref = this.subfolders; for (j = 0, len = ref.length; j < len; j++) { @@ -149,20 +144,20 @@ this.ProjectFolder = class ProjectFolder { this.files.splice(i, 1); } } - } + }; - removeEmptyFolders() { + ProjectFolder.prototype.removeEmptyFolders = function() { var f, i, j, ref; for (i = j = ref = this.subfolders.length - 1; j >= 0; i = j += -1) { f = this.subfolders[i]; f.removeEmptyFolders(); - if (f.subfolders.length === 0 && f.files.length === 0 && !f.protected) { + if (f.subfolders.length === 0 && f.files.length === 0 && !f["protected"]) { this.subfolders.splice(i, 1); } } - } + }; - sort() { + ProjectFolder.prototype.sort = function() { var f, j, len, ref; ref = this.subfolders; for (j = 0, len = ref.length; j < len; j++) { @@ -183,14 +178,14 @@ this.ProjectFolder = class ProjectFolder { return 1; } }); - } + }; - setElement(element) { + ProjectFolder.prototype.setElement = function(element) { this.element = element; return this.setOpen(this.open); - } + }; - setOpen(open) { + ProjectFolder.prototype.setOpen = function(open) { this.open = open; if (this.element != null) { if (this.open) { @@ -199,10 +194,12 @@ this.ProjectFolder = class ProjectFolder { return this.element.classList.remove("open"); } } - } + }; + + ProjectFolder.prototype.find = function() {}; - find() {} + ProjectFolder.prototype.remove = function() {}; - remove() {} + return ProjectFolder; -}; +})(); diff --git a/static/js/publish/publish.js b/static/js/publish/publish.js index 5d893115..d8ceba26 100644 --- a/static/js/publish/publish.js +++ b/static/js/publish/publish.js @@ -1,41 +1,53 @@ -this.Publish = class Publish { - constructor(app) { +this.Publish = (function() { + function Publish(app) { this.app = app; - this.app.appui.setAction("publish-button", () => { - return this.setProjectPublic(true); - }); - this.app.appui.setAction("unpublish-button", () => { - return this.setProjectPublic(false); - }); - this.tags_validator = new InputValidator(document.getElementById("publish-add-tags"), document.getElementById("publish-add-tags-button"), null, (value) => { - return this.addTags(value[0]); - }); + this.app.appui.setAction("publish-button", (function(_this) { + return function() { + return _this.setProjectPublic(true); + }; + })(this)); + this.app.appui.setAction("unpublish-button", (function(_this) { + return function() { + return _this.setProjectPublic(false); + }; + })(this)); + this.tags_validator = new InputValidator(document.getElementById("publish-add-tags"), document.getElementById("publish-add-tags-button"), null, (function(_this) { + return function(value) { + return _this.addTags(value[0]); + }; + })(this)); this.description_save = 0; - document.querySelector("#publish-box-textarea").addEventListener("input", () => { - return this.description_save = Date.now() + 2000; - }); - setInterval((() => { - return this.checkDescriptionSave(); - }), 1000); + document.querySelector("#publish-box-textarea").addEventListener("input", (function(_this) { + return function() { + return _this.description_save = Date.now() + 2000; + }; + })(this)); + setInterval(((function(_this) { + return function() { + return _this.checkDescriptionSave(); + }; + })(this)), 1000); this.builders = []; this.builders.push(new AppBuild(this.app, "android")); this.builders.push(new AppBuild(this.app, "windows")); this.builders.push(new AppBuild(this.app, "macos")); this.builders.push(new AppBuild(this.app, "linux")); this.builders.push(new AppBuild(this.app, "raspbian")); - document.getElementById("publish-listed").addEventListener("change", () => { - if (this.app.project != null) { - this.app.project.unlisted = !document.getElementById("publish-listed").checked; - this.app.options.optionChanged("unlisted", !document.getElementById("publish-listed").checked); - this.sendProjectPublic(this.app.project.public); - return this.updateCheckList(); - } - }); + document.getElementById("publish-listed").addEventListener("change", (function(_this) { + return function() { + if (_this.app.project != null) { + _this.app.project.unlisted = !document.getElementById("publish-listed").checked; + _this.app.options.optionChanged("unlisted", !document.getElementById("publish-listed").checked); + _this.sendProjectPublic(_this.app.project["public"]); + return _this.updateCheckList(); + } + }; + })(this)); } - loadProject(project) { + Publish.prototype.loadProject = function(project) { var b, build, j, len, public_url, ref; - if (project.public) { + if (project["public"]) { document.getElementById("publish-box").style.display = "none"; document.getElementById("unpublish-box").style.display = "block"; } else { @@ -45,7 +57,7 @@ this.Publish = class Publish { document.getElementById("publish-validate-first").style.display = this.app.user.flags["validated"] ? "none" : "block"; document.getElementById("publish-listed").checked = !project.unlisted; this.updateCheckList(); - public_url = `${location.origin.replace(".dev", ".io")}/i/${this.app.project.owner.nick}/${this.app.project.slug}/`; + public_url = (location.origin.replace(".dev", ".io")) + "/i/" + this.app.project.owner.nick + "/" + this.app.project.slug + "/"; document.getElementById("publish-public-link").href = public_url; document.getElementById("publish-public-link").innerText = public_url; document.querySelector("#publish-box-textarea").value = project.description; @@ -57,53 +69,56 @@ this.Publish = class Publish { document.querySelector("#publish-box .publish-button").classList.add("disabled"); } b = document.querySelector("#html-export .publish-button"); - b.onclick = () => { - var loc; - loc = `/${project.owner.nick}/${project.slug}/`; - if (!project.public) { - loc += project.code + "/"; - } - return window.location = loc + "publish/html/?v=" + Date.now(); - }; + b.onclick = (function(_this) { + return function() { + var loc; + loc = "/" + project.owner.nick + "/" + project.slug + "/"; + if (!project["public"]) { + loc += project.code + "/"; + } + return window.location = loc + "publish/html/?v=" + Date.now(); + }; + })(this); b = document.querySelector("#server-export .publish-button"); - b.onclick = () => { - var loc; - loc = `/${project.owner.nick}/${project.slug}/`; - if (!project.public) { - loc += project.code + "/"; - } - return window.location = loc + "publish/html/?server&v=" + Date.now(); - }; + b.onclick = (function(_this) { + return function() { + var loc; + loc = "/" + project.owner.nick + "/" + project.slug + "/"; + if (!project["public"]) { + loc += project.code + "/"; + } + return window.location = loc + "publish/html/?server&v=" + Date.now(); + }; + })(this); ref = this.builders; for (j = 0, len = ref.length; j < len; j++) { build = ref[j]; build.loadProject(project); } this.updateServerExport(); - } + }; - updateServerExport() { + Publish.prototype.updateServerExport = function() { return document.querySelector("#publish-box-server").style.display = (this.app.project != null) && this.app.project.networking ? "block" : "none"; - } + }; - updateCheckList() { + Publish.prototype.updateCheckList = function() { var project; project = this.app.project; - if (project.public && !project.unlisted && !this.app.user.flags.approved && !project.flags.approved) { + if (project["public"] && !project.unlisted && !this.app.user.flags.approved && !project.flags.approved) { return document.getElementById("publish-checklist").style.display = "block"; } else { return document.getElementById("publish-checklist").style.display = "none"; } - } + }; - updateTags() { - var j, len, list, ref, t; + Publish.prototype.updateTags = function() { + var fn, j, len, list, ref, t; list = document.getElementById("publish-tag-list"); list.innerHTML = ""; ref = this.app.project.tags; - for (j = 0, len = ref.length; j < len; j++) { - t = ref[j]; - ((t) => { + fn = (function(_this) { + return function(t) { var e, i, span; e = document.createElement("div"); t = t.replace(/[<>&;"']/g, ""); @@ -113,16 +128,20 @@ this.Publish = class Publish { i = document.createElement("i"); i.classList.add("fa"); i.classList.add("fa-times-circle"); - i.addEventListener("click", () => { - return this.removeTag(t); + i.addEventListener("click", function() { + return _this.removeTag(t); }); e.appendChild(i); return list.appendChild(e); - })(t); + }; + })(this); + for (j = 0, len = ref.length; j < len; j++) { + t = ref[j]; + fn(t); } - } + }; - removeTag(t) { + Publish.prototype.removeTag = function(t) { var tags; tags = this.app.project.tags; if (tags.indexOf(t) >= 0) { @@ -131,13 +150,15 @@ this.Publish = class Publish { name: "set_project_tags", project: this.app.project.id, tags: tags - }, (msg) => { - return this.updateTags(); - }); + }, (function(_this) { + return function(msg) { + return _this.updateTags(); + }; + })(this)); } - } + }; - addTags(value) { + Publish.prototype.addTags = function(value) { var change, j, len, tags, v; tags = this.app.project.tags; value = value.toLowerCase().split(","); @@ -155,21 +176,26 @@ this.Publish = class Publish { name: "set_project_tags", project: this.app.project.id, tags: tags - }, (msg) => { - this.updateTags(); - return this.tags_validator.reset(); - }); + }, (function(_this) { + return function(msg) { + _this.updateTags(); + return _this.tags_validator.reset(); + }; + })(this)); } - } + }; - projectUpdate(type) { + Publish.prototype.projectUpdate = function(type) { switch (type) { case "tags": return this.updateTags(); } - } + }; - checkDescriptionSave(force = false) { + Publish.prototype.checkDescriptionSave = function(force) { + if (force == null) { + force = false; + } if (this.description_save > 0 && (Date.now() > this.description_save || force)) { this.description_save = 0; this.app.project.description = document.querySelector("#publish-box-textarea").value; @@ -178,11 +204,13 @@ this.Publish = class Publish { project: this.app.project.id, option: "description", value: document.querySelector("#publish-box-textarea").value - }, (msg) => {}); + }, (function(_this) { + return function(msg) {}; + })(this)); } - } + }; - setProjectPublic(pub) { + Publish.prototype.setProjectPublic = function(pub) { if (pub && !this.app.user.flags["validated"]) { return; } @@ -195,22 +223,26 @@ this.Publish = class Publish { this.checkDescriptionSave(true); this.sendProjectPublic(pub); return this.updateCheckList(); - } + }; - sendProjectPublic(pub) { + Publish.prototype.sendProjectPublic = function(pub) { if (this.app.project != null) { return this.app.client.sendRequest({ name: "set_project_public", project: this.app.project.id, - public: pub - }, (msg) => { - if (msg.public != null) { - this.app.project.public = msg.public; - this.app.project.notifyListeners("public"); - return this.loadProject(this.app.project); - } - }); + "public": pub + }, (function(_this) { + return function(msg) { + if (msg["public"] != null) { + _this.app.project["public"] = msg["public"]; + _this.app.project.notifyListeners("public"); + return _this.loadProject(_this.app.project); + } + }; + })(this)); } - } + }; + + return Publish; -}; +})(); diff --git a/static/js/runtime/assetmanager.js b/static/js/runtime/assetmanager.js index 8dc09d93..e4ebc94c 100644 --- a/static/js/runtime/assetmanager.js +++ b/static/js/runtime/assetmanager.js @@ -1,36 +1,50 @@ -this.AssetManager = class AssetManager { - constructor(runtime) { +this.AssetManager = (function() { + function AssetManager(runtime) { this.runtime = runtime; - this.interface = { - loadFont: (font) => { - return this.loadFont(font); - }, - loadModel: (path, scene, callback) => { - return this.loadModel(path, scene, callback); - }, - loadImage: (path, callback) => { - return this.loadImage(path, callback); - }, - loadJSON: (path, callback) => { - return this.loadJSON(path, callback); - }, - loadText: (path, callback) => { - return this.loadText(path, callback); - }, - loadCSV: (path, callback) => { - return this.loadCSV(path, callback); - }, - loadMarkdown: (path, callback) => { - return this.loadMarkdown(path, callback); - } + this["interface"] = { + loadFont: (function(_this) { + return function(font) { + return _this.loadFont(font); + }; + })(this), + loadModel: (function(_this) { + return function(path, scene, callback) { + return _this.loadModel(path, scene, callback); + }; + })(this), + loadImage: (function(_this) { + return function(path, callback) { + return _this.loadImage(path, callback); + }; + })(this), + loadJSON: (function(_this) { + return function(path, callback) { + return _this.loadJSON(path, callback); + }; + })(this), + loadText: (function(_this) { + return function(path, callback) { + return _this.loadText(path, callback); + }; + })(this), + loadCSV: (function(_this) { + return function(path, callback) { + return _this.loadCSV(path, callback); + }; + })(this), + loadMarkdown: (function(_this) { + return function(path, callback) { + return _this.loadMarkdown(path, callback); + }; + })(this) }; } - getInterface() { - return this.interface; - } + AssetManager.prototype.getInterface = function() { + return this["interface"]; + }; - loadFont(font) { + AssetManager.prototype.loadFont = function(font) { var err, file, name, split; if (typeof font !== "string") { return; @@ -39,17 +53,19 @@ this.AssetManager = class AssetManager { split = file.split("-"); name = split[split.length - 1]; try { - font = new FontFace(name, `url(assets/${file}.ttf)`); - return font.load().then(() => { - return document.fonts.add(font); - }); + font = new FontFace(name, "url(assets/" + file + ".ttf)"); + return font.load().then((function(_this) { + return function() { + return document.fonts.add(font); + }; + })(this)); } catch (error) { err = error; return console.error(err); } - } + }; - loadModel(path, scene, callback) { + AssetManager.prototype.loadModel = function(path, scene, callback) { var loader; if (typeof BABYLON === "undefined" || BABYLON === null) { return; @@ -63,16 +79,18 @@ this.AssetManager = class AssetManager { path = path.replace(/\//g, "-"); path += ".glb"; } - return BABYLON.SceneLoader.LoadAssetContainer("", `assets/${path}`, scene, (container) => { - loader.container = container; - loader.ready = 1; - if (callback) { - return callback(container); - } - }); - } + return BABYLON.SceneLoader.LoadAssetContainer("", "assets/" + path, scene, (function(_this) { + return function(container) { + loader.container = container; + loader.ready = 1; + if (callback) { + return callback(container); + } + }; + })(this)); + }; - loadImage(path, callback) { + AssetManager.prototype.loadImage = function(path, callback) { var img, loader; loader = { ready: 0 @@ -81,63 +99,74 @@ this.AssetManager = class AssetManager { path = this.runtime.assets[path].file; } img = new Image; - img.src = `assets/${path}`; - img.onload = () => { - var i; - i = new msImage(img); - loader.image = i; - loader.ready = 1; - if (callback) { - return callback(i); - } - }; + img.src = "assets/" + path; + img.onload = (function(_this) { + return function() { + var i; + i = new msImage(img); + loader.image = i; + loader.ready = 1; + if (callback) { + return callback(i); + } + }; + })(this); return loader; - } + }; - loadJSON(path, callback) { + AssetManager.prototype.loadJSON = function(path, callback) { var loader; path = path.replace(/\//g, "-"); - path = `assets/${path}.json`; + path = "assets/" + path + ".json"; loader = { ready: 0 }; - fetch(path).then((result) => { - return result.json().then((data) => { - loader.data = data; - loader.ready = 1; - if (callback) { - return callback(data); - } - }); - }); + fetch(path).then((function(_this) { + return function(result) { + return result.json().then(function(data) { + loader.data = data; + loader.ready = 1; + if (callback) { + return callback(data); + } + }); + }; + })(this)); return loader; - } + }; - loadText(path, callback, ext = "txt") { + AssetManager.prototype.loadText = function(path, callback, ext) { var loader; + if (ext == null) { + ext = "txt"; + } path = path.replace(/\//g, "-"); - path = `assets/${path}.${ext}`; + path = "assets/" + path + "." + ext; loader = { ready: 0 }; - fetch(path).then((result) => { - return result.text().then((text) => { - loader.text = text; - loader.ready = 1; - if (callback) { - return callback(text); - } - }); - }); + fetch(path).then((function(_this) { + return function(result) { + return result.text().then(function(text) { + loader.text = text; + loader.ready = 1; + if (callback) { + return callback(text); + } + }); + }; + })(this)); return loader; - } + }; - loadCSV(path, callback) { + AssetManager.prototype.loadCSV = function(path, callback) { return this.loadText(path, callback, "csv"); - } + }; - loadMarkdown(path, callback) { + AssetManager.prototype.loadMarkdown = function(path, callback) { return this.loadText(path, callback, "md"); - } + }; + + return AssetManager; -}; +})(); diff --git a/static/js/runtime/audio/sound.js b/static/js/runtime/audio/sound.js index da3968ce..416e5d53 100644 --- a/static/js/runtime/audio/sound.js +++ b/static/js/runtime/audio/sound.js @@ -1,10 +1,10 @@ -this.Sound = class Sound { - constructor(audio, url) { +this.Sound = (function() { + function Sound(audio, url) { var request; this.audio = audio; this.url = url; if (typeof MicroSound !== "undefined" && MicroSound !== null) { - this.class = MicroSound; + this["class"] = MicroSound; } if (this.url instanceof AudioBuffer) { this.buffer = this.url; @@ -14,18 +14,32 @@ this.Sound = class Sound { request = new XMLHttpRequest(); request.open('GET', this.url, true); request.responseType = 'arraybuffer'; - request.onload = () => { - return this.audio.context.decodeAudioData(request.response, (buffer1) => { - this.buffer = buffer1; - return this.ready = 1; - }); - }; + request.onload = (function(_this) { + return function() { + return _this.audio.context.decodeAudioData(request.response, function(buffer1) { + _this.buffer = buffer1; + return _this.ready = 1; + }); + }; + })(this); request.send(); } } - play(volume = 1, pitch = 1, pan = 0, loopit = false) { + Sound.prototype.play = function(volume, pitch, pan, loopit) { var gain, panner, playing, res, source; + if (volume == null) { + volume = 1; + } + if (pitch == null) { + pitch = 1; + } + if (pan == null) { + pan = 0; + } + if (loopit == null) { + loopit = false; + } if (this.buffer == null) { return; } @@ -57,20 +71,24 @@ this.Sound = class Sound { playing = null; if (loopit) { playing = { - stop: () => { - return source.stop(); - } + stop: (function(_this) { + return function() { + return source.stop(); + }; + })(this) }; this.audio.addPlaying(playing); } res = { - stop: () => { - source.stop(); - if (playing) { - this.audio.removePlaying(playing); - } - return 1; - }, + stop: (function(_this) { + return function() { + source.stop(); + if (playing) { + _this.audio.removePlaying(playing); + } + return 1; + }; + })(this), setVolume: function(volume) { return gain.gain.value = Math.max(0, Math.min(1, volume)); }, @@ -89,64 +107,64 @@ this.Sound = class Sound { return res.finished = true; }; return res; - } + }; - static createSoundClass(audiocore) { + Sound.createSoundClass = function(audiocore) { return window.MicroSound = (function() { - var _Class; + _Class.classname = "Sound"; - _Class = class { - constructor(channels, length, sampleRate = 44100) { - var buffer, ch1, ch2, snd; - this.class = MicroSound; - channels = channels === 1 ? 1 : 2; - if (!(length > 1) || !(length < 44100 * 1000)) { - length = 44100; - } - if (!(sampleRate >= 8000) || !(sampleRate <= 96000)) { - sampleRate = 44100; + function _Class(channels, length, sampleRate) { + var buffer, ch1, ch2, snd; + if (sampleRate == null) { + sampleRate = 44100; + } + this["class"] = MicroSound; + channels = channels === 1 ? 1 : 2; + if (!(length > 1) || !(length < 44100 * 1000)) { + length = 44100; + } + if (!(sampleRate >= 8000) || !(sampleRate <= 96000)) { + sampleRate = 44100; + } + buffer = audiocore.context.createBuffer(channels, length, sampleRate); + snd = new Sound(audiocore, buffer); + this.channels = channels; + this.length = length; + this.sampleRate = sampleRate; + ch1 = buffer.getChannelData(0); + if (channels === 2) { + ch2 = buffer.getChannelData(1); + } + this.play = function(volume, pitch, pan, loopit) { + return snd.play(volume, pitch, pan, loopit); + }; + this.write = function(channel, position, value) { + if (channel === 0) { + ch1 = buffer.getChannelData(0); + return ch1[position] = value; + } else if (channels === 2) { + ch2 = buffer.getChannelData(1); + return ch2[position] = value; } - buffer = audiocore.context.createBuffer(channels, length, sampleRate); - snd = new Sound(audiocore, buffer); - this.channels = channels; - this.length = length; - this.sampleRate = sampleRate; - ch1 = buffer.getChannelData(0); - if (channels === 2) { + }; + this.read = function(channel, position) { + if (channel === 0) { + ch1 = buffer.getChannelData(0); + return ch1[position]; + } else if (channels === 2) { ch2 = buffer.getChannelData(1); + return ch2[position]; + } else { + return 0; } - this.play = function(volume, pitch, pan, loopit) { - return snd.play(volume, pitch, pan, loopit); - }; - this.write = function(channel, position, value) { - if (channel === 0) { - ch1 = buffer.getChannelData(0); - return ch1[position] = value; - } else if (channels === 2) { - ch2 = buffer.getChannelData(1); - return ch2[position] = value; - } - }; - this.read = function(channel, position) { - if (channel === 0) { - ch1 = buffer.getChannelData(0); - return ch1[position]; - } else if (channels === 2) { - ch2 = buffer.getChannelData(1); - return ch2[position]; - } else { - return 0; - } - }; - } - - }; - - _Class.classname = "Sound"; + }; + } return _Class; - }).call(this); - } + })(); + }; + + return Sound; -}; +})(); diff --git a/static/js/runtime/m2d/m2d.js b/static/js/runtime/m2d/m2d.js index 210a1b40..52b94e93 100644 --- a/static/js/runtime/m2d/m2d.js +++ b/static/js/runtime/m2d/m2d.js @@ -1,42 +1,62 @@ -var M2D; +var M2D, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; M2D = {}; -M2D.Scene = class Scene extends PIXI.Container { - constructor() { - super(); +M2D.Scene = (function(superClass) { + extend(Scene, superClass); + + function Scene() { + Scene.__super__.constructor.call(this); } - add(child) { + Scene.prototype.add = function(child) { return this.addChild(child); - } + }; + + return Scene; -}; +})(PIXI.Container); -M2D.Camera = class Camera { - constructor(fov = 200, x = 0, y = 0) { - this.fov = fov; - this.x = x; - this.y = y; +M2D.Camera = (function() { + function Camera(fov, x, y) { + this.fov = fov != null ? fov : 200; + this.x = x != null ? x : 0; + this.y = y != null ? y : 0; } -}; + return Camera; + +})(); + +M2D.Group = (function(superClass) { + extend(Group, superClass); -M2D.Group = class Group extends PIXI.Container { - constructor() { - super(); + function Group() { + Group.__super__.constructor.call(this); } -}; + return Group; -M2D.Sprite = class Sprite extends PIXI.Sprite { - constructor(source, width = 20, height = 20) { +})(PIXI.Container); + +M2D.Sprite = (function(superClass) { + extend(Sprite, superClass); + + function Sprite(source, width, height) { + if (width == null) { + width = 20; + } + if (height == null) { + height = 20; + } if (source instanceof Sprite) { - super(PIXI.Texture.from(source.frames[0].canvas)); + Sprite.__super__.constructor.call(this, PIXI.Texture.from(source.frames[0].canvas)); } else if (typeof source === "string" && (M2D.runtime.sprites[source] != null)) { - super(PIXI.Texture.from(M2D.runtime.sprites[source].frames[0].canvas)); + Sprite.__super__.constructor.call(this, PIXI.Texture.from(M2D.runtime.sprites[source].frames[0].canvas)); } else { - super(source); + Sprite.__super__.constructor.call(this, source); } this.width = width; this.height = height; @@ -45,7 +65,9 @@ M2D.Sprite = class Sprite extends PIXI.Sprite { this.scale.y *= -1; } -}; + return Sprite; + +})(PIXI.Sprite); if (PIXI.BaseTexture.defaultOptions != null) { PIXI.BaseTexture.defaultOptions.scaleMode = PIXI.SCALE_MODES.NEAREST; diff --git a/static/js/runtime/microvm.js b/static/js/runtime/microvm.js index 7c38e981..ea335519 100644 --- a/static/js/runtime/microvm.js +++ b/static/js/runtime/microvm.js @@ -1,15 +1,23 @@ -this.MicroVM = class MicroVM { - constructor(meta = {}, global = {}, namespace1 = "/microstudio", preserve_ls = false) { +this.MicroVM = (function() { + function MicroVM(meta, global, namespace1, preserve_ls) { var ctx, err; - this.namespace = namespace1; - this.preserve_ls = preserve_ls; + if (meta == null) { + meta = {}; + } + if (global == null) { + global = {}; + } + this.namespace = namespace1 != null ? namespace1 : "/microstudio"; + this.preserve_ls = preserve_ls != null ? preserve_ls : false; if (meta.print == null) { - meta.print = (text) => { - if (typeof text === "object" && (this.runner != null)) { - text = this.runner.toString(text); - } - return console.info(text); - }; + meta.print = (function(_this) { + return function(text) { + if (typeof text === "object" && (_this.runner != null)) { + text = _this.runner.toString(text); + } + return console.info(text); + }; + })(this); } Array.prototype.insert = function(e) { this.splice(0, 0, e); @@ -127,8 +135,8 @@ this.MicroVM = class MicroVM { }; meta.random = new Random(0); meta.PI = Math.PI; - meta.true = 1; - meta.false = 0; + meta["true"] = 1; + meta["false"] = 0; global.system = { time: Date.now, language: navigator.language, @@ -139,24 +147,28 @@ this.MicroVM = class MicroVM { touch: "ontouchstart" in window ? 1 : 0, gamepad: 0 }, - prompt: (text, callback) => { - return setTimeout((() => { - var args, result; - global.mouse.pressed = 0; - global.touch.touching = 0; - result = window.prompt(text); - if ((callback != null) && typeof callback === "function") { - args = [(result != null ? 1 : 0), result]; - this.context.timeout = Date.now() + 1000; - return callback.apply(null, args); - } - }), 0); - }, - say: (text) => { - return setTimeout((() => { - return window.alert(text); - }), 0); - } + prompt: (function(_this) { + return function(text, callback) { + return setTimeout((function() { + var args, result; + global.mouse.pressed = 0; + global.touch.touching = 0; + result = window.prompt(text); + if ((callback != null) && typeof callback === "function") { + args = [(result != null ? 1 : 0), result]; + _this.context.timeout = Date.now() + 1000; + return callback.apply(null, args); + } + }), 0); + }; + })(this), + say: (function(_this) { + return function(text) { + return setTimeout((function() { + return window.alert(text); + }), 0); + }; + })(this) }; try { global.system.inputs.keyboard = window.matchMedia("(pointer:fine)").matches ? 1 : 0; @@ -193,7 +205,7 @@ this.MicroVM = class MicroVM { this.runner = new Runner(this); } - clearWarnings() { + MicroVM.prototype.clearWarnings = function() { return this.context.warnings = { using_undefined_variable: {}, assigning_field_to_undefined: {}, @@ -201,19 +213,25 @@ this.MicroVM = class MicroVM { assigning_api_variable: {}, assignment_as_condition: {} }; - } + }; - setMeta(key, value) { + MicroVM.prototype.setMeta = function(key, value) { return this.context.meta[key] = value; - } + }; - setGlobal(key, value) { + MicroVM.prototype.setGlobal = function(key, value) { return this.context.global[key] = value; - } + }; - run(program, timeout = 3000, filename = "", callback) { + MicroVM.prototype.run = function(program, timeout, filename, callback) { var err, res; this.program = program; + if (timeout == null) { + timeout = 3000; + } + if (filename == null) { + filename = ""; + } this.error_info = null; this.context.timeout = Date.now() + timeout; this.context.stack_size = 0; @@ -236,7 +254,7 @@ this.MicroVM = class MicroVM { line: this.context.location.token.line, column: this.context.location.token.column }; - console.info(`Error at line: ${this.context.location.token.line} column: ${this.context.location.token.column}`); + console.info("Error at line: " + this.context.location.token.line + " column: " + this.context.location.token.column); } else { this.error_info = { error: err, @@ -246,10 +264,16 @@ this.MicroVM = class MicroVM { console.error(err); return this.storage_service.check(); } - } + }; - call(name, args = [], timeout = 3000) { + MicroVM.prototype.call = function(name, args, timeout) { var err, res; + if (args == null) { + args = []; + } + if (timeout == null) { + timeout = 3000; + } this.error_info = null; this.context.timeout = Date.now() + timeout; this.context.stack_size = 0; @@ -273,18 +297,18 @@ this.MicroVM = class MicroVM { }; } if ((this.context.location != null) && (this.context.location.token != null)) { - console.info(`Error at line: ${this.context.location.token.line} column: ${this.context.location.token.column}`); + console.info("Error at line: " + this.context.location.token.line + " column: " + this.context.location.token.column); } return this.storage_service.check(); } - } + }; - createStorageService() { + MicroVM.prototype.createStorageService = function() { var err, error, ls, namespace, s, service, storage, write_storage; try { ls = window.localStorage; } catch (error1) { - error = error1; // in incognito mode, embedded by an iframe, localStorage isn't available + error = error1; console.info("localStorage not available"); return service = { api: { @@ -307,7 +331,7 @@ this.MicroVM = class MicroVM { write_storage = false; namespace = this.namespace; try { - s = ls.getItem(`ms${namespace}`); + s = ls.getItem("ms" + namespace); if (s) { storage = JSON.parse(s); } @@ -316,46 +340,52 @@ this.MicroVM = class MicroVM { } return service = { api: { - set: (name, value) => { - value = this.storableObject(value); - if ((name != null) && (value != null)) { - storage[name] = value; - write_storage = true; - } - return value; - }, - get: (name) => { - if (name != null) { - if (storage[name] != null) { - return storage[name]; + set: (function(_this) { + return function(name, value) { + value = _this.storableObject(value); + if ((name != null) && (value != null)) { + storage[name] = value; + write_storage = true; + } + return value; + }; + })(this), + get: (function(_this) { + return function(name) { + if (name != null) { + if (storage[name] != null) { + return storage[name]; + } else { + return 0; + } } else { return 0; } - } else { - return 0; - } - } + }; + })(this) }, - check: () => { - if (write_storage) { - write_storage = false; - try { - return ls.setItem(`ms${namespace}`, JSON.stringify(storage)); - } catch (error1) { - err = error1; + check: (function(_this) { + return function() { + if (write_storage) { + write_storage = false; + try { + return ls.setItem("ms" + namespace, JSON.stringify(storage)); + } catch (error1) { + err = error1; + } } - } - } + }; + })(this) }; - } + }; - storableObject(value) { + MicroVM.prototype.storableObject = function(value) { var referenced; referenced = [this.context.global.screen, this.context.global.system, this.context.global.keyboard, this.context.global.audio, this.context.global.gamepad, this.context.global.touch, this.context.global.mouse, this.context.global.sprites, this.context.global.maps]; return this.makeStorableObject(value, referenced); - } + }; - makeStorableObject(value, referenced) { + MicroVM.prototype.makeStorableObject = function(value, referenced) { var i, j, key, len, res, v; if (value == null) { return value; @@ -395,6 +425,8 @@ this.MicroVM = class MicroVM { } else { return value; } - } + }; + + return MicroVM; -}; +})(); diff --git a/static/js/runtime/mpserver.js b/static/js/runtime/mpserver.js index a0c6e230..fdaa053f 100644 --- a/static/js/runtime/mpserver.js +++ b/static/js/runtime/mpserver.js @@ -1,5 +1,5 @@ -this.MPServer = class MPServer { - constructor() { +this.MPServer = (function() { + function MPServer() { var impl; impl = new MPServerImpl(this); this.send = function(data) { @@ -29,86 +29,98 @@ this.MPServer = class MPServer { player.runtime.addServer(impl); } -}; + return MPServer; -this.MPServerImpl = class MPServerImpl { - constructor(_interface) { +})(); + +this.MPServerImpl = (function() { + function MPServerImpl(_interface) { var err; - this.interface = _interface; - this.interface.status = "starting"; + this["interface"] = _interface; + this["interface"].status = "starting"; this.reconnect_delay = 1000; this.clients = {}; this.clients_connected = []; this.clients_disconnected = {}; try { - this.getRelay((address) => { - return this.connect(address); - }); + this.getRelay((function(_this) { + return function(address) { + return _this.connect(address); + }; + })(this)); } catch (error) { err = error; console.error(err); } } - getRelay(callback) { + MPServerImpl.prototype.getRelay = function(callback) { return player.client.sendRequest({ name: "get_relay_server" - }, (msg) => { - var address; - console.info("RELAY SERVER RECEIVED"); - console.info(msg); - if (msg.name === "error") { - this.interface.status = "error"; - return this.interface.error = msg.error; - } else { - address = msg.address; - if (address === "self") { - address = location.origin.replace("http", "ws"); + }, (function(_this) { + return function(msg) { + var address; + console.info("RELAY SERVER RECEIVED"); + console.info(msg); + if (msg.name === "error") { + _this["interface"].status = "error"; + return _this["interface"].error = msg.error; + } else { + address = msg.address; + if (address === "self") { + address = location.origin.replace("http", "ws"); + } + return callback(address); } - return callback(address); - } - }); - } + }; + })(this)); + }; - connect(address) { + MPServerImpl.prototype.connect = function(address) { this.socket = new WebSocket(address); - this.socket.onmessage = (msg) => { - var err; - try { - msg = JSON.parse(msg.data); - switch (msg.name) { - case "mp_update": - this.interface.status = "running"; - return player.runtime.timer(); - case "mp_client_connection": - return this.clientConnected(msg); - case "mp_client_message": - return this.clientMessage(msg); - case "mp_client_disconnected": - return this.clientDisconnected(msg); + this.socket.onmessage = (function(_this) { + return function(msg) { + var err; + try { + msg = JSON.parse(msg.data); + switch (msg.name) { + case "mp_update": + _this["interface"].status = "running"; + return player.runtime.timer(); + case "mp_client_connection": + return _this.clientConnected(msg); + case "mp_client_message": + return _this.clientMessage(msg); + case "mp_client_disconnected": + return _this.clientDisconnected(msg); + } + } catch (error) { + err = error; + return console.error(err); } - } catch (error) { - err = error; - return console.error(err); - } - }; - this.socket.onopen = () => { - var user; - this.interface.status = "running"; - this.reconnect_delay = 1000; - user = location.href; - return this.send({ - name: "mp_start_server", - token: window.ms_server_token, - server_id: ms_project_id - }); - }; - return this.socket.onclose = () => { - return this.interface.status = "disconnected"; - }; - } + }; + })(this); + this.socket.onopen = (function(_this) { + return function() { + var user; + _this["interface"].status = "running"; + _this.reconnect_delay = 1000; + user = location.href; + return _this.send({ + name: "mp_start_server", + token: window.ms_server_token, + server_id: ms_project_id + }); + }; + })(this); + return this.socket.onclose = (function(_this) { + return function() { + return _this["interface"].status = "disconnected"; + }; + })(this); + }; - clientConnected(msg) { + MPServerImpl.prototype.clientConnected = function(msg) { var client; if (msg.client_id == null) { return; @@ -116,9 +128,9 @@ this.MPServerImpl = class MPServerImpl { client = new MPClient(this, msg.client_id); this.clients_connected.push(client); return this.clients[msg.client_id] = client; - } + }; - clientMessage(msg) { + MPServerImpl.prototype.clientMessage = function(msg) { var client; if (msg.client_id == null) { return; @@ -127,9 +139,9 @@ this.MPServerImpl = class MPServerImpl { if (client != null) { return client.message(msg.data); } - } + }; - clientDisconnected(msg) { + MPServerImpl.prototype.clientDisconnected = function(msg) { var client; if (msg.client_id == null) { return; @@ -139,38 +151,38 @@ this.MPServerImpl = class MPServerImpl { if (client != null) { return this.clients_disconnected[client.client_id] = true; } - } + }; - sendMessage(data) { + MPServerImpl.prototype.sendMessage = function(data) { return this.send({ name: "mp_server_message", data: data }); - } + }; - send(data) { + MPServerImpl.prototype.send = function(data) { return this.socket.send(JSON.stringify(data)); - } + }; - update() { + MPServerImpl.prototype.update = function() { var c, client, closed_connections, connection, i, id, j, k, l, len, len1, len2, m, messages, n, new_connections, ref, ref1, ref2, ref3, ref4; new_connections = []; closed_connections = []; - for (i = j = ref = this.interface.active_connections.length - 1; j >= 0; i = j += -1) { - c = this.interface.active_connections[i]; + for (i = j = ref = this["interface"].active_connections.length - 1; j >= 0; i = j += -1) { + c = this["interface"].active_connections[i]; if (this.clients_disconnected[c.id]) { - this.interface.active_connections.splice(i, 1); + this["interface"].active_connections.splice(i, 1); closed_connections.push(c); } } ref1 = this.clients_connected; for (k = 0, len = ref1.length; k < len; k++) { c = ref1[k]; - new_connections.push(c.interface); - this.interface.active_connections.push(c.interface); + new_connections.push(c["interface"]); + this["interface"].active_connections.push(c["interface"]); } - this.interface.new_connections = new_connections; - this.interface.closed_connections = closed_connections; + this["interface"].new_connections = new_connections; + this["interface"].closed_connections = closed_connections; this.clients_disconnected = {}; this.clients_connected = []; ref2 = this.clients; @@ -179,7 +191,7 @@ this.MPServerImpl = class MPServerImpl { client.update(); } messages = []; - ref3 = this.interface.active_connections; + ref3 = this["interface"].active_connections; for (l = 0, len1 = ref3.length; l < len1; l++) { connection = ref3[l]; ref4 = connection.messages; @@ -188,69 +200,77 @@ this.MPServerImpl = class MPServerImpl { messages.push(m); } } - this.interface.messages = messages; - } + this["interface"].messages = messages; + }; - close() { + MPServerImpl.prototype.close = function() { return this.socket.close(); - } + }; + + return MPServerImpl; -}; +})(); -this.MPClient = class MPClient { - constructor(server, client_id) { +this.MPClient = (function() { + function MPClient(server, client_id) { this.server = server; this.client_id = client_id; - this.interface = { + this["interface"] = { id: this.client_id, status: "connected", messages: [], - send: (data) => { - return this.sendMessage(data); - }, - disconnect: () => { - return this.disconnect(); - } + send: (function(_this) { + return function(data) { + return _this.sendMessage(data); + }; + })(this), + disconnect: (function(_this) { + return function() { + return _this.disconnect(); + }; + })(this) }; this.message_buffer = []; } - sendMessage(data) { + MPClient.prototype.sendMessage = function(data) { return this.server.send({ name: "mp_server_message", client_id: this.client_id, data: data }); - } + }; - disconnect() { + MPClient.prototype.disconnect = function() { return this.server.send({ name: "mp_disconnect_client", client_id: this.client_id }); - } + }; - message(msg) { + MPClient.prototype.message = function(msg) { return this.message_buffer.push(msg); - } + }; - disconnected() { - return this.interface.status = "disconnected"; - } + MPClient.prototype.disconnected = function() { + return this["interface"].status = "disconnected"; + }; - update() { + MPClient.prototype.update = function() { var j, len, m, messages, ref; messages = []; ref = this.message_buffer; for (j = 0, len = ref.length; j < len; j++) { m = ref[j]; messages.push({ - connection: this.interface, + connection: this["interface"], data: m }); } - this.interface.messages = messages; + this["interface"].messages = messages; return this.message_buffer = []; - } + }; + + return MPClient; -}; +})(); diff --git a/static/js/runtime/mpserverconnection.js b/static/js/runtime/mpserverconnection.js index 226518c9..c4a748e9 100644 --- a/static/js/runtime/mpserverconnection.js +++ b/static/js/runtime/mpserverconnection.js @@ -1,37 +1,43 @@ -this.MPServerConnection = class MPServerConnection { - constructor(address) { +this.MPServerConnection = (function() { + function MPServerConnection(address) { var impl; this.status = "connecting"; impl = new MPServerConnectionImpl(this, address); - this.send = (data) => { - var err; - try { - impl.sendMessage(data); - return "sent"; - } catch (error) { - err = error; - console.error(err); - return err.toString(); - } - }; - this.close = () => { - var err; - try { - return impl.close(); - } catch (error) { - err = error; - return console.error(err); - } - }; + this.send = (function(_this) { + return function(data) { + var err; + try { + impl.sendMessage(data); + return "sent"; + } catch (error) { + err = error; + console.error(err); + return err.toString(); + } + }; + })(this); + this.close = (function(_this) { + return function() { + var err; + try { + return impl.close(); + } catch (error) { + err = error; + return console.error(err); + } + }; + })(this); this.messages = []; } -}; + return MPServerConnection; + +})(); -this.MPServerConnectionImpl = class MPServerConnectionImpl { - constructor(_interface, address1) { +this.MPServerConnectionImpl = (function() { + function MPServerConnectionImpl(_interface, address1) { var err; - this.interface = _interface; + this["interface"] = _interface; this.address = address1; this.status = "connecting"; this.buffer = []; @@ -39,9 +45,11 @@ this.MPServerConnectionImpl = class MPServerConnectionImpl { this.connect(this.address); } else { try { - this.getRelay((address) => { - return this.connect(address); - }); + this.getRelay((function(_this) { + return function(address) { + return _this.connect(address); + }; + })(this)); } catch (error) { err = error; console.error(err); @@ -51,66 +59,74 @@ this.MPServerConnectionImpl = class MPServerConnectionImpl { player.runtime.addConnection(this); } - getRelay(callback) { + MPServerConnectionImpl.prototype.getRelay = function(callback) { return player.client.sendRequest({ name: "get_relay_server" - }, (msg) => { - var address; - if (msg.name === "error") { - this.interface.status = "error"; - return this.interface.error = msg.error; - } else { - address = msg.address; - if (address === "self") { - address = location.origin.replace("http", "ws"); + }, (function(_this) { + return function(msg) { + var address; + if (msg.name === "error") { + _this["interface"].status = "error"; + return _this["interface"].error = msg.error; + } else { + address = msg.address; + if (address === "self") { + address = location.origin.replace("http", "ws"); + } + return callback(address); } - return callback(address); - } - }); - } + }; + })(this)); + }; - connect(address) { + MPServerConnectionImpl.prototype.connect = function(address) { this.socket = new WebSocket(address); - this.socket.onmessage = (msg) => { - var err; - try { - msg = JSON.parse(msg.data); - switch (msg.name) { - case "mp_server_message": - return this.messages.push(msg.data); + this.socket.onmessage = (function(_this) { + return function(msg) { + var err; + try { + msg = JSON.parse(msg.data); + switch (msg.name) { + case "mp_server_message": + return _this.messages.push(msg.data); + } + } catch (error) { + err = error; + return console.error(err); } - } catch (error) { - err = error; - return console.error(err); - } - }; - this.socket.onopen = () => { - var i, len, m, ref; - this.interface.status = "connected"; - this.send({ - name: "mp_client_connection", - server_id: ms_project_id - }); - ref = this.buffer; - for (i = 0, len = ref.length; i < len; i++) { - m = ref[i]; - this.sendMessage(m); - } - return this.buffer = []; - }; - return this.socket.onclose = () => { - return this.interface.status = "disconnected"; - }; - } + }; + })(this); + this.socket.onopen = (function(_this) { + return function() { + var i, len, m, ref; + _this["interface"].status = "connected"; + _this.send({ + name: "mp_client_connection", + server_id: ms_project_id + }); + ref = _this.buffer; + for (i = 0, len = ref.length; i < len; i++) { + m = ref[i]; + _this.sendMessage(m); + } + return _this.buffer = []; + }; + })(this); + return this.socket.onclose = (function(_this) { + return function() { + return _this["interface"].status = "disconnected"; + }; + })(this); + }; - update() { - if (this.messages.length > 0 || this.interface.messages.length > 0) { - this.interface.messages = this.messages; + MPServerConnectionImpl.prototype.update = function() { + if (this.messages.length > 0 || this["interface"].messages.length > 0) { + this["interface"].messages = this.messages; return this.messages = []; } - } + }; - sendMessage(data) { + MPServerConnectionImpl.prototype.sendMessage = function(data) { if ((this.socket != null) && this.socket.readyState === 1) { return this.send({ name: "mp_client_message", @@ -119,14 +135,16 @@ this.MPServerConnectionImpl = class MPServerConnectionImpl { } else { return this.buffer.push(data); } - } + }; - send(data) { + MPServerConnectionImpl.prototype.send = function(data) { return this.socket.send(JSON.stringify(data)); - } + }; - close() { + MPServerConnectionImpl.prototype.close = function() { return this.socket.close(); - } + }; + + return MPServerConnectionImpl; -}; +})(); diff --git a/static/js/runtime/msimage.js b/static/js/runtime/msimage.js index 8bce3b26..646bc115 100644 --- a/static/js/runtime/msimage.js +++ b/static/js/runtime/msimage.js @@ -1,761 +1,776 @@ var b, j, len1, ref; this.msImage = (function() { - class msImage { - constructor(width, height, centered = false) { - this.width = width; - this.height = height; - this.centered = centered; - this.class = msImage; - if (this.width instanceof Image) { - this.image = this.width; - this.width = this.image.width; - this.height = this.image.height; - } else if (this.width instanceof HTMLCanvasElement) { - this.canvas = this.width; - this.width = this.canvas.width; - this.height = this.canvas.height; - } else { - this.canvas = document.createElement("canvas"); - this.canvas.width = this.width = Math.round(this.width); - this.canvas.height = this.height = Math.round(this.height); - } - } + msImage.classname = "Image"; - setRGB(x, y, r, g, b) { - this.initContext(); - if (this.pixeldata == null) { - this.pixeldata = this.context.getImageData(0, 0, 1, 1); - } - if (r.R != null) { - this.pixeldata.data[0] = r.R; - this.pixeldata.data[1] = r.G; - this.pixeldata.data[2] = r.B; - } else { - this.pixeldata.data[0] = r; - this.pixeldata.data[1] = g; - this.pixeldata.data[2] = b; - } - this.pixeldata.data[3] = 255; - return this.context.putImageData(this.pixeldata, x, y); - } + function msImage(width, height, centered) { + this.width = width; + this.height = height; + this.centered = centered != null ? centered : false; + this["class"] = msImage; + if (this.width instanceof Image) { + this.image = this.width; + this.width = this.image.width; + this.height = this.image.height; + } else if (this.width instanceof HTMLCanvasElement) { + this.canvas = this.width; + this.width = this.canvas.width; + this.height = this.canvas.height; + } else { + this.canvas = document.createElement("canvas"); + this.canvas.width = this.width = Math.round(this.width); + this.canvas.height = this.height = Math.round(this.height); + } + } + + msImage.prototype.setRGB = function(x, y, r, g, b) { + this.initContext(); + if (this.pixeldata == null) { + this.pixeldata = this.context.getImageData(0, 0, 1, 1); + } + if (r.R != null) { + this.pixeldata.data[0] = r.R; + this.pixeldata.data[1] = r.G; + this.pixeldata.data[2] = r.B; + } else { + this.pixeldata.data[0] = r; + this.pixeldata.data[1] = g; + this.pixeldata.data[2] = b; + } + this.pixeldata.data[3] = 255; + return this.context.putImageData(this.pixeldata, x, y); + }; - setRGBA(x, y, r, g, b, a) { - this.initContext(); - if (this.pixeldata == null) { - this.pixeldata = this.context.getImageData(0, 0, 1, 1); - } - if (r.R != null) { - this.pixeldata.data[0] = r.R; - this.pixeldata.data[1] = r.G; - this.pixeldata.data[2] = r.B; - this.pixeldata.data[3] = r.A != null ? r.A : 255; - } else { - this.pixeldata.data[0] = r; - this.pixeldata.data[1] = g; - this.pixeldata.data[2] = b; - this.pixeldata.data[3] = a; - } - return this.context.putImageData(this.pixeldata, x, y); - } + msImage.prototype.setRGBA = function(x, y, r, g, b, a) { + this.initContext(); + if (this.pixeldata == null) { + this.pixeldata = this.context.getImageData(0, 0, 1, 1); + } + if (r.R != null) { + this.pixeldata.data[0] = r.R; + this.pixeldata.data[1] = r.G; + this.pixeldata.data[2] = r.B; + this.pixeldata.data[3] = r.A != null ? r.A : 255; + } else { + this.pixeldata.data[0] = r; + this.pixeldata.data[1] = g; + this.pixeldata.data[2] = b; + this.pixeldata.data[3] = a; + } + return this.context.putImageData(this.pixeldata, x, y); + }; - getRGB(x, y, result = {}) { - var d; - this.initContext(); - d = this.context.getImageData(x, y, 1, 1); - result.R = d.data[0]; - result.G = d.data[1]; - result.B = d.data[2]; - return result; - } + msImage.prototype.getRGB = function(x, y, result) { + var d; + if (result == null) { + result = {}; + } + this.initContext(); + d = this.context.getImageData(x, y, 1, 1); + result.R = d.data[0]; + result.G = d.data[1]; + result.B = d.data[2]; + return result; + }; - getRGBA(x, y, result = {}) { - var d; - this.initContext(); - d = this.context.getImageData(x, y, 1, 1); - result.R = d.data[0]; - result.G = d.data[1]; - result.B = d.data[2]; - result.A = d.data[3]; - return result; - } + msImage.prototype.getRGBA = function(x, y, result) { + var d; + if (result == null) { + result = {}; + } + this.initContext(); + d = this.context.getImageData(x, y, 1, 1); + result.R = d.data[0]; + result.G = d.data[1]; + result.B = d.data[2]; + result.A = d.data[3]; + return result; + }; - initContext() { - if (this.context != null) { - return; - } - if ((this.canvas == null) && (this.image != null)) { - this.canvas = document.createElement("canvas"); - this.canvas.width = this.image.width; - this.canvas.height = this.image.height; - this.context = this.canvas.getContext("2d"); - this.context.drawImage(this.image, 0, 0); - this.image = null; - } - this.alpha = 1; - this.pixelated = 1; - this.line_width = 1; - this.context = this.canvas.getContext("2d"); - this.context.lineCap = "round"; - if (this.centered) { - this.translation_x = this.width / 2; - this.translation_y = this.height / 2; - this.rotation = 0; - this.scale_x = 1; - this.scale_y = -1; - this.image_transform = true; - this.anchor_x = 0; - this.anchor_y = 0; - this.object_scale_y = -1; - } else { - this.translation_x = 0; - this.translation_y = 0; - this.rotation = 0; - this.scale_x = 1; - this.scale_y = 1; - this.image_transform = false; - this.anchor_x = -1; - this.anchor_y = 1; - this.object_scale_y = 1; - } - this.object_rotation = 0; - this.object_scale_x = 1; - return this.font = "BitCell"; - } - - clear(color) { - var blending_save, c, s; - this.initContext(); - c = this.context.fillStyle; - s = this.context.strokeStyle; - blending_save = this.context.globalCompositeOperation; - this.context.globalAlpha = 1; - this.context.globalCompositeOperation = "source-over"; - if (color != null) { - this.setColor(color); - } else { - this.context.fillStyle = "#000"; - } - this.context.fillRect(0, 0, this.width, this.height); - this.context.fillStyle = c; - this.context.strokeStyle = s; - return this.context.globalCompositeOperation = blending_save; + msImage.prototype.initContext = function() { + if (this.context != null) { + return; } + if ((this.canvas == null) && (this.image != null)) { + this.canvas = document.createElement("canvas"); + this.canvas.width = this.image.width; + this.canvas.height = this.image.height; + this.context = this.canvas.getContext("2d"); + this.context.drawImage(this.image, 0, 0); + this.image = null; + } + this.alpha = 1; + this.pixelated = 1; + this.line_width = 1; + this.context = this.canvas.getContext("2d"); + this.context.lineCap = "round"; + if (this.centered) { + this.translation_x = this.width / 2; + this.translation_y = this.height / 2; + this.rotation = 0; + this.scale_x = 1; + this.scale_y = -1; + this.image_transform = true; + this.anchor_x = 0; + this.anchor_y = 0; + this.object_scale_y = -1; + } else { + this.translation_x = 0; + this.translation_y = 0; + this.rotation = 0; + this.scale_x = 1; + this.scale_y = 1; + this.image_transform = false; + this.anchor_x = -1; + this.anchor_y = 1; + this.object_scale_y = 1; + } + this.object_rotation = 0; + this.object_scale_x = 1; + return this.font = "BitCell"; + }; - setColor(color) { - this.initContext(); - if (color == null) { - return; - } - if (typeof color === "string") { - this.context.fillStyle = color; - return this.context.strokeStyle = color; - } + msImage.prototype.clear = function(color) { + var blending_save, c, s; + this.initContext(); + c = this.context.fillStyle; + s = this.context.strokeStyle; + blending_save = this.context.globalCompositeOperation; + this.context.globalAlpha = 1; + this.context.globalCompositeOperation = "source-over"; + if (color != null) { + this.setColor(color); + } else { + this.context.fillStyle = "#000"; } + this.context.fillRect(0, 0, this.width, this.height); + this.context.fillStyle = c; + this.context.strokeStyle = s; + return this.context.globalCompositeOperation = blending_save; + }; - setAlpha(alpha) { - this.initContext(); - return this.alpha = alpha; + msImage.prototype.setColor = function(color) { + this.initContext(); + if (color == null) { + return; } - - setPixelated(pixelated) { - this.initContext(); - return this.pixelated = pixelated; + if (typeof color === "string") { + this.context.fillStyle = color; + return this.context.strokeStyle = color; } + }; - setBlending(blending) { - this.initContext(); - blending = BLENDING_MODES[blending || "normal"] || "source-over"; - return this.context.globalCompositeOperation = blending; - } + msImage.prototype.setAlpha = function(alpha) { + this.initContext(); + return this.alpha = alpha; + }; - setLineWidth(line_width) { - this.initContext(); - return this.line_width = line_width; - } + msImage.prototype.setPixelated = function(pixelated) { + this.initContext(); + return this.pixelated = pixelated; + }; - setLineDash(dash) { - this.initContext(); - if (!Array.isArray(dash)) { - return this.context.setLineDash([]); - } else { - return this.context.setLineDash(dash); - } - } + msImage.prototype.setBlending = function(blending) { + this.initContext(); + blending = BLENDING_MODES[blending || "normal"] || "source-over"; + return this.context.globalCompositeOperation = blending; + }; - setLinearGradient(x1, y1, x2, y2, c1, c2) { - var grd; - this.initContext(); - grd = this.context.createLinearGradient(x1, y1, x2, y2); - grd.addColorStop(0, c1); - grd.addColorStop(1, c2); - this.context.fillStyle = grd; - return this.context.strokeStyle = grd; - } + msImage.prototype.setLineWidth = function(line_width) { + this.initContext(); + return this.line_width = line_width; + }; - setRadialGradient(x, y, radius, c1, c2) { - var grd; - this.initContext(); - grd = this.context.createRadialGradient(x, y, 0, x, y, radius); - grd.addColorStop(0, c1); - grd.addColorStop(1, c2); - this.context.fillStyle = grd; - return this.context.strokeStyle = grd; + msImage.prototype.setLineDash = function(dash) { + this.initContext(); + if (!Array.isArray(dash)) { + return this.context.setLineDash([]); + } else { + return this.context.setLineDash(dash); } + }; - setFont(font) { - return this.font = font || "Verdana"; - } + msImage.prototype.setLinearGradient = function(x1, y1, x2, y2, c1, c2) { + var grd; + this.initContext(); + grd = this.context.createLinearGradient(x1, y1, x2, y2); + grd.addColorStop(0, c1); + grd.addColorStop(1, c2); + this.context.fillStyle = grd; + return this.context.strokeStyle = grd; + }; - setTranslation(translation_x, translation_y) { - this.initContext(); - this.translation_x = translation_x; - this.translation_y = translation_y; - if (!isFinite(this.translation_x)) { - this.translation_x = 0; - } - if (!isFinite(this.translation_y)) { - this.translation_y = 0; - } - return this.updateScreenTransform(); - } + msImage.prototype.setRadialGradient = function(x, y, radius, c1, c2) { + var grd; + this.initContext(); + grd = this.context.createRadialGradient(x, y, 0, x, y, radius); + grd.addColorStop(0, c1); + grd.addColorStop(1, c2); + this.context.fillStyle = grd; + return this.context.strokeStyle = grd; + }; - setScale(scale_x, scale_y) { - this.initContext(); - this.scale_x = scale_x; - this.scale_y = scale_y; - if (!isFinite(this.scale_x) || this.scale_x === 0) { - this.scale_x = 1; - } - if (!isFinite(this.scale_y) || this.scale_y === 0) { - this.scale_y = 1; - } - return this.updateScreenTransform(); - } + msImage.prototype.setFont = function(font) { + return this.font = font || "Verdana"; + }; - setRotation(rotation) { - this.initContext(); - this.rotation = rotation; - if (!isFinite(this.rotation)) { - this.rotation = 0; - } - return this.updateScreenTransform(); + msImage.prototype.setTranslation = function(translation_x, translation_y) { + this.initContext(); + this.translation_x = translation_x; + this.translation_y = translation_y; + if (!isFinite(this.translation_x)) { + this.translation_x = 0; + } + if (!isFinite(this.translation_y)) { + this.translation_y = 0; } + return this.updateScreenTransform(); + }; - updateScreenTransform() { - return this.image_transform = this.translation_x !== 0 || this.translation_y !== 0 || this.scale_x !== 1 || this.scale_y !== 1 || this.rotation !== 0; + msImage.prototype.setScale = function(scale_x, scale_y) { + this.initContext(); + this.scale_x = scale_x; + this.scale_y = scale_y; + if (!isFinite(this.scale_x) || this.scale_x === 0) { + this.scale_x = 1; } + if (!isFinite(this.scale_y) || this.scale_y === 0) { + this.scale_y = 1; + } + return this.updateScreenTransform(); + }; - setDrawAnchor(anchor_x, anchor_y) { - this.initContext(); - this.anchor_x = anchor_x; - this.anchor_y = anchor_y; - if (typeof this.anchor_x !== "number") { - this.anchor_x = 0; - } - if (typeof this.anchor_y !== "number") { - return this.anchor_y = 0; - } + msImage.prototype.setRotation = function(rotation) { + this.initContext(); + this.rotation = rotation; + if (!isFinite(this.rotation)) { + this.rotation = 0; } + return this.updateScreenTransform(); + }; + + msImage.prototype.updateScreenTransform = function() { + return this.image_transform = this.translation_x !== 0 || this.translation_y !== 0 || this.scale_x !== 1 || this.scale_y !== 1 || this.rotation !== 0; + }; - setDrawRotation(object_rotation) { - this.initContext(); - return this.object_rotation = object_rotation; + msImage.prototype.setDrawAnchor = function(anchor_x, anchor_y) { + this.initContext(); + this.anchor_x = anchor_x; + this.anchor_y = anchor_y; + if (typeof this.anchor_x !== "number") { + this.anchor_x = 0; } + if (typeof this.anchor_y !== "number") { + return this.anchor_y = 0; + } + }; + + msImage.prototype.setDrawRotation = function(object_rotation) { + this.initContext(); + return this.object_rotation = object_rotation; + }; - setDrawScale(object_scale_x, object_scale_y = object_scale_x) { - this.initContext(); - this.object_scale_x = object_scale_x; - return this.object_scale_y = object_scale_y; + msImage.prototype.setDrawScale = function(object_scale_x, object_scale_y) { + if (object_scale_y == null) { + object_scale_y = object_scale_x; } + this.initContext(); + this.object_scale_x = object_scale_x; + return this.object_scale_y = object_scale_y; + }; - initDrawOp(x, y, object_transform = true) { - var res; - res = false; - if (this.image_transform) { + msImage.prototype.initDrawOp = function(x, y, object_transform) { + var res; + if (object_transform == null) { + object_transform = true; + } + res = false; + if (this.image_transform) { + this.context.save(); + res = true; + this.context.translate(this.translation_x, this.translation_y); + this.context.scale(this.scale_x, this.scale_y); + this.context.rotate(this.rotation / 180 * Math.PI); + this.context.translate(x, y); + } + if (object_transform && (this.object_rotation !== 0 || this.object_scale_x !== 1 || this.object_scale_y !== 1)) { + if (!res) { this.context.save(); res = true; - this.context.translate(this.translation_x, this.translation_y); - this.context.scale(this.scale_x, this.scale_y); - this.context.rotate(this.rotation / 180 * Math.PI); this.context.translate(x, y); } - if (object_transform && (this.object_rotation !== 0 || this.object_scale_x !== 1 || this.object_scale_y !== 1)) { - if (!res) { - this.context.save(); - res = true; - this.context.translate(x, y); - } - if (this.object_rotation !== 0) { - this.context.rotate(this.object_rotation / 180 * Math.PI); - } - if (this.object_scale_x !== 1 || this.object_scale_y !== 1) { - this.context.scale(this.object_scale_x, this.object_scale_y); - } + if (this.object_rotation !== 0) { + this.context.rotate(this.object_rotation / 180 * Math.PI); + } + if (this.object_scale_x !== 1 || this.object_scale_y !== 1) { + this.context.scale(this.object_scale_x, this.object_scale_y); } - return res; } + return res; + }; - closeDrawOp(x, y) { - return this.context.restore(); - } + msImage.prototype.closeDrawOp = function(x, y) { + return this.context.restore(); + }; - fillRect(x, y, w, h, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - if (this.initDrawOp(x, y)) { - this.context.fillRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); - return this.closeDrawOp(x, y); - } else { - return this.context.fillRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); - } + msImage.prototype.fillRect = function(x, y, w, h, color) { + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + if (this.initDrawOp(x, y)) { + this.context.fillRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); + return this.closeDrawOp(x, y); + } else { + return this.context.fillRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); } + }; - fillRoundRect(x, y, w, h, round = 10, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - if (this.initDrawOp(x, y)) { - this.context.fillRoundRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h, round); - return this.closeDrawOp(x, y); - } else { - return this.context.fillRoundRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h, round); - } + msImage.prototype.fillRoundRect = function(x, y, w, h, round, color) { + if (round == null) { + round = 10; } - - fillRound(x, y, w, h, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - w = Math.abs(w); - h = Math.abs(h); - if (this.initDrawOp(x, y)) { - this.context.beginPath(); - this.context.ellipse(-this.anchor_x * w / 2, 0 + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); - this.context.fill(); - return this.closeDrawOp(x, y); - } else { - this.context.beginPath(); - this.context.ellipse(x - this.anchor_x * w / 2, y + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); - return this.context.fill(); - } + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + if (this.initDrawOp(x, y)) { + this.context.fillRoundRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h, round); + return this.closeDrawOp(x, y); + } else { + return this.context.fillRoundRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h, round); } + }; - drawRect(x, y, w, h, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (this.initDrawOp(x, y)) { - this.context.strokeRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); - return this.closeDrawOp(x, y); - } else { - return this.context.strokeRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); - } + msImage.prototype.fillRound = function(x, y, w, h, color) { + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + w = Math.abs(w); + h = Math.abs(h); + if (this.initDrawOp(x, y)) { + this.context.beginPath(); + this.context.ellipse(-this.anchor_x * w / 2, 0 + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); + this.context.fill(); + return this.closeDrawOp(x, y); + } else { + this.context.beginPath(); + this.context.ellipse(x - this.anchor_x * w / 2, y + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); + return this.context.fill(); } + }; - drawRoundRect(x, y, w, h, round = 10, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (this.initDrawOp(x, y)) { - this.context.strokeRoundRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h, round); - return this.closeDrawOp(x, y); - } else { - return this.context.strokeRoundRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h, round); - } + msImage.prototype.drawRect = function(x, y, w, h, color) { + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (this.initDrawOp(x, y)) { + this.context.strokeRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); + return this.closeDrawOp(x, y); + } else { + return this.context.strokeRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); } + }; - drawRound(x, y, w, h, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - w = Math.abs(w); - h = Math.abs(h); - if (this.initDrawOp(x, y)) { - this.context.beginPath(); - this.context.ellipse(0 - this.anchor_x * w / 2, 0 + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); - this.context.stroke(); - return this.closeDrawOp(x, y); - } else { - this.context.beginPath(); - this.context.ellipse(x - this.anchor_x * w / 2, y + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); - return this.context.stroke(); - } + msImage.prototype.drawRoundRect = function(x, y, w, h, round, color) { + if (round == null) { + round = 10; } - - drawLine(x1, y1, x2, y2, color) { - var transform; - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - transform = this.initDrawOp(0, 0, false); - this.context.beginPath(); - this.context.moveTo(x1, y1); - this.context.lineTo(x2, y2); - this.context.stroke(); - if (transform) { - return this.closeDrawOp(); - } + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (this.initDrawOp(x, y)) { + this.context.strokeRoundRect(-w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h, round); + return this.closeDrawOp(x, y); + } else { + return this.context.strokeRoundRect(x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h, round); } + }; - drawPolyline() { - var args, i, j, len, ref, transform; - args = arguments; - this.initContext(); - if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { - this.setColor(args[args.length - 1]); - } - if (Array.isArray(args[0])) { - if ((args[1] != null) && typeof args[1] === "string") { - this.setColor(args[1]); - } - args = args[0]; - } - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (args.length < 4) { - return; - } - len = Math.floor(args.length / 2); - transform = this.initDrawOp(0, 0, false); + msImage.prototype.drawRound = function(x, y, w, h, color) { + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + w = Math.abs(w); + h = Math.abs(h); + if (this.initDrawOp(x, y)) { this.context.beginPath(); - this.context.moveTo(args[0], args[1]); - for (i = j = 1, ref = len - 1; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - this.context.lineTo(args[i * 2], args[i * 2 + 1]); - } + this.context.ellipse(0 - this.anchor_x * w / 2, 0 + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); this.context.stroke(); - if (transform) { - return this.closeDrawOp(); - } - } - - drawPolygon() { - var args, i, j, len, ref, transform; - args = arguments; - this.initContext(); - if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { - this.setColor(args[args.length - 1]); - } - if (Array.isArray(args[0])) { - if ((args[1] != null) && typeof args[1] === "string") { - this.setColor(args[1]); - } - args = args[0]; - } - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (args.length < 4) { - return; - } - len = Math.floor(args.length / 2); - transform = this.initDrawOp(0, 0, false); + return this.closeDrawOp(x, y); + } else { this.context.beginPath(); - this.context.moveTo(args[0], args[1]); - for (i = j = 1, ref = len - 1; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - this.context.lineTo(args[i * 2], args[i * 2 + 1]); - } - this.context.closePath(); - this.context.stroke(); - if (transform) { - return this.closeDrawOp(); - } + this.context.ellipse(x - this.anchor_x * w / 2, y + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); + return this.context.stroke(); } + }; - fillPolygon() { - var args, i, j, len, ref, transform; - args = arguments; - this.initContext(); - if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { - this.setColor(args[args.length - 1]); - } - if (Array.isArray(args[0])) { - if ((args[1] != null) && typeof args[1] === "string") { - this.setColor(args[1]); - } - args = args[0]; - } - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (args.length < 4) { - return; - } - len = Math.floor(args.length / 2); - transform = this.initDrawOp(0, 0, false); - this.context.beginPath(); - this.context.moveTo(args[0], args[1]); - for (i = j = 1, ref = len - 1; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - this.context.lineTo(args[i * 2], args[i * 2 + 1]); - } - this.context.fill(); - if (transform) { - return this.closeDrawOp(); - } + msImage.prototype.drawLine = function(x1, y1, x2, y2, color) { + var transform; + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + transform = this.initDrawOp(0, 0, false); + this.context.beginPath(); + this.context.moveTo(x1, y1); + this.context.lineTo(x2, y2); + this.context.stroke(); + if (transform) { + return this.closeDrawOp(); } + }; - drawQuadCurve() { - var args, index, len, transform; - args = arguments; - this.initContext(); - if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { - this.setColor(args[args.length - 1]); - } - if (Array.isArray(args[0])) { - if ((args[1] != null) && typeof args[1] === "string") { - this.setColor(args[1]); - } - args = args[0]; - } - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (args.length < 4) { - return; - } - len = Math.floor(args.length / 2); - transform = this.initDrawOp(0, 0, false); - this.context.beginPath(); - this.context.moveTo(args[0], args[1]); - index = 2; - while (index <= args.length - 4) { - this.context.quadraticCurveTo(args[index], args[index + 1], args[index + 2], args[index + 3]); - index += 4; - } - this.context.stroke(); - if (transform) { - return this.closeDrawOp(); + msImage.prototype.drawPolyline = function() { + var args, i, j, len, ref, transform; + args = arguments; + this.initContext(); + if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { + this.setColor(args[args.length - 1]); + } + if (Array.isArray(args[0])) { + if ((args[1] != null) && typeof args[1] === "string") { + this.setColor(args[1]); } + args = args[0]; + } + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (args.length < 4) { + return; } + len = Math.floor(args.length / 2); + transform = this.initDrawOp(0, 0, false); + this.context.beginPath(); + this.context.moveTo(args[0], args[1]); + for (i = j = 1, ref = len - 1; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + this.context.lineTo(args[i * 2], args[i * 2 + 1]); + } + this.context.stroke(); + if (transform) { + return this.closeDrawOp(); + } + }; - drawBezierCurve() { - var args, index, len, transform; - args = arguments; - this.initContext(); - if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { - this.setColor(args[args.length - 1]); - } - if (Array.isArray(args[0])) { - if ((args[1] != null) && typeof args[1] === "string") { - this.setColor(args[1]); - } - args = args[0]; - } - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (args.length < 4) { - return; - } - len = Math.floor(args.length / 2); - transform = this.initDrawOp(0, 0, false); - this.context.beginPath(); - this.context.moveTo(args[0], args[1]); - index = 2; - while (index <= args.length - 6) { - this.context.bezierCurveTo(args[index], args[index + 1], args[index + 2], args[index + 3], args[index + 4], args[index + 5]); - index += 6; - } - this.context.stroke(); - if (transform) { - return this.closeDrawOp(); + msImage.prototype.drawPolygon = function() { + var args, i, j, len, ref, transform; + args = arguments; + this.initContext(); + if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { + this.setColor(args[args.length - 1]); + } + if (Array.isArray(args[0])) { + if ((args[1] != null) && typeof args[1] === "string") { + this.setColor(args[1]); } + args = args[0]; + } + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (args.length < 4) { + return; + } + len = Math.floor(args.length / 2); + transform = this.initDrawOp(0, 0, false); + this.context.beginPath(); + this.context.moveTo(args[0], args[1]); + for (i = j = 1, ref = len - 1; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + this.context.lineTo(args[i * 2], args[i * 2 + 1]); + } + this.context.closePath(); + this.context.stroke(); + if (transform) { + return this.closeDrawOp(); } + }; - drawArc(x, y, radius, angle1, angle2, ccw, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (this.initDrawOp(x, y)) { - this.context.beginPath(); - this.context.arc(0, 0, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); - this.context.stroke(); - return this.closeDrawOp(x, -y); - } else { - this.context.beginPath(); - this.context.arc(x, y, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); - return this.context.stroke(); + msImage.prototype.fillPolygon = function() { + var args, i, j, len, ref, transform; + args = arguments; + this.initContext(); + if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { + this.setColor(args[args.length - 1]); + } + if (Array.isArray(args[0])) { + if ((args[1] != null) && typeof args[1] === "string") { + this.setColor(args[1]); } + args = args[0]; + } + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (args.length < 4) { + return; + } + len = Math.floor(args.length / 2); + transform = this.initDrawOp(0, 0, false); + this.context.beginPath(); + this.context.moveTo(args[0], args[1]); + for (i = j = 1, ref = len - 1; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + this.context.lineTo(args[i * 2], args[i * 2 + 1]); + } + this.context.fill(); + if (transform) { + return this.closeDrawOp(); } + }; - fillArc(x, y, radius, angle1, angle2, ccw, color) { - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.lineWidth = this.line_width; - if (this.initDrawOp(x, y)) { - this.context.beginPath(); - this.context.arc(0, 0, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); - this.context.fill(); - return this.closeDrawOp(x, -y); - } else { - this.context.beginPath(); - this.context.arc(x, y, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); - return this.context.fill(); - } + msImage.prototype.drawQuadCurve = function() { + var args, index, len, transform; + args = arguments; + this.initContext(); + if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { + this.setColor(args[args.length - 1]); + } + if (Array.isArray(args[0])) { + if ((args[1] != null) && typeof args[1] === "string") { + this.setColor(args[1]); + } + args = args[0]; + } + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (args.length < 4) { + return; + } + len = Math.floor(args.length / 2); + transform = this.initDrawOp(0, 0, false); + this.context.beginPath(); + this.context.moveTo(args[0], args[1]); + index = 2; + while (index <= args.length - 4) { + this.context.quadraticCurveTo(args[index], args[index + 1], args[index + 2], args[index + 3]); + index += 4; + } + this.context.stroke(); + if (transform) { + return this.closeDrawOp(); } + }; - textWidth(text, size) { - this.initContext(); - this.context.font = `${size}pt ${this.font}`; - return this.context.measureText(text).width; + msImage.prototype.drawBezierCurve = function() { + var args, index, len, transform; + args = arguments; + this.initContext(); + if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { + this.setColor(args[args.length - 1]); + } + if (Array.isArray(args[0])) { + if ((args[1] != null) && typeof args[1] === "string") { + this.setColor(args[1]); + } + args = args[0]; + } + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (args.length < 4) { + return; + } + len = Math.floor(args.length / 2); + transform = this.initDrawOp(0, 0, false); + this.context.beginPath(); + this.context.moveTo(args[0], args[1]); + index = 2; + while (index <= args.length - 6) { + this.context.bezierCurveTo(args[index], args[index + 1], args[index + 2], args[index + 3], args[index + 4], args[index + 5]); + index += 6; + } + this.context.stroke(); + if (transform) { + return this.closeDrawOp(); } + }; - drawText(text, x, y, size, color) { - var h, w; - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.font = `${size}pt ${this.font}`; - this.context.textAlign = "center"; - this.context.textBaseline = "middle"; - w = this.context.measureText(text).width; - h = size; - if (this.initDrawOp(x, y)) { - this.context.fillText(text, 0 - this.anchor_x * w / 2, 0 + this.anchor_y * h / 2); - return this.closeDrawOp(x, y); - } else { - return this.context.fillText(text, x - this.anchor_x * w / 2, y + this.anchor_y * h / 2); - } + msImage.prototype.drawArc = function(x, y, radius, angle1, angle2, ccw, color) { + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (this.initDrawOp(x, y)) { + this.context.beginPath(); + this.context.arc(0, 0, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); + this.context.stroke(); + return this.closeDrawOp(x, -y); + } else { + this.context.beginPath(); + this.context.arc(x, y, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); + return this.context.stroke(); } + }; - drawTextOutline(text, x, y, size, color) { - var h, w; - this.initContext(); - this.setColor(color); - this.context.globalAlpha = this.alpha; - this.context.font = `${size}pt ${this.font}`; - this.context.lineWidth = this.line_width; - this.context.textAlign = "center"; - this.context.textBaseline = "middle"; - w = this.context.measureText(text).width; - h = size; - if (this.initDrawOp(x, y)) { - this.context.strokeText(text, 0 - this.anchor_x * w / 2, 0 + this.anchor_y * h / 2); - return this.closeDrawOp(x, y); - } else { - return this.context.strokeText(text, x - this.anchor_x * w / 2, y + this.anchor_y * h / 2); - } + msImage.prototype.fillArc = function(x, y, radius, angle1, angle2, ccw, color) { + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.lineWidth = this.line_width; + if (this.initDrawOp(x, y)) { + this.context.beginPath(); + this.context.arc(0, 0, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); + this.context.fill(); + return this.closeDrawOp(x, -y); + } else { + this.context.beginPath(); + this.context.arc(x, y, radius, angle1 / 180 * Math.PI, angle2 / 180 * Math.PI, ccw); + return this.context.fill(); } + }; - getSpriteFrame(sprite) { - var dt, frame, s; - frame = null; - if (typeof sprite === "string") { - s = window.player.runtime.sprites[sprite]; - if (s != null) { - sprite = s; - } else { - s = sprite.split("."); - if (s.length > 1) { - sprite = window.player.runtime.sprites[s[0]]; - frame = s[1] | 0; - } - } - } else if (sprite instanceof msImage) { - return sprite.canvas || sprite.image; - } - if ((sprite == null) || !sprite.ready) { - return null; - } - if (sprite.frames.length > 1) { - if (frame == null) { - dt = 1000 / sprite.fps; - frame = Math.floor((Date.now() - sprite.animation_start) / dt) % sprite.frames.length; - } - if (frame >= 0 && frame < sprite.frames.length) { - return sprite.frames[frame].canvas; - } else { - return sprite.frames[0].canvas; - } - } else if (sprite.frames[0] != null) { - return sprite.frames[0].canvas; - } else { - return null; - } + msImage.prototype.textWidth = function(text, size) { + this.initContext(); + this.context.font = size + "pt " + this.font; + return this.context.measureText(text).width; + }; + + msImage.prototype.drawText = function(text, x, y, size, color) { + var h, w; + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.font = size + "pt " + this.font; + this.context.textAlign = "center"; + this.context.textBaseline = "middle"; + w = this.context.measureText(text).width; + h = size; + if (this.initDrawOp(x, y)) { + this.context.fillText(text, 0 - this.anchor_x * w / 2, 0 + this.anchor_y * h / 2); + return this.closeDrawOp(x, y); + } else { + return this.context.fillText(text, x - this.anchor_x * w / 2, y + this.anchor_y * h / 2); } + }; - drawImage(sprite, x, y, w, h) { - return this.drawSprite(sprite, x, y, w, h); + msImage.prototype.drawTextOutline = function(text, x, y, size, color) { + var h, w; + this.initContext(); + this.setColor(color); + this.context.globalAlpha = this.alpha; + this.context.font = size + "pt " + this.font; + this.context.lineWidth = this.line_width; + this.context.textAlign = "center"; + this.context.textBaseline = "middle"; + w = this.context.measureText(text).width; + h = size; + if (this.initDrawOp(x, y)) { + this.context.strokeText(text, 0 - this.anchor_x * w / 2, 0 + this.anchor_y * h / 2); + return this.closeDrawOp(x, y); + } else { + return this.context.strokeText(text, x - this.anchor_x * w / 2, y + this.anchor_y * h / 2); } + }; - drawSprite(sprite, x, y, w, h) { - var canvas; - this.initContext(); - canvas = this.getSpriteFrame(sprite); - if (canvas == null) { - return; - } - if (w == null) { - w = canvas.width; - } - if (!h) { - h = w / canvas.width * canvas.height; - } - this.context.globalAlpha = this.alpha; - this.context.imageSmoothingEnabled = !this.pixelated; - if (this.initDrawOp(x, y)) { - this.context.drawImage(canvas, -w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); - return this.closeDrawOp(x, y); + msImage.prototype.getSpriteFrame = function(sprite) { + var dt, frame, s; + frame = null; + if (typeof sprite === "string") { + s = window.player.runtime.sprites[sprite]; + if (s != null) { + sprite = s; } else { - return this.context.drawImage(canvas, x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); + s = sprite.split("."); + if (s.length > 1) { + sprite = window.player.runtime.sprites[s[0]]; + frame = s[1] | 0; + } } + } else if (sprite instanceof msImage) { + return sprite.canvas || sprite.image; } - - drawImagePart(sprite, sx, sy, sw, sh, x, y, w, h) { - return this.drawSpritePart(sprite, sx, sy, sw, sh, x, y, w, h); + if ((sprite == null) || !sprite.ready) { + return null; } - - drawSpritePart(sprite, sx, sy, sw, sh, x, y, w, h) { - var canvas; - this.initContext(); - canvas = this.getSpriteFrame(sprite); - if (canvas == null) { - return; - } - if (w == null) { - w = canvas.width; + if (sprite.frames.length > 1) { + if (frame == null) { + dt = 1000 / sprite.fps; + frame = Math.floor((Date.now() - sprite.animation_start) / dt) % sprite.frames.length; } - if (!h) { - h = w / sw * sh; - } - this.context.globalAlpha = this.alpha; - this.context.imageSmoothingEnabled = !this.pixelated; - if (this.initDrawOp(x, y)) { - this.context.drawImage(canvas, sx, sy, sw, sh, -w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); - return this.closeDrawOp(x, y); + if (frame >= 0 && frame < sprite.frames.length) { + return sprite.frames[frame].canvas; } else { - return this.context.drawImage(canvas, sx, sy, sw, sh, x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); + return sprite.frames[0].canvas; } + } else if (sprite.frames[0] != null) { + return sprite.frames[0].canvas; + } else { + return null; } + }; - drawMap(map, x, y, w, h) { - this.initContext(); - if (typeof map === "string") { - map = window.player.runtime.maps[map]; - } - if ((map == null) || !map.ready) { - return; - } - this.context.globalAlpha = this.alpha; - this.context.imageSmoothingEnabled = !this.pixelated; - if (this.initDrawOp(x, y)) { - map.draw(this.context, -w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); - return this.closeDrawOp(x, y); - } else { - return map.draw(this.context, x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); - } + msImage.prototype.drawImage = function(sprite, x, y, w, h) { + return this.drawSprite(sprite, x, y, w, h); + }; + + msImage.prototype.drawSprite = function(sprite, x, y, w, h) { + var canvas; + this.initContext(); + canvas = this.getSpriteFrame(sprite); + if (canvas == null) { + return; + } + if (w == null) { + w = canvas.width; } + if (!h) { + h = w / canvas.width * canvas.height; + } + this.context.globalAlpha = this.alpha; + this.context.imageSmoothingEnabled = !this.pixelated; + if (this.initDrawOp(x, y)) { + this.context.drawImage(canvas, -w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); + return this.closeDrawOp(x, y); + } else { + return this.context.drawImage(canvas, x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); + } + }; + msImage.prototype.drawImagePart = function(sprite, sx, sy, sw, sh, x, y, w, h) { + return this.drawSpritePart(sprite, sx, sy, sw, sh, x, y, w, h); }; - msImage.classname = "Image"; + msImage.prototype.drawSpritePart = function(sprite, sx, sy, sw, sh, x, y, w, h) { + var canvas; + this.initContext(); + canvas = this.getSpriteFrame(sprite); + if (canvas == null) { + return; + } + if (w == null) { + w = canvas.width; + } + if (!h) { + h = w / sw * sh; + } + this.context.globalAlpha = this.alpha; + this.context.imageSmoothingEnabled = !this.pixelated; + if (this.initDrawOp(x, y)) { + this.context.drawImage(canvas, sx, sy, sw, sh, -w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); + return this.closeDrawOp(x, y); + } else { + return this.context.drawImage(canvas, sx, sy, sw, sh, x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); + } + }; + + msImage.prototype.drawMap = function(map, x, y, w, h) { + this.initContext(); + if (typeof map === "string") { + map = window.player.runtime.maps[map]; + } + if ((map == null) || !map.ready) { + return; + } + this.context.globalAlpha = this.alpha; + this.context.imageSmoothingEnabled = !this.pixelated; + if (this.initDrawOp(x, y)) { + map.draw(this.context, -w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); + return this.closeDrawOp(x, y); + } else { + return map.draw(this.context, x - w / 2 - this.anchor_x * w / 2, y - h / 2 + this.anchor_y * h / 2, w, h); + } + }; return msImage; -}).call(this); +})(); this.BLENDING_MODES = { normal: "source-over", diff --git a/static/js/runtime/pixi/screen.js b/static/js/runtime/pixi/screen.js index 6c3fba1b..d1c969df 100644 --- a/static/js/runtime/pixi/screen.js +++ b/static/js/runtime/pixi/screen.js @@ -1,5 +1,5 @@ -this.Screen = class Screen { - constructor(runtime) { +this.Screen = (function() { + function Screen(runtime) { this.runtime = runtime; this.renderer = new PIXI.Renderer({ width: 200, @@ -21,31 +21,33 @@ this.Screen = class Screen { }; } - getInterface() { + Screen.prototype.getInterface = function() { var screen; - if (this.interface != null) { - return this.interface; + if (this["interface"] != null) { + return this["interface"]; } screen = this; - return this.interface = { + return this["interface"] = { width: this.width, height: this.height, - render: (stage) => { - return screen.render(stage); - } + render: (function(_this) { + return function(stage) { + return screen.render(stage); + }; + })(this) }; - } + }; - updateInterface() { - this.interface.width = this.width; - return this.interface.height = this.height; - } + Screen.prototype.updateInterface = function() { + this["interface"].width = this.width; + return this["interface"].height = this.height; + }; - initDraw() {} + Screen.prototype.initDraw = function() {}; - clear() {} + Screen.prototype.clear = function() {}; - resize() { + Screen.prototype.resize = function() { var ch, cw, h, min, r, ratio, w; cw = window.innerWidth; ch = window.innerHeight; @@ -111,49 +113,67 @@ this.Screen = class Screen { this.renderer.resize(w, h); this.width = w; return this.height = h; - } + }; - render(stage) { + Screen.prototype.render = function(stage) { this.renderer.render(stage); if (this.take_picture_callback != null) { this.take_picture_callback(this.canvas.toDataURL()); return this.take_picture_callback = null; } - } + }; - startControl(element) { + Screen.prototype.startControl = function(element) { this.element = element; - document.addEventListener("touchstart", (event) => { - return this.touchStart(event); - }); - document.addEventListener("touchmove", (event) => { - return this.touchMove(event); - }); - document.addEventListener("touchend", (event) => { - return this.touchRelease(event); - }); - document.addEventListener("touchcancel", (event) => { - return this.touchRelease(event); - }); - document.addEventListener("mousedown", (event) => { - return this.mouseDown(event); - }); - document.addEventListener("mousemove", (event) => { - return this.mouseMove(event); - }); - document.addEventListener("mouseup", (event) => { - return this.mouseUp(event); - }); - document.addEventListener("mousewheel", (event) => { - return this.mouseWheel(event); - }); - document.addEventListener("DOMMouseScroll", (event) => { - return this.mouseWheel(event); - }); + document.addEventListener("touchstart", (function(_this) { + return function(event) { + return _this.touchStart(event); + }; + })(this)); + document.addEventListener("touchmove", (function(_this) { + return function(event) { + return _this.touchMove(event); + }; + })(this)); + document.addEventListener("touchend", (function(_this) { + return function(event) { + return _this.touchRelease(event); + }; + })(this)); + document.addEventListener("touchcancel", (function(_this) { + return function(event) { + return _this.touchRelease(event); + }; + })(this)); + document.addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.mouseDown(event); + }; + })(this)); + document.addEventListener("mousemove", (function(_this) { + return function(event) { + return _this.mouseMove(event); + }; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function(event) { + return _this.mouseUp(event); + }; + })(this)); + document.addEventListener("mousewheel", (function(_this) { + return function(event) { + return _this.mouseWheel(event); + }; + })(this)); + document.addEventListener("DOMMouseScroll", (function(_this) { + return function(event) { + return _this.mouseWheel(event); + }; + })(this)); return this.ratio = devicePixelRatio; - } + }; - touchStart(event) { + Screen.prototype.touchStart = function(event) { var b, i, j, min, ref, t, x, y; event.preventDefault(); event.stopPropagation(); @@ -173,9 +193,9 @@ this.Screen = class Screen { this.mouse.left = 1; } return false; - } + }; - touchMove(event) { + Screen.prototype.touchMove = function(event) { var b, i, j, min, ref, t, x, y; event.preventDefault(); event.stopPropagation(); @@ -193,9 +213,9 @@ this.Screen = class Screen { } } return false; - } + }; - touchRelease(event) { + Screen.prototype.touchRelease = function(event) { var i, j, ref, t, x, y; for (i = j = 0, ref = event.changedTouches.length - 1; j <= ref; i = j += 1) { t = event.changedTouches[i]; @@ -208,9 +228,9 @@ this.Screen = class Screen { this.mouse.middle = 0; } return false; - } + }; - mouseDown(event) { + Screen.prototype.mouseDown = function(event) { var b, min, x, y; this.mousepressed = true; b = this.canvas.getBoundingClientRect(); @@ -221,7 +241,6 @@ this.Screen = class Screen { x: x, y: y }; - //console.info @touches["mouse"] this.mouse.x = x; this.mouse.y = y; switch (event.button) { @@ -236,9 +255,9 @@ this.Screen = class Screen { } this.mouse.pressed = Math.min(1, this.mouse.left + this.mouse.right + this.mouse.middle); return false; - } + }; - mouseMove(event) { + Screen.prototype.mouseMove = function(event) { var b, min, x, y; event.preventDefault(); b = this.canvas.getBoundingClientRect(); @@ -252,9 +271,9 @@ this.Screen = class Screen { this.mouse.x = x; this.mouse.y = y; return false; - } + }; - mouseUp(event) { + Screen.prototype.mouseUp = function(event) { var b, min, x, y; delete this.touches["mouse"]; b = this.canvas.getBoundingClientRect(); @@ -275,19 +294,21 @@ this.Screen = class Screen { } this.mouse.pressed = Math.min(1, this.mouse.left + this.mouse.right + this.mouse.middle); return false; - } + }; - mouseWheel(e) { + Screen.prototype.mouseWheel = function(e) { e.preventDefault(); if (e.wheelDelta < 0 || e.detail > 0) { return this.wheel = -1; } else { return this.wheel = 1; } - } + }; - takePicture(take_picture_callback) { + Screen.prototype.takePicture = function(take_picture_callback) { this.take_picture_callback = take_picture_callback; - } + }; + + return Screen; -}; +})(); diff --git a/static/js/runtime/runtime.js b/static/js/runtime/runtime.js index 6fb71b34..f7f87a55 100644 --- a/static/js/runtime/runtime.js +++ b/static/js/runtime/runtime.js @@ -1,7 +1,7 @@ var arrayBufferToBase64, loadFile, loadLameJSLib, loadWaveFileLib, saveFile, writeProjectFile; -this.Runtime = class Runtime { - constructor(url1, sources, resources, listener) { +this.Runtime = (function() { + function Runtime(url1, sources, resources, listener) { this.url = url1; this.sources = sources; this.resources = resources; @@ -23,9 +23,11 @@ this.Runtime = class Runtime { this.orientation = window.orientation; this.aspect = window.aspect; this.report_errors = true; - this.log = (text) => { - return this.listener.log(text); - }; + this.log = (function(_this) { + return function(text) { + return _this.listener.log(text); + }; + })(this); this.update_memory = {}; this.time_machine = new TimeMachine(this); this.createDropFeature(); @@ -33,12 +35,15 @@ this.Runtime = class Runtime { this.connections = []; } - addConnection(connection) { + Runtime.prototype.addConnection = function(connection) { return this.connections.push(connection); - } + }; - updateSource(file, src, reinit = false) { + Runtime.prototype.updateSource = function(file, src, reinit) { var err, init; + if (reinit == null) { + reinit = false; + } if (this.vm == null) { return false; } @@ -84,9 +89,9 @@ this.Runtime = class Runtime { return false; } } - } + }; - start() { + Runtime.prototype.start = function() { var a, i, j, k, key, l, len1, len2, len3, len4, len5, m, n, name, o, ref, ref1, ref2, ref3, ref4, ref5, s, value; if (window.ms_async_load) { this.startReady(); @@ -94,10 +99,12 @@ this.Runtime = class Runtime { ref = this.resources.images; for (j = 0, len1 = ref.length; j < len1; j++) { i = ref[j]; - s = LoadSprite(this.url + "sprites/" + i.file + "?v=" + i.version, i.properties, () => { - this.updateMaps(); - return this.checkStartReady(); - }); + s = LoadSprite(this.url + "sprites/" + i.file + "?v=" + i.version, i.properties, (function(_this) { + return function() { + _this.updateMaps(); + return _this.checkStartReady(); + }; + })(this)); name = i.file.split(".")[0].replace(/-/g, "/"); s.name = name; this.sprites[name] = s; @@ -107,9 +114,11 @@ this.Runtime = class Runtime { for (k = 0, len2 = ref1.length; k < len2; k++) { m = ref1[k]; name = m.file.split(".")[0].replace(/-/g, "/"); - this.maps[name] = LoadMap(this.url + `maps/${m.file}?v=${m.version}`, () => { - return this.checkStartReady(); - }); + this.maps[name] = LoadMap(this.url + ("maps/" + m.file + "?v=" + m.version), (function(_this) { + return function() { + return _this.checkStartReady(); + }; + })(this)); this.maps[name].name = name; } } else if (this.resources.maps != null) { @@ -146,9 +155,9 @@ this.Runtime = class Runtime { a.name = name; this.assets[name] = a; } - } + }; - checkStartReady() { + Runtime.prototype.checkStartReady = function() { var count, key, progress, ready, ref, ref1, value; count = 0; ready = 0; @@ -192,18 +201,20 @@ this.Runtime = class Runtime { if (!this.started) { return this.startReady(); } - } + }; - startReady() { + Runtime.prototype.startReady = function() { var err, file, global, init, j, len1, lib, meta, namespace, ref, ref1, src; this.started = true; meta = { - print: (text) => { - if ((typeof text === "object" || typeof text === "function") && (this.vm != null)) { - text = this.vm.runner.toString(text); - } - return this.listener.log(text); - } + print: (function(_this) { + return function(text) { + if ((typeof text === "object" || typeof text === "function") && (_this.vm != null)) { + text = _this.vm.runner.toString(text); + } + return _this.listener.log(text); + }; + })(this) }; global = { screen: this.screen.getInterface(), @@ -254,19 +265,23 @@ this.Runtime = class Runtime { if (window.ms_use_server) { this.vm.context.global.ServerConnection = MPServerConnection; } - this.vm.context.global.system.pause = () => { - return this.listener.codePaused(); - }; - this.vm.context.global.system.exit = () => { - return this.exit(); - }; + this.vm.context.global.system.pause = (function(_this) { + return function() { + return _this.listener.codePaused(); + }; + })(this); + this.vm.context.global.system.exit = (function(_this) { + return function() { + return _this.exit(); + }; + })(this); if (!window.ms_async_load) { this.vm.context.global.system.loading = 100; } this.vm.context.global.system.file = System.file; this.vm.context.global.system.javascript = System.javascript; if (window.ms_in_editor) { - this.vm.context.global.system.project = new ProjectInterface(this).interface; + this.vm.context.global.system.project = new ProjectInterface(this)["interface"]; } System.runtime = this; ref1 = this.sources; @@ -297,25 +312,27 @@ this.Runtime = class Runtime { this.last_time = Date.now(); this.current_frame = 0; this.floating_frame = 0; - requestAnimationFrame(() => { - return this.timer(); - }); + requestAnimationFrame((function(_this) { + return function() { + return _this.timer(); + }; + })(this)); this.screen.startControl(); return this.listener.postMessage({ name: "started" }); - } + }; - updateMaps() { + Runtime.prototype.updateMaps = function() { var key, map, ref; ref = this.maps; for (key in ref) { map = ref[key]; map.needs_update = true; } - } + }; - runCommand(command, callback) { + Runtime.prototype.runCommand = function(command, callback) { var err, res, warnings; try { warnings = this.vm.context.warnings; @@ -339,9 +356,9 @@ this.Runtime = class Runtime { err = error; return this.listener.reportError(err); } - } + }; - projectFileUpdated(type, file, version, data, properties) { + Runtime.prototype.projectFileUpdated = function(type, file, version, data, properties) { switch (type) { case "sprites": return this.updateSprite(file, version, data, properties); @@ -350,24 +367,24 @@ this.Runtime = class Runtime { case "ms": return this.updateCode(file, version, data); } - } + }; - projectFileDeleted(type, file) { + Runtime.prototype.projectFileDeleted = function(type, file) { switch (type) { case "sprites": return delete this.sprites[file.substring(0, file.length - 4).replace(/-/g, "/")]; case "maps": return delete this.maps[file.substring(0, file.length - 5).replace(/-/g, "/")]; } - } + }; - projectOptionsUpdated(msg) { + Runtime.prototype.projectOptionsUpdated = function(msg) { this.orientation = msg.orientation; this.aspect = msg.aspect; return this.screen.resize(); - } + }; - updateSprite(name, version, data, properties) { + Runtime.prototype.updateSprite = function(name, version, data, properties) { var img, slug; slug = name; name = name.replace(/-/g, "/"); @@ -377,35 +394,43 @@ this.Runtime = class Runtime { img = new Image; img.crossOrigin = "Anonymous"; img.src = data; - return img.onload = () => { - UpdateSprite(this.sprites[name], img, properties); - return this.updateMaps(); - }; + return img.onload = (function(_this) { + return function() { + UpdateSprite(_this.sprites[name], img, properties); + return _this.updateMaps(); + }; + })(this); } else { - this.sprites[name] = LoadSprite(data, properties, () => { - return this.updateMaps(); - }); + this.sprites[name] = LoadSprite(data, properties, (function(_this) { + return function() { + return _this.updateMaps(); + }; + })(this)); return this.sprites[name].name = name; } } else { if (this.sprites[name] != null) { img = new Image; img.crossOrigin = "Anonymous"; - img.src = this.url + "sprites/" + slug + `.png?v=${version}`; - return img.onload = () => { - UpdateSprite(this.sprites[name], img, properties); - return this.updateMaps(); - }; + img.src = this.url + "sprites/" + slug + (".png?v=" + version); + return img.onload = (function(_this) { + return function() { + UpdateSprite(_this.sprites[name], img, properties); + return _this.updateMaps(); + }; + })(this); } else { - this.sprites[name] = LoadSprite(this.url + "sprites/" + slug + `.png?v=${version}`, properties, () => { - return this.updateMaps(); - }); + this.sprites[name] = LoadSprite(this.url + "sprites/" + slug + (".png?v=" + version), properties, (function(_this) { + return function() { + return _this.updateMaps(); + }; + })(this)); return this.sprites[name].name = name; } } - } + }; - updateMap(name, version, data) { + Runtime.prototype.updateMap = function(name, version, data) { var m, url; name = name.replace(/-/g, "/"); if (data != null) { @@ -420,7 +445,7 @@ this.Runtime = class Runtime { return this.maps[name].name = name; } } else { - url = this.url + `maps/${name}.json?v=${version}`; + url = this.url + ("maps/" + name + ".json?v=" + version); m = this.maps[name]; if (m != null) { return m.loadFile(url); @@ -429,9 +454,9 @@ this.Runtime = class Runtime { return this.maps[name].name = name; } } - } + }; - updateCode(name, version, data) { + Runtime.prototype.updateCode = function(name, version, data) { var req, url; if (data != null) { this.sources[name] = data; @@ -440,27 +465,29 @@ this.Runtime = class Runtime { } return this.updateSource(name, data, true); } else { - url = this.url + `ms/${name}.ms?v=${version}`; + url = this.url + ("ms/" + name + ".ms?v=" + version); req = new XMLHttpRequest(); - req.onreadystatechange = (event) => { - if (req.readyState === XMLHttpRequest.DONE) { - if (req.status === 200) { - this.sources[name] = req.responseText; - return this.updateSource(name, this.sources[name], true); + req.onreadystatechange = (function(_this) { + return function(event) { + if (req.readyState === XMLHttpRequest.DONE) { + if (req.status === 200) { + _this.sources[name] = req.responseText; + return _this.updateSource(name, _this.sources[name], true); + } } - } - }; + }; + })(this); req.open("GET", url); return req.send(); } - } + }; - stop() { + Runtime.prototype.stop = function() { this.stopped = true; return this.audio.cancelBeeps(); - } + }; - stepForward() { + Runtime.prototype.stepForward = function() { if (this.stopped) { this.updateCall(); this.drawCall(); @@ -469,25 +496,29 @@ this.Runtime = class Runtime { } return this.watchStep(); } - } + }; - resume() { + Runtime.prototype.resume = function() { if (this.stopped) { this.stopped = false; - return requestAnimationFrame(() => { - return this.timer(); - }); + return requestAnimationFrame((function(_this) { + return function() { + return _this.timer(); + }; + })(this)); } - } + }; - timer() { + Runtime.prototype.timer = function() { var ds, dt, fps, i, j, ref, time, update_rate; if (this.stopped) { return; } - requestAnimationFrame(() => { - return this.timer(); - }); + requestAnimationFrame((function(_this) { + return function() { + return _this.timer(); + }; + })(this)); time = Date.now(); if (Math.abs(time - this.last_time) > 160) { this.last_time = time - 16; @@ -503,7 +534,6 @@ this.Runtime = class Runtime { this.floating_frame += this.dt * update_rate / 1000; ds = Math.min(10, Math.round(this.floating_frame - this.current_frame)); if ((ds === 0 || ds === 2) && update_rate === 60 && Math.abs(fps - 60) < 2) { - //console.info "INCORRECT DS: "+ds+ " floating = "+@floating_frame+" current = "+@current_frame ds = 1; this.floating_frame = this.current_frame + 1; } @@ -523,29 +553,25 @@ this.Runtime = class Runtime { if (ds > 0) { return this.watchStep(); } - } + }; - //if ds != 1 - // console.info "frame missed" - //if @current_frame%60 == 0 - // console.info("fps: #{Math.round(1000/@dt)}") - updateCall() { + Runtime.prototype.updateCall = function() { var err; if (this.vm.runner.triggers_controls_update) { if (this.vm.runner.updateControls == null) { - this.vm.runner.updateControls = () => { - return this.updateControls(); - }; + this.vm.runner.updateControls = (function(_this) { + return function() { + return _this.updateControls(); + }; + })(this); } } else { this.updateControls(); } try { - //time = Date.now() this.vm.call("update"); this.time_machine.step(); this.reportWarnings(); - //console.info "update time: "+(Date.now()-time) if (this.vm.error_info != null) { err = this.vm.error_info; err.type = "update"; @@ -557,9 +583,9 @@ this.Runtime = class Runtime { return this.listener.reportError(err); } } - } + }; - drawCall() { + Runtime.prototype.drawCall = function() { var err; try { this.screen.initDraw(); @@ -577,9 +603,9 @@ this.Runtime = class Runtime { return this.listener.reportError(err); } } - } + }; - reportWarnings() { + Runtime.prototype.reportWarnings = function() { var key, ref, ref1, ref2, ref3, ref4, value; if (this.vm != null) { ref = this.vm.context.warnings.invoking_non_function; @@ -657,9 +683,9 @@ this.Runtime = class Runtime { } } } - } + }; - updateControls() { + Runtime.prototype.updateControls = function() { var c, err, j, k, key, len1, len2, ref, t, touches; ref = this.connections; for (j = 0, len1 = ref.length; j < len1; j++) { @@ -723,44 +749,44 @@ this.Runtime = class Runtime { } catch (error) { err = error; } - } + }; - getAssetURL(asset) { + Runtime.prototype.getAssetURL = function(asset) { return this.url + "assets/" + asset + ".glb"; - } + }; - getWatcher() { + Runtime.prototype.getWatcher = function() { return this.watcher || (this.watcher = new Watcher(this)); - } + }; - watch(variables) { + Runtime.prototype.watch = function(variables) { return this.getWatcher().watch(variables); - } + }; - watchStep() { + Runtime.prototype.watchStep = function() { return this.getWatcher().step(); - } + }; - stopWatching() { + Runtime.prototype.stopWatching = function() { return this.getWatcher().stop(); - } + }; - exit() { + Runtime.prototype.exit = function() { var err; this.stop(); if (this.screen.clear != null) { - setTimeout((() => { - return this.screen.clear(); - }), 1); + setTimeout(((function(_this) { + return function() { + return _this.screen.clear(); + }; + })(this)), 1); } try { - // microStudio embedded exit this.listener.exit(); } catch (error) { err = error; } try { - // TODO: Cordova exit, this might work if ((navigator.app != null) && (navigator.app.exitApp != null)) { navigator.app.exitApp(); } @@ -768,74 +794,81 @@ this.Runtime = class Runtime { err = error; } try { - // TODO: Electron exit, may already be covered by window.close() - - // Windowed mode exit return window.close(); } catch (error) { err = error; } - } + }; - createDropFeature() { - document.addEventListener("dragenter", (event) => { - return event.stopPropagation(); - }); - document.addEventListener("dragleave", (event) => { - return event.stopPropagation(); - }); - document.addEventListener("dragover", (event) => { - event.preventDefault(); - if (player.runtime.screen.mouseMove != null) { - return player.runtime.screen.mouseMove(event); - } - }); - return document.addEventListener("drop", (event) => { - var err, file, files, i, index, j, len1, list, processFile, ref, result; - event.preventDefault(); - event.stopPropagation(); - try { - list = []; - files = []; - ref = event.dataTransfer.items; - for (j = 0, len1 = ref.length; j < len1; j++) { - i = ref[j]; - if (i.kind === "file") { - file = i.getAsFile(); - files.push(file); - } + Runtime.prototype.createDropFeature = function() { + document.addEventListener("dragenter", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); + document.addEventListener("dragleave", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); + document.addEventListener("dragover", (function(_this) { + return function(event) { + event.preventDefault(); + if (player.runtime.screen.mouseMove != null) { + return player.runtime.screen.mouseMove(event); } - result = []; - index = 0; - processFile = function() { - var f; - if (index < files.length) { - f = files[index++]; - return loadFile(f, function(data) { - result.push({ - name: f.name, - size: f.size, - content: data, - file_type: f.type - }); - return processFile(); - }); - } else { - player.runtime.files_dropped = result; - if (typeof window.dropHandler === "function") { - return window.dropHandler(result); + }; + })(this)); + return document.addEventListener("drop", (function(_this) { + return function(event) { + var err, file, files, i, index, j, len1, list, processFile, ref, result; + event.preventDefault(); + event.stopPropagation(); + try { + list = []; + files = []; + ref = event.dataTransfer.items; + for (j = 0, len1 = ref.length; j < len1; j++) { + i = ref[j]; + if (i.kind === "file") { + file = i.getAsFile(); + files.push(file); } } - }; - return processFile(); - } catch (error) { - err = error; - return console.error(err); - } - }); - } + result = []; + index = 0; + processFile = function() { + var f; + if (index < files.length) { + f = files[index++]; + return loadFile(f, function(data) { + result.push({ + name: f.name, + size: f.size, + content: data, + file_type: f.type + }); + return processFile(); + }); + } else { + player.runtime.files_dropped = result; + if (typeof window.dropHandler === "function") { + return window.dropHandler(result); + } + } + }; + return processFile(); + } catch (error) { + err = error; + return console.error(err); + } + }; + })(this)); + }; -}; + return Runtime; + +})(); saveFile = function(data, name, type) { var a, blob, url; @@ -953,7 +986,7 @@ this.System = { javascript: function(s) { var err, f, res; try { - f = eval(`res = function(global) { ${s} }`); + f = eval("res = function(global) { " + s + " }"); res = f.call(player.runtime.vm.context.global, player.runtime.vm.context.global); } catch (error) { err = error; @@ -1000,20 +1033,22 @@ this.System = { name = "image"; } format = typeof format === "string" && format.toLowerCase() === "jpg" ? "jpg" : "png"; - if (!name.endsWith(`.${format}`)) { - name += `.${format}`; + if (!name.endsWith("." + format)) { + name += "." + format; } a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; - return c.toBlob(((blob) => { - var url; - url = window.URL.createObjectURL(blob); - a.href = url; - a.download = name; - a.click(); - return window.URL.revokeObjectURL(url); - }), (format === "png" ? "image/png" : "image/jpeg"), options); + return c.toBlob(((function(_this) { + return function(blob) { + var url; + url = window.URL.createObjectURL(blob); + a.href = url; + a.download = name; + a.click(); + return window.URL.revokeObjectURL(url); + }; + })(this)), (format === "png" ? "image/png" : "image/jpeg"), options); } else if (typeof obj === "object") { obj = System.runtime.vm.storableObject(obj); obj = JSON.stringify(obj, null, 2); @@ -1047,40 +1082,42 @@ this.System = { } input.type = "file"; if (typeof extensions === "string") { - input.accept = `.${extensions}`; + input.accept = "." + extensions; } else if (Array.isArray(extensions)) { - for (i = j = 0, ref = extensions.length - 1; (0 <= ref ? j <= ref : j >= ref); i = 0 <= ref ? ++j : --j) { - extensions[i] = `.${extensions[i]}`; + for (i = j = 0, ref = extensions.length - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) { + extensions[i] = "." + extensions[i]; } input.accept = extensions.join(","); } - input.addEventListener("change", (event) => { - var files, index, processFile, result; - files = event.target.files; - result = []; - index = 0; - processFile = function() { - var f; - if (index < files.length) { - f = files[index++]; - return loadFile(f, function(data) { - result.push({ - name: f.name, - size: f.size, - content: data, - file_type: f.type + input.addEventListener("change", (function(_this) { + return function(event) { + var files, index, processFile, result; + files = event.target.files; + result = []; + index = 0; + processFile = function() { + var f; + if (index < files.length) { + f = files[index++]; + return loadFile(f, function(data) { + result.push({ + name: f.name, + size: f.size, + content: data, + file_type: f.type + }); + return processFile(); }); - return processFile(); - }); - } else { - player.runtime.files_loaded = result; - if (typeof callback === "function") { - return callback(result); + } else { + player.runtime.files_loaded = result; + if (typeof callback === "function") { + return callback(result); + } } - } + }; + return processFile(); }; - return processFile(); - }); + })(this)); return input.click(); }, setDropHandler: function(handler) { diff --git a/static/js/runtime/runtime_server.js b/static/js/runtime/runtime_server.js index 6e83de4a..08f4ad8b 100644 --- a/static/js/runtime/runtime_server.js +++ b/static/js/runtime/runtime_server.js @@ -1,5 +1,5 @@ -this.Runtime = class Runtime { - constructor(url1, sources, resources, listener) { +this.Runtime = (function() { + function Runtime(url1, sources, resources, listener) { this.url = url1; this.sources = sources; this.resources = resources; @@ -12,19 +12,24 @@ this.Runtime = class Runtime { this.asset_manager = new AssetManager(this); this.previous_init = null; this.report_errors = true; - this.log = (text) => { - return this.listener.log(text); - }; + this.log = (function(_this) { + return function(text) { + return _this.listener.log(text); + }; + })(this); this.update_memory = {}; this.servers = []; } - addServer(server) { + Runtime.prototype.addServer = function(server) { return this.servers.push(server); - } + }; - updateSource(file, src, reinit = false) { + Runtime.prototype.updateSource = function(file, src, reinit) { var err, init; + if (reinit == null) { + reinit = false; + } if (this.vm == null) { return false; } @@ -68,9 +73,9 @@ this.Runtime = class Runtime { return false; } } - } + }; - start() { + Runtime.prototype.start = function() { var j, key, len, m, name, ref, ref1, value; if (window.ms_async_load) { this.startReady(); @@ -80,9 +85,11 @@ this.Runtime = class Runtime { for (j = 0, len = ref.length; j < len; j++) { m = ref[j]; name = m.file.split(".")[0].replace(/-/g, "/"); - this.maps[name] = LoadMap(this.url + `maps/${m.file}?v=${m.version}`, () => { - return this.checkStartReady(); - }); + this.maps[name] = LoadMap(this.url + ("maps/" + m.file + "?v=" + m.version), (function(_this) { + return function() { + return _this.checkStartReady(); + }; + })(this)); this.maps[name].name = name; } } else if (this.resources.maps != null) { @@ -96,9 +103,9 @@ this.Runtime = class Runtime { } } this.checkStartReady(); - } + }; - checkStartReady() { + Runtime.prototype.checkStartReady = function() { var count, key, ready, ref, value; count = 0; ready = 0; @@ -122,18 +129,20 @@ this.Runtime = class Runtime { if (!this.started) { return this.startReady(); } - } + }; - startReady() { + Runtime.prototype.startReady = function() { var err, file, global, init, j, len, lib, meta, namespace, ref, ref1, src; this.started = true; meta = { - print: (text) => { - if ((typeof text === "object" || typeof text === "function") && (this.vm != null)) { - text = this.vm.runner.toString(text); - } - return this.listener.log(text); - } + print: (function(_this) { + return function(text) { + if ((typeof text === "object" || typeof text === "function") && (_this.vm != null)) { + text = _this.vm.runner.toString(text); + } + return _this.listener.log(text); + }; + })(this) }; global = { sprites: this.sprites, @@ -158,12 +167,16 @@ this.Runtime = class Runtime { namespace = location.pathname + "[server]"; this.vm = new MicroVM(meta, global, namespace, location.hash === "#transpiler"); this.vm.context.global.Server = MPServer; - this.vm.context.global.system.pause = () => { - return this.listener.codePaused(); - }; - this.vm.context.global.system.exit = () => { - return this.exit(); - }; + this.vm.context.global.system.pause = (function(_this) { + return function() { + return _this.listener.codePaused(); + }; + })(this); + this.vm.context.global.system.exit = (function(_this) { + return function() { + return _this.exit(); + }; + })(this); if (!window.ms_async_load) { this.vm.context.global.system.loading = 100; } @@ -197,25 +210,27 @@ this.Runtime = class Runtime { this.last_time = Date.now(); this.current_frame = 0; this.floating_frame = 0; - this.clock_interval = setInterval((() => { - return this.clock(); - }), 16); + this.clock_interval = setInterval(((function(_this) { + return function() { + return _this.clock(); + }; + })(this)), 16); this.watcher = new Watcher(this); return this.listener.postMessage({ name: "started" }); - } + }; - updateMaps() { + Runtime.prototype.updateMaps = function() { var key, map, ref; ref = this.maps; for (key in ref) { map = ref[key]; map.needs_update = true; } - } + }; - runCommand(command, callback) { + Runtime.prototype.runCommand = function(command, callback) { var err, res, warnings; try { warnings = this.vm.context.warnings; @@ -239,27 +254,27 @@ this.Runtime = class Runtime { err = error; return this.listener.reportError(err); } - } + }; - projectFileUpdated(type, file, version, data, properties) { + Runtime.prototype.projectFileUpdated = function(type, file, version, data, properties) { switch (type) { case "maps": return this.updateMap(file, version, data); case "ms": return this.updateCode(file, version, data); } - } + }; - projectFileDeleted(type, file) { + Runtime.prototype.projectFileDeleted = function(type, file) { switch (type) { case "maps": return delete this.maps[file.substring(0, file.length - 5).replace(/-/g, "/")]; } - } + }; - projectOptionsUpdated(msg) {} + Runtime.prototype.projectOptionsUpdated = function(msg) {}; - updateMap(name, version, data) { + Runtime.prototype.updateMap = function(name, version, data) { var m, url; name = name.replace(/-/g, "/"); if (data != null) { @@ -274,7 +289,7 @@ this.Runtime = class Runtime { return this.maps[name].name = name; } } else { - url = this.url + `maps/${name}.json?v=${version}`; + url = this.url + ("maps/" + name + ".json?v=" + version); m = this.maps[name]; if (m != null) { return m.loadFile(url); @@ -283,9 +298,9 @@ this.Runtime = class Runtime { return this.maps[name].name = name; } } - } + }; - updateCode(name, version, data) { + Runtime.prototype.updateCode = function(name, version, data) { var req, url; if (data != null) { this.sources[name] = data; @@ -294,28 +309,30 @@ this.Runtime = class Runtime { } return this.updateSource(name, data, true); } else { - url = this.url + `ms/${name}.ms?v=${version}`; + url = this.url + ("ms/" + name + ".ms?v=" + version); req = new XMLHttpRequest(); - req.onreadystatechange = (event) => { - if (req.readyState === XMLHttpRequest.DONE) { - if (req.status === 200) { - this.sources[name] = req.responseText; - return this.updateSource(name, this.sources[name], true); + req.onreadystatechange = (function(_this) { + return function(event) { + if (req.readyState === XMLHttpRequest.DONE) { + if (req.status === 200) { + _this.sources[name] = req.responseText; + return _this.updateSource(name, _this.sources[name], true); + } } - } - }; + }; + })(this); req.open("GET", url); return req.send(); } - } + }; - stop() { + Runtime.prototype.stop = function() { this.stopped = true; clearInterval(this.clock_interval); return this.audio.cancelBeeps(); - } + }; - stepForward() { + Runtime.prototype.stepForward = function() { if (this.stopped) { this.updateCall(); if (this.vm.runner.tick != null) { @@ -323,22 +340,24 @@ this.Runtime = class Runtime { } return this.watcher.update(); } - } + }; - resume() { + Runtime.prototype.resume = function() { if (this.stopped) { this.stopped = false; - return this.clock_interval = setInterval((() => { - return this.clock(); - }), 16); + return this.clock_interval = setInterval(((function(_this) { + return function() { + return _this.clock(); + }; + })(this)), 16); } - } + }; - clock() { + Runtime.prototype.clock = function() { return this.timer(); - } + }; - timer() { + Runtime.prototype.timer = function() { var ds, dt, fps, i, j, ref, time; if (this.stopped) { return; @@ -363,9 +382,9 @@ this.Runtime = class Runtime { if (ds > 0) { return this.watcher.update(); } - } + }; - updateControls() { + Runtime.prototype.updateControls = function() { var j, len, ref, results, s; ref = this.servers; results = []; @@ -374,15 +393,17 @@ this.Runtime = class Runtime { results.push(s.update()); } return results; - } + }; - updateCall() { + Runtime.prototype.updateCall = function() { var err; if (this.vm.runner.triggers_controls_update) { if (this.vm.runner.updateControls == null) { - this.vm.runner.updateControls = () => { - return this.updateControls(); - }; + this.vm.runner.updateControls = (function(_this) { + return function() { + return _this.updateControls(); + }; + })(this); } } else { this.updateControls(); @@ -401,9 +422,9 @@ this.Runtime = class Runtime { return this.listener.reportError(err); } } - } + }; - reportWarnings() { + Runtime.prototype.reportWarnings = function() { var key, ref, ref1, ref2, ref3, value; if (this.vm != null) { ref = this.vm.context.warnings.invoking_non_function; @@ -467,19 +488,17 @@ this.Runtime = class Runtime { } } } - } + }; - exit() { + Runtime.prototype.exit = function() { var err; this.stop(); try { - // microStudio embedded exit this.listener.exit(); } catch (error) { err = error; } try { - // TODO: Cordova exit, this might work if ((navigator.app != null) && (navigator.app.exitApp != null)) { navigator.app.exitApp(); } @@ -487,22 +506,21 @@ this.Runtime = class Runtime { err = error; } try { - // TODO: Electron exit, may already be covered by window.close() - - // Windowed mode exit return window.close(); } catch (error) { err = error; } - } + }; -}; + return Runtime; + +})(); this.System = { javascript: function(s) { var err, f, res; try { - f = eval(`res = function(global) { ${s} }`); + f = eval("res = function(global) { " + s + " }"); res = f.call(player.runtime.vm.context.global, player.runtime.vm.context.global); } catch (error) { err = error; diff --git a/static/js/runtime/screen.js b/static/js/runtime/screen.js index 847a43d6..18d61c0a 100644 --- a/static/js/runtime/screen.js +++ b/static/js/runtime/screen.js @@ -1,5 +1,5 @@ -this.Screen = class Screen { - constructor(runtime) { +this.Screen = (function() { + function Screen(runtime) { this.runtime = runtime; this.canvas = document.createElement("canvas"); this.canvas.width = 1080; @@ -35,29 +35,33 @@ this.Screen = class Screen { this.loadFont(this.font); this.initContext(); this.cursor = "default"; - this.canvas.addEventListener("mousemove", () => { - this.last_mouse_move = Date.now(); - if (this.cursor !== "default" && this.cursor_visibility === "auto") { - this.cursor = "default"; - return this.canvas.style.cursor = "default"; - } - }); - setInterval((() => { - return this.checkMouseCursor(); - }), 1000); + this.canvas.addEventListener("mousemove", (function(_this) { + return function() { + _this.last_mouse_move = Date.now(); + if (_this.cursor !== "default" && _this.cursor_visibility === "auto") { + _this.cursor = "default"; + return _this.canvas.style.cursor = "default"; + } + }; + })(this)); + setInterval(((function(_this) { + return function() { + return _this.checkMouseCursor(); + }; + })(this)), 1000); this.cursor_visibility = "auto"; } - checkMouseCursor() { + Screen.prototype.checkMouseCursor = function() { if (Date.now() > this.last_mouse_move + 4000 && this.cursor_visibility === "auto") { if (this.cursor !== "none") { this.cursor = "none"; return this.canvas.style.cursor = "none"; } } - } + }; - setCursorVisible(visible) { + Screen.prototype.setCursorVisible = function(visible) { this.cursor_visibility = visible; if (visible) { this.cursor = "default"; @@ -66,9 +70,9 @@ this.Screen = class Screen { this.cursor = "none"; return this.canvas.style.cursor = "none"; } - } + }; - initContext() { + Screen.prototype.initContext = function() { var b, c, j, len1, ratio, ref; c = this.canvas.getContext("2d", { alpha: false @@ -84,12 +88,6 @@ this.Screen = class Screen { this.context.scale(ratio, ratio); this.width = this.canvas.width / ratio; this.height = this.canvas.height / ratio; - // @translation_x = 0 - // @translation_y = 0 - // @rotation = 0 - // @scale_x = 1 - // @scale_y = 1 - // @screen_transform = false this.context.lineCap = "round"; this.blending = { normal: "source-over", @@ -100,15 +98,15 @@ this.Screen = class Screen { b = ref[j]; this.blending[b] = b; } - } + }; - getInterface() { + Screen.prototype.getInterface = function() { var screen; - if (this.interface != null) { - return this.interface; + if (this["interface"] != null) { + return this["interface"]; } screen = this; - return this.interface = { + return this["interface"] = { width: this.width, height: this.height, clear: function(color) { @@ -235,14 +233,14 @@ this.Screen = class Screen { return screen.isFontReady(font); } }; - } + }; - updateInterface() { - this.interface.width = this.width; - return this.interface.height = this.height; - } + Screen.prototype.updateInterface = function() { + this["interface"].width = this.width; + return this["interface"].height = this.height; + }; - clear(color) { + Screen.prototype.clear = function(color) { var blending_save, c, s; c = this.context.fillStyle; s = this.context.strokeStyle; @@ -258,18 +256,18 @@ this.Screen = class Screen { this.context.fillStyle = c; this.context.strokeStyle = s; return this.context.globalCompositeOperation = blending_save; - } + }; - initDraw() { + Screen.prototype.initDraw = function() { this.alpha = 1; this.line_width = 1; if (this.supersampling !== this.previous_supersampling) { this.resize(); return this.previous_supersampling = this.supersampling; } - } + }; - setColor(color) { + Screen.prototype.setColor = function(color) { var b, c, g, r; if (color == null) { return; @@ -289,79 +287,85 @@ this.Screen = class Screen { this.context.fillStyle = color; return this.context.strokeStyle = color; } - } + }; - setAlpha(alpha1) { + Screen.prototype.setAlpha = function(alpha1) { this.alpha = alpha1; - } + }; - setPixelated(pixelated1) { + Screen.prototype.setPixelated = function(pixelated1) { this.pixelated = pixelated1; - } + }; - setBlending(blending) { + Screen.prototype.setBlending = function(blending) { blending = this.blending[blending || "normal"] || "source-over"; return this.context.globalCompositeOperation = blending; - } + }; - setLineWidth(line_width) { + Screen.prototype.setLineWidth = function(line_width) { this.line_width = line_width; - } + }; - setLineDash(dash) { + Screen.prototype.setLineDash = function(dash) { if (!Array.isArray(dash)) { return this.context.setLineDash([]); } else { return this.context.setLineDash(dash); } - } + }; - setLinearGradient(x1, y1, x2, y2, c1, c2) { + Screen.prototype.setLinearGradient = function(x1, y1, x2, y2, c1, c2) { var grd; grd = this.context.createLinearGradient(x1, -y1, x2, -y2); grd.addColorStop(0, c1); grd.addColorStop(1, c2); this.context.fillStyle = grd; return this.context.strokeStyle = grd; - } + }; - setRadialGradient(x, y, radius, c1, c2) { + Screen.prototype.setRadialGradient = function(x, y, radius, c1, c2) { var grd; grd = this.context.createRadialGradient(x, -y, 0, x, -y, radius); grd.addColorStop(0, c1); grd.addColorStop(1, c2); this.context.fillStyle = grd; return this.context.strokeStyle = grd; - } + }; - setFont(font) { + Screen.prototype.setFont = function(font) { this.font = font || "Verdana"; return this.loadFont(this.font); - } + }; - loadFont(font = "BitCell") { + Screen.prototype.loadFont = function(font) { var err; + if (font == null) { + font = "BitCell"; + } if (!this.font_load_requested[font]) { this.font_load_requested[font] = true; try { if ((document.fonts != null) && (document.fonts.load != null)) { - document.fonts.load(`16pt ${font}`); + document.fonts.load("16pt " + font); } } catch (error) { err = error; } } return 1; - } + }; - isFontReady(font = this.font) { + Screen.prototype.isFontReady = function(font) { var err, res; + if (font == null) { + font = this.font; + } if (this.font_loaded[font]) { return 1; } try { if ((document.fonts != null) && (document.fonts.check != null)) { - res = document.fonts.check(`16pt ${font}`); + res = document.fonts.check("16pt " + font); if (res) { this.font_loaded[font] = res; } @@ -375,9 +379,9 @@ this.Screen = class Screen { err = error; } return 1; - } + }; - setTranslation(translation_x, translation_y) { + Screen.prototype.setTranslation = function(translation_x, translation_y) { this.translation_x = translation_x; this.translation_y = translation_y; if (!isFinite(this.translation_x)) { @@ -387,9 +391,9 @@ this.Screen = class Screen { this.translation_y = 0; } return this.updateScreenTransform(); - } + }; - setScale(scale_x, scale_y) { + Screen.prototype.setScale = function(scale_x, scale_y) { this.scale_x = scale_x; this.scale_y = scale_y; if (!isFinite(this.scale_x) || this.scale_x === 0) { @@ -399,21 +403,21 @@ this.Screen = class Screen { this.scale_y = 1; } return this.updateScreenTransform(); - } + }; - setRotation(rotation1) { + Screen.prototype.setRotation = function(rotation1) { this.rotation = rotation1; if (!isFinite(this.rotation)) { this.rotation = 0; } return this.updateScreenTransform(); - } + }; - updateScreenTransform() { + Screen.prototype.updateScreenTransform = function() { return this.screen_transform = this.translation_x !== 0 || this.translation_y !== 0 || this.scale_x !== 1 || this.scale_y !== 1 || this.rotation !== 0; - } + }; - setDrawAnchor(anchor_x, anchor_y) { + Screen.prototype.setDrawAnchor = function(anchor_x, anchor_y) { this.anchor_x = anchor_x; this.anchor_y = anchor_y; if (typeof this.anchor_x !== "number") { @@ -422,19 +426,22 @@ this.Screen = class Screen { if (typeof this.anchor_y !== "number") { return this.anchor_y = 0; } - } + }; - setDrawRotation(object_rotation) { + Screen.prototype.setDrawRotation = function(object_rotation) { this.object_rotation = object_rotation; - } + }; - setDrawScale(object_scale_x, object_scale_y = this.object_scale_x) { + Screen.prototype.setDrawScale = function(object_scale_x, object_scale_y) { this.object_scale_x = object_scale_x; - this.object_scale_y = object_scale_y; - } + this.object_scale_y = object_scale_y != null ? object_scale_y : this.object_scale_x; + }; - initDrawOp(x, y, object_transform = true) { + Screen.prototype.initDrawOp = function(x, y, object_transform) { var res; + if (object_transform == null) { + object_transform = true; + } res = false; if (this.screen_transform) { this.context.save(); @@ -458,19 +465,13 @@ this.Screen = class Screen { } } return res; - } - - closeDrawOp(x, y) { - //if @object_scale_x != 1 or @object_scale_y != 1 - // @context.scale 1/@object_scale_x,1/@object_scale_y + }; - //if @object_rotation != 0 - // @context.rotate -@object_rotation/180*Math.PI - //@context.translate -x,-y + Screen.prototype.closeDrawOp = function(x, y) { return this.context.restore(); - } + }; - fillRect(x, y, w, h, color) { + Screen.prototype.fillRect = function(x, y, w, h, color) { this.setColor(color); this.context.globalAlpha = this.alpha; if (this.initDrawOp(x, -y)) { @@ -479,9 +480,12 @@ this.Screen = class Screen { } else { return this.context.fillRect(x - w / 2 - this.anchor_x * w / 2, -y - h / 2 + this.anchor_y * h / 2, w, h); } - } + }; - fillRoundRect(x, y, w, h, round = 10, color) { + Screen.prototype.fillRoundRect = function(x, y, w, h, round, color) { + if (round == null) { + round = 10; + } this.setColor(color); this.context.globalAlpha = this.alpha; if (this.initDrawOp(x, -y)) { @@ -490,9 +494,9 @@ this.Screen = class Screen { } else { return this.context.fillRoundRect(x - w / 2 - this.anchor_x * w / 2, -y - h / 2 + this.anchor_y * h / 2, w, h, round); } - } + }; - fillRound(x, y, w, h, color) { + Screen.prototype.fillRound = function(x, y, w, h, color) { this.setColor(color); this.context.globalAlpha = this.alpha; w = Math.abs(w); @@ -507,9 +511,9 @@ this.Screen = class Screen { this.context.ellipse(x - this.anchor_x * w / 2, -y + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); return this.context.fill(); } - } + }; - drawRect(x, y, w, h, color) { + Screen.prototype.drawRect = function(x, y, w, h, color) { this.setColor(color); this.context.globalAlpha = this.alpha; this.context.lineWidth = this.line_width; @@ -519,9 +523,12 @@ this.Screen = class Screen { } else { return this.context.strokeRect(x - w / 2 - this.anchor_x * w / 2, -y - h / 2 + this.anchor_y * h / 2, w, h); } - } + }; - drawRoundRect(x, y, w, h, round = 10, color) { + Screen.prototype.drawRoundRect = function(x, y, w, h, round, color) { + if (round == null) { + round = 10; + } this.setColor(color); this.context.globalAlpha = this.alpha; this.context.lineWidth = this.line_width; @@ -531,9 +538,9 @@ this.Screen = class Screen { } else { return this.context.strokeRoundRect(x - w / 2 - this.anchor_x * w / 2, -y - h / 2 + this.anchor_y * h / 2, w, h, round); } - } + }; - drawRound(x, y, w, h, color) { + Screen.prototype.drawRound = function(x, y, w, h, color) { this.setColor(color); this.context.globalAlpha = this.alpha; this.context.lineWidth = this.line_width; @@ -549,9 +556,9 @@ this.Screen = class Screen { this.context.ellipse(x - this.anchor_x * w / 2, -y + this.anchor_y * h / 2, w / 2, h / 2, 0, 0, Math.PI * 2, false); return this.context.stroke(); } - } + }; - drawLine(x1, y1, x2, y2, color) { + Screen.prototype.drawLine = function(x1, y1, x2, y2, color) { var transform; this.setColor(color); this.context.globalAlpha = this.alpha; @@ -564,9 +571,9 @@ this.Screen = class Screen { if (transform) { return this.closeDrawOp(); } - } + }; - drawPolyline(args) { + Screen.prototype.drawPolyline = function(args) { var i, j, len, ref, transform; if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { this.setColor(args[args.length - 1]); @@ -586,16 +593,16 @@ this.Screen = class Screen { transform = this.initDrawOp(0, 0, false); this.context.beginPath(); this.context.moveTo(args[0], -args[1]); - for (i = j = 1, ref = len - 1; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + for (i = j = 1, ref = len - 1; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { this.context.lineTo(args[i * 2], -args[i * 2 + 1]); } this.context.stroke(); if (transform) { return this.closeDrawOp(); } - } + }; - drawPolygon(args) { + Screen.prototype.drawPolygon = function(args) { var i, j, len, ref, transform; if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { this.setColor(args[args.length - 1]); @@ -615,7 +622,7 @@ this.Screen = class Screen { transform = this.initDrawOp(0, 0, false); this.context.beginPath(); this.context.moveTo(args[0], -args[1]); - for (i = j = 1, ref = len - 1; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + for (i = j = 1, ref = len - 1; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { this.context.lineTo(args[i * 2], -args[i * 2 + 1]); } this.context.closePath(); @@ -623,9 +630,9 @@ this.Screen = class Screen { if (transform) { return this.closeDrawOp(); } - } + }; - fillPolygon(args) { + Screen.prototype.fillPolygon = function(args) { var i, j, len, ref, transform; if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { this.setColor(args[args.length - 1]); @@ -645,16 +652,16 @@ this.Screen = class Screen { transform = this.initDrawOp(0, 0, false); this.context.beginPath(); this.context.moveTo(args[0], -args[1]); - for (i = j = 1, ref = len - 1; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + for (i = j = 1, ref = len - 1; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { this.context.lineTo(args[i * 2], -args[i * 2 + 1]); } this.context.fill(); if (transform) { return this.closeDrawOp(); } - } + }; - drawQuadCurve(args) { + Screen.prototype.drawQuadCurve = function(args) { var index, len, transform; if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { this.setColor(args[args.length - 1]); @@ -683,9 +690,9 @@ this.Screen = class Screen { if (transform) { return this.closeDrawOp(); } - } + }; - drawBezierCurve(args) { + Screen.prototype.drawBezierCurve = function(args) { var index, len, transform; if (args.length > 0 && args.length % 2 === 1 && typeof args[args.length - 1] === "string") { this.setColor(args[args.length - 1]); @@ -714,9 +721,9 @@ this.Screen = class Screen { if (transform) { return this.closeDrawOp(); } - } + }; - drawArc(x, y, radius, angle1, angle2, ccw, color) { + Screen.prototype.drawArc = function(x, y, radius, angle1, angle2, ccw, color) { this.setColor(color); this.context.globalAlpha = this.alpha; this.context.lineWidth = this.line_width; @@ -730,9 +737,9 @@ this.Screen = class Screen { this.context.arc(x, -y, radius, -angle1 / 180 * Math.PI, -angle2 / 180 * Math.PI, ccw); return this.context.stroke(); } - } + }; - fillArc(x, y, radius, angle1, angle2, ccw, color) { + Screen.prototype.fillArc = function(x, y, radius, angle1, angle2, ccw, color) { this.setColor(color); this.context.globalAlpha = this.alpha; this.context.lineWidth = this.line_width; @@ -746,18 +753,18 @@ this.Screen = class Screen { this.context.arc(x, -y, radius, -angle1 / 180 * Math.PI, -angle2 / 180 * Math.PI, ccw); return this.context.fill(); } - } + }; - textWidth(text, size) { - this.context.font = `${size}pt ${this.font}`; + Screen.prototype.textWidth = function(text, size) { + this.context.font = size + "pt " + this.font; return this.context.measureText(text).width; - } + }; - drawText(text, x, y, size, color) { + Screen.prototype.drawText = function(text, x, y, size, color) { var h, w; this.setColor(color); this.context.globalAlpha = this.alpha; - this.context.font = `${size}pt ${this.font}`; + this.context.font = size + "pt " + this.font; this.context.textAlign = "center"; this.context.textBaseline = "middle"; w = this.context.measureText(text).width; @@ -768,13 +775,13 @@ this.Screen = class Screen { } else { return this.context.fillText(text, x - this.anchor_x * w / 2, -y + this.anchor_y * h / 2); } - } + }; - drawTextOutline(text, x, y, size, color) { + Screen.prototype.drawTextOutline = function(text, x, y, size, color) { var h, w; this.setColor(color); this.context.globalAlpha = this.alpha; - this.context.font = `${size}pt ${this.font}`; + this.context.font = size + "pt " + this.font; this.context.lineWidth = this.line_width; this.context.textAlign = "center"; this.context.textBaseline = "middle"; @@ -786,9 +793,9 @@ this.Screen = class Screen { } else { return this.context.strokeText(text, x - this.anchor_x * w / 2, -y + this.anchor_y * h / 2); } - } + }; - getSpriteFrame(sprite) { + Screen.prototype.getSpriteFrame = function(sprite) { var dt, frame, s; frame = null; if (typeof sprite === "string") { @@ -823,9 +830,9 @@ this.Screen = class Screen { } else { return null; } - } + }; - drawSprite(sprite, x, y, w, h) { + Screen.prototype.drawSprite = function(sprite, x, y, w, h) { var canvas; canvas = this.getSpriteFrame(sprite); if (canvas == null) { @@ -845,9 +852,9 @@ this.Screen = class Screen { } else { return this.context.drawImage(canvas, x - w / 2 - this.anchor_x * w / 2, -y - h / 2 + this.anchor_y * h / 2, w, h); } - } + }; - drawSpritePart(sprite, sx, sy, sw, sh, x, y, w, h) { + Screen.prototype.drawSpritePart = function(sprite, sx, sy, sw, sh, x, y, w, h) { var canvas; canvas = this.getSpriteFrame(sprite); if (canvas == null) { @@ -867,9 +874,9 @@ this.Screen = class Screen { } else { return this.context.drawImage(canvas, sx, sy, sw, sh, x - w / 2 - this.anchor_x * w / 2, -y - h / 2 + this.anchor_y * h / 2, w, h); } - } + }; - drawMap(map, x, y, w, h) { + Screen.prototype.drawMap = function(map, x, y, w, h) { if (typeof map === "string") { map = this.runtime.maps[map]; } @@ -880,15 +887,13 @@ this.Screen = class Screen { this.context.imageSmoothingEnabled = !this.pixelated; if (this.initDrawOp(x, -y)) { map.draw(this.context, -w / 2 - this.anchor_x * w / 2, -h / 2 + this.anchor_y * h / 2, w, h); - //@context.drawImage map.getCanvas(),-w/2-@anchor_x*w/2,-h/2+@anchor_y*h/2,w,h return this.closeDrawOp(x, -y); } else { return map.draw(this.context, x - w / 2 - this.anchor_x * w / 2, -y - h / 2 + this.anchor_y * h / 2, w, h); } - } + }; - //@context.drawImage map.getCanvas(),x-w/2-@anchor_x*w/2,-y-h/2+@anchor_y*h/2,w,h - resize() { + Screen.prototype.resize = function() { var backingStoreRatio, ch, cw, devicePixelRatio, h, min, r, ratio, w; cw = window.innerWidth; ch = window.innerHeight; @@ -903,8 +908,6 @@ this.Screen = class Screen { ">1x1": 1 / 1 }[this.runtime.aspect]; min = this.runtime.aspect.startsWith(">"); - //if not ratio? and @runtime.orientation in ["portrait","landscape"] - // ratio = 16/9 if (ratio != null) { if (min) { switch (this.runtime.orientation) { @@ -959,44 +962,62 @@ this.Screen = class Screen { this.canvas.width = this.width; this.canvas.height = this.height; return this.initContext(); - } + }; - startControl(element) { + Screen.prototype.startControl = function(element) { var backingStoreRatio, devicePixelRatio; this.element = element; - document.addEventListener("touchstart", (event) => { - return this.touchStart(event); - }); - document.addEventListener("touchmove", (event) => { - return this.touchMove(event); - }); - document.addEventListener("touchend", (event) => { - return this.touchRelease(event); - }); - document.addEventListener("touchcancel", (event) => { - return this.touchRelease(event); - }); - document.addEventListener("mousedown", (event) => { - return this.mouseDown(event); - }); - document.addEventListener("mousemove", (event) => { - return this.mouseMove(event); - }); - document.addEventListener("mouseup", (event) => { - return this.mouseUp(event); - }); - document.addEventListener("mousewheel", (event) => { - return this.mouseWheel(event); - }); - document.addEventListener("DOMMouseScroll", (event) => { - return this.mouseWheel(event); - }); + document.addEventListener("touchstart", (function(_this) { + return function(event) { + return _this.touchStart(event); + }; + })(this)); + document.addEventListener("touchmove", (function(_this) { + return function(event) { + return _this.touchMove(event); + }; + })(this)); + document.addEventListener("touchend", (function(_this) { + return function(event) { + return _this.touchRelease(event); + }; + })(this)); + document.addEventListener("touchcancel", (function(_this) { + return function(event) { + return _this.touchRelease(event); + }; + })(this)); + document.addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.mouseDown(event); + }; + })(this)); + document.addEventListener("mousemove", (function(_this) { + return function(event) { + return _this.mouseMove(event); + }; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function(event) { + return _this.mouseUp(event); + }; + })(this)); + document.addEventListener("mousewheel", (function(_this) { + return function(event) { + return _this.mouseWheel(event); + }; + })(this)); + document.addEventListener("DOMMouseScroll", (function(_this) { + return function(event) { + return _this.mouseWheel(event); + }; + })(this)); devicePixelRatio = window.devicePixelRatio || 1; backingStoreRatio = this.context.webkitBackingStorePixelRatio || this.context.mozBackingStorePixelRatio || this.context.msBackingStorePixelRatio || this.context.oBackingStorePixelRatio || this.context.backingStorePixelRatio || 1; return this.ratio = devicePixelRatio / backingStoreRatio; - } + }; - touchStart(event) { + Screen.prototype.touchStart = function(event) { var b, i, j, min, ref, t, x, y; event.preventDefault(); event.stopPropagation(); @@ -1016,9 +1037,9 @@ this.Screen = class Screen { this.mouse.left = 1; } return false; - } + }; - touchMove(event) { + Screen.prototype.touchMove = function(event) { var b, i, j, min, ref, t, x, y; event.preventDefault(); event.stopPropagation(); @@ -1036,9 +1057,9 @@ this.Screen = class Screen { } } return false; - } + }; - touchRelease(event) { + Screen.prototype.touchRelease = function(event) { var i, j, ref, t, x, y; for (i = j = 0, ref = event.changedTouches.length - 1; j <= ref; i = j += 1) { t = event.changedTouches[i]; @@ -1051,9 +1072,9 @@ this.Screen = class Screen { this.mouse.middle = 0; } return false; - } + }; - mouseDown(event) { + Screen.prototype.mouseDown = function(event) { var b, min, x, y; this.mousepressed = true; b = this.canvas.getBoundingClientRect(); @@ -1064,7 +1085,6 @@ this.Screen = class Screen { x: x, y: y }; - //console.info @touches["mouse"] this.mouse.x = x; this.mouse.y = y; switch (event.button) { @@ -1079,9 +1099,9 @@ this.Screen = class Screen { } this.mouse.pressed = Math.min(1, this.mouse.left + this.mouse.right + this.mouse.middle); return false; - } + }; - mouseMove(event) { + Screen.prototype.mouseMove = function(event) { var b, min, x, y; event.preventDefault(); b = this.canvas.getBoundingClientRect(); @@ -1095,9 +1115,9 @@ this.Screen = class Screen { this.mouse.x = x; this.mouse.y = y; return false; - } + }; - mouseUp(event) { + Screen.prototype.mouseUp = function(event) { var b, min, x, y; delete this.touches["mouse"]; b = this.canvas.getBoundingClientRect(); @@ -1118,18 +1138,20 @@ this.Screen = class Screen { } this.mouse.pressed = Math.min(1, this.mouse.left + this.mouse.right + this.mouse.middle); return false; - } + }; - mouseWheel(e) { + Screen.prototype.mouseWheel = function(e) { if (e.wheelDelta < 0 || e.detail > 0) { return this.wheel = -1; } else { return this.wheel = 1; } - } + }; - takePicture(callback) { + Screen.prototype.takePicture = function(callback) { return callback(this.canvas.toDataURL()); - } + }; + + return Screen; -}; +})(); diff --git a/static/js/runtime/sprite.js b/static/js/runtime/sprite.js index ba42ab3c..f5e69167 100644 --- a/static/js/runtime/sprite.js +++ b/static/js/runtime/sprite.js @@ -1,5 +1,5 @@ -this.Sprite = class Sprite { - constructor(width, height) { +this.Sprite = (function() { + function Sprite(width, height) { this.width = width; this.height = height; this.name = ""; @@ -12,7 +12,7 @@ this.Sprite = class Sprite { } } - setFPS(fps) { + Sprite.prototype.setFPS = function(fps) { var dt, frame; dt = 1000 / this.fps; frame = ((Date.now() - this.animation_start) / dt) % this.frames.length; @@ -20,19 +20,21 @@ this.Sprite = class Sprite { dt = 1000 / fps; this.animation_start = Date.now() - frame * dt; return fps; - } + }; - setFrame(f) { + Sprite.prototype.setFrame = function(f) { return this.animation_start = Date.now() - 1000 / this.fps * f; - } + }; - getFrame() { + Sprite.prototype.getFrame = function() { var dt; dt = 1000 / this.fps; return Math.floor((Date.now() - this.animation_start) / dt) % this.frames.length; - } + }; -}; + return Sprite; + +})(); this.LoadSprite = function(url, properties, loaded) { var img, sprite; @@ -43,35 +45,39 @@ this.LoadSprite = function(url, properties, loaded) { img.crossOrigin = "Anonymous"; } img.src = url; - img.onload = () => { - var frame, i, j, numframes, ref; - sprite.ready = true; - if (img.width > 0 && img.height > 0) { - numframes = 1; - if ((properties != null) && (properties.frames != null)) { - numframes = properties.frames; - } - if (properties.fps != null) { - sprite.fps = properties.fps; + img.onload = (function(_this) { + return function() { + var frame, i, j, numframes, ref; + sprite.ready = true; + if (img.width > 0 && img.height > 0) { + numframes = 1; + if ((properties != null) && (properties.frames != null)) { + numframes = properties.frames; + } + if (properties.fps != null) { + sprite.fps = properties.fps; + } + sprite.width = img.width; + sprite.height = Math.round(img.height / numframes); + sprite.frames = []; + for (i = j = 0, ref = numframes - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) { + frame = new msImage(sprite.width, sprite.height); + frame.initContext(); + frame.context.drawImage(img, 0, -i * sprite.height); + sprite.frames.push(frame); + } + sprite.ready = true; } - sprite.width = img.width; - sprite.height = Math.round(img.height / numframes); - sprite.frames = []; - for (i = j = 0, ref = numframes - 1; (0 <= ref ? j <= ref : j >= ref); i = 0 <= ref ? ++j : --j) { - frame = new msImage(sprite.width, sprite.height); - frame.initContext(); - frame.context.drawImage(img, 0, -i * sprite.height); - sprite.frames.push(frame); + if (loaded != null) { + return loaded(); } - sprite.ready = true; - } - if (loaded != null) { - return loaded(); - } - }; - img.onerror = () => { - return sprite.ready = 1; - }; + }; + })(this); + img.onerror = (function(_this) { + return function() { + return sprite.ready = 1; + }; + })(this); return sprite; }; @@ -88,7 +94,7 @@ this.UpdateSprite = function(sprite, img, properties) { sprite.width = img.width; sprite.height = Math.round(img.height / numframes); sprite.frames = []; - for (i = j = 0, ref = numframes - 1; (0 <= ref ? j <= ref : j >= ref); i = 0 <= ref ? ++j : --j) { + for (i = j = 0, ref = numframes - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) { frame = new msImage(sprite.width, sprite.height); frame.initContext(); frame.context.drawImage(img, 0, -i * sprite.height); diff --git a/static/js/runtime/timemachine.js b/static/js/runtime/timemachine.js index 8742bfc4..1314f156 100644 --- a/static/js/runtime/timemachine.js +++ b/static/js/runtime/timemachine.js @@ -1,5 +1,5 @@ -this.TimeMachine = class TimeMachine { - constructor(runtime) { +this.TimeMachine = (function() { + function TimeMachine(runtime) { this.runtime = runtime; this.history = []; this.record_index = 0; @@ -10,7 +10,7 @@ this.TimeMachine = class TimeMachine { this.loop_length = 60 * 4; } - step() { + TimeMachine.prototype.step = function() { var end, err, histo, i, index, j, ref, ref1, start; if (this.recording) { try { @@ -41,9 +41,9 @@ this.TimeMachine = class TimeMachine { return console.error(err); } } - } + }; - messageReceived(data) { + TimeMachine.prototype.messageReceived = function(data) { var pos; switch (data.command) { case "start_recording": @@ -87,23 +87,25 @@ this.TimeMachine = class TimeMachine { case "stop_looping": return this.stopLooping(); } - } + }; - stopLooping() { + TimeMachine.prototype.stopLooping = function() { if (this.looping) { this.looping = false; this.replay_position = this.loop_start; return this.sendStatus(); } - } + }; - loop() { + TimeMachine.prototype.loop = function() { if (!this.looping) { return; } - requestAnimationFrame(() => { - return this.loop(); - }); + requestAnimationFrame((function(_this) { + return function() { + return _this.loop(); + }; + })(this)); if (this.loop_index === 0) { this.replay_position = this.loop_start; this.replay(true); @@ -121,9 +123,9 @@ this.TimeMachine = class TimeMachine { this.resetControls(); } return this.sendStatus(); - } + }; - stepBackward() { + TimeMachine.prototype.stepBackward = function() { if (this.replay_position + 1 >= this.record_length) { return; } @@ -131,9 +133,9 @@ this.TimeMachine = class TimeMachine { this.replay_position += 1; this.replay(); return this.sendStatus(); - } + }; - stepForward() { + TimeMachine.prototype.stepForward = function() { if (this.replay_position <= 1) { return; } @@ -141,9 +143,9 @@ this.TimeMachine = class TimeMachine { this.replay_position--; this.replay(); return this.sendStatus(); - } + }; - replayControls() { + TimeMachine.prototype.replayControls = function() { var index; if (this.replay_position >= this.record_length) { return; @@ -156,9 +158,9 @@ this.TimeMachine = class TimeMachine { this.copyGlobal(this.history[index].gamepad, this.runtime.vm.context.global.gamepad); this.copyGlobal(this.history[index].touch, this.runtime.vm.context.global.touch); return this.copyGlobal(this.history[index].mouse, this.runtime.vm.context.global.mouse); - } + }; - resetControls() { + TimeMachine.prototype.resetControls = function() { var mouse, touch; this.runtime.keyboard.reset(); touch = this.runtime.vm.context.global.touch; @@ -169,24 +171,23 @@ this.TimeMachine = class TimeMachine { mouse.left = 0; mouse.right = 0; return mouse.middle = 0; - } + }; - replay(clone = false) { + TimeMachine.prototype.replay = function(clone) { var index; + if (clone == null) { + clone = false; + } index = (this.record_index - this.replay_position + this.max_length) % this.max_length; this.copyGlobal((clone ? this.storableHistory(this.history[index]) : this.history[index]), this.runtime.vm.context.global); - //@runtime.vm.context.global = if clone then @storableHistory(@history[index]) else @history[index] - //@runtime.vm.context.meta.global = @runtime.vm.context.global - //@runtime.vm.context.object = @runtime.vm.context.global - //@runtime.vm.context.local = @runtime.vm.context.global this.runtime.vm.call("draw"); if (this.runtime.vm.runner.tick != null) { this.runtime.vm.runner.tick(); } return this.runtime.watchStep(); - } + }; - copyGlobal(source, dest) { + TimeMachine.prototype.copyGlobal = function(source, dest) { var key, value; for (key in source) { value = source[key]; @@ -202,9 +203,9 @@ this.TimeMachine = class TimeMachine { delete dest[key]; } } - } + }; - sendStatus() { + TimeMachine.prototype.sendStatus = function() { return this.runtime.listener.postMessage({ name: "time_machine", command: "status", @@ -212,32 +213,13 @@ this.TimeMachine = class TimeMachine { head: this.record_length - this.replay_position, max: this.max_length }); - } + }; - storableHistory(value) { + TimeMachine.prototype.storableHistory = function(value) { var clones, global, refs; global = this.runtime.vm.context.global; - this.excluded = [ - global.screen, - global.system, - //global.keyboard - global.audio, - //global.gamepad - //global.touch - //global.mouse - global.sprites, - global.maps, - global.sounds, - global.music, - global.assets, - global.asset_manager, - global.fonts, - global.storage, - window - ]; + this.excluded = [global.screen, global.system, global.audio, global.sprites, global.maps, global.sounds, global.music, global.assets, global.asset_manager, global.fonts, global.storage, window]; if (global.PIXI != null) { - // for key,value of window - // @excluded.push value this.excluded.push(global.PIXI); } if (global.BABYLON != null) { @@ -276,9 +258,9 @@ this.TimeMachine = class TimeMachine { refs = []; clones = []; return this.makeStorableObject(value, refs, clones); - } + }; - makeStorableObject(value, refs, clones) { + TimeMachine.prototype.makeStorableObject = function(value, refs, clones) { var i, index, j, key, len, res, v; if (value == null) { return value; @@ -327,6 +309,8 @@ this.TimeMachine = class TimeMachine { } else { return value; } - } + }; + + return TimeMachine; -}; +})(); diff --git a/static/js/runtime/watcher.js b/static/js/runtime/watcher.js index 475a7f60..3c728bbe 100644 --- a/static/js/runtime/watcher.js +++ b/static/js/runtime/watcher.js @@ -1,16 +1,16 @@ -this.Watcher = class Watcher { - constructor(runtime) { +this.Watcher = (function() { + function Watcher(runtime) { this.runtime = runtime; this.vm = this.runtime.vm; } - update() { + Watcher.prototype.update = function() { if (this.watching_variables) { return this.step(); } - } + }; - watch(variables) { + Watcher.prototype.watch = function(variables) { this.watching = true; this.watching_variables = variables; this.exclusion_list = [this.vm.context.global.screen, this.vm.context.global.system, this.vm.context.global.keyboard, this.vm.context.global.audio, this.vm.context.global.gamepad, this.vm.context.global.touch, this.vm.context.global.mouse, this.vm.context.global.sprites, this.vm.context.global.maps, this.vm.context.global.sounds, this.vm.context.global.music, this.vm.context.global.assets, this.vm.context.global.asset_manager, this.vm.context.global.fonts, this.vm.context.global.storage]; @@ -48,14 +48,17 @@ this.Watcher = class Watcher { this.exclusion_list.push(this.vm.context.global.print); } return this.step(); - } + }; - stop() { + Watcher.prototype.stop = function() { return this.watching = false; - } + }; - step(variables = this.watching_variables) { + Watcher.prototype.step = function(variables) { var index, j, len, res, v, value, vs; + if (variables == null) { + variables = this.watching_variables; + } if (!this.watching) { return; } @@ -80,10 +83,16 @@ this.Watcher = class Watcher { name: "watch_update", data: res }); - } + }; - exploreValue(value, depth = 1, array_max = 10) { + Watcher.prototype.exploreValue = function(value, depth, array_max) { var i, j, key, len, res, v; + if (depth == null) { + depth = 1; + } + if (array_max == null) { + array_max = 10; + } if (value == null) { return { type: "number", @@ -121,8 +130,8 @@ this.Watcher = class Watcher { if (value.classname) { v = "class " + value.classname; } - if ((value.class != null) && (value.class.classname != null)) { - v = value.class.classname; + if ((value["class"] != null) && (value["class"].classname != null)) { + v = value["class"].classname; } return { type: "object", @@ -159,6 +168,8 @@ this.Watcher = class Watcher { value: value }; } - } + }; + + return Watcher; -}; +})(); diff --git a/static/js/sound/soundeditor.js b/static/js/sound/soundeditor.js index 3fe393e0..20bc1fd4 100644 --- a/static/js/sound/soundeditor.js +++ b/static/js/sound/soundeditor.js @@ -1,6 +1,11 @@ -this.SoundEditor = class SoundEditor extends Manager { - constructor(app) { - super(app); +var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +this.SoundEditor = (function(superClass) { + extend(SoundEditor, superClass); + + function SoundEditor(app) { + SoundEditor.__super__.constructor.call(this, app); this.folder = "sounds"; this.item = "sound"; this.list_change_event = "soundlist"; @@ -11,92 +16,98 @@ this.SoundEditor = class SoundEditor extends Manager { this.init(); } - update() { - return super.update(); - } + SoundEditor.prototype.update = function() { + return SoundEditor.__super__.update.call(this); + }; - openItem(name) { + SoundEditor.prototype.openItem = function(name) { var sound; - super.openItem(name); + SoundEditor.__super__.openItem.call(this, name); sound = this.app.project.getSound(name); if (sound != null) { return sound.play(); } - } + }; - createAsset(folder) { + SoundEditor.prototype.createAsset = function(folder) { var input; input = document.createElement("input"); input.type = "file"; input.accept = ".wav,.ogg,.flac"; - input.addEventListener("change", (event) => { - var f, files, i, len; - files = event.target.files; - if (files.length >= 1) { - for (i = 0, len = files.length; i < len; i++) { - f = files[i]; - this.fileDropped(f, folder); + input.addEventListener("change", (function(_this) { + return function(event) { + var f, files, i, len; + files = event.target.files; + if (files.length >= 1) { + for (i = 0, len = files.length; i < len; i++) { + f = files[i]; + _this.fileDropped(f, folder); + } } - } - }); + }; + })(this)); return input.click(); - } + }; - fileDropped(file, folder) { + SoundEditor.prototype.fileDropped = function(file, folder) { var reader; - console.info(`processing ${file.name}`); + console.info("processing " + file.name); console.info("folder: " + folder); reader = new FileReader(); - reader.addEventListener("load", () => { - var audioContext, file_size; - file_size = reader.result.byteLength; - console.info("file read, size = " + file_size); - if (file_size > 30000000) { // client side limit 30 Mb - this.app.appui.showNotification(this.app.translator.get("Audio file is too heavy")); - return; - } - audioContext = new AudioContext(); - return audioContext.decodeAudioData(reader.result, (decoded) => { - var ext, name, r2, sound, thumbnailer; - console.info(decoded); - thumbnailer = new SoundThumbnailer(decoded, 96, 64); - name = file.name.split(".")[0]; - ext = file.name.split(".")[1].toLowerCase(); - name = this.findNewFilename(name, "getSound", folder); - if (folder != null) { - name = folder.getFullDashPath() + "-" + name; - } - if (folder != null) { - folder.setOpen(true); + reader.addEventListener("load", (function(_this) { + return function() { + var audioContext, file_size; + file_size = reader.result.byteLength; + console.info("file read, size = " + file_size); + if (file_size > 30000000) { + _this.app.appui.showNotification(_this.app.translator.get("Audio file is too heavy")); + return; } - sound = this.app.project.createSound(name, thumbnailer.canvas.toDataURL(), file_size); - sound.uploading = true; - this.setSelectedItem(name); - r2 = new FileReader(); - r2.addEventListener("load", () => { - var data; - sound.local_url = r2.result; - data = r2.result.split(",")[1]; - this.app.project.addPendingChange(this); - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: `sounds/${name}.${ext}`, - properties: {}, - content: data, - thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] - }, (msg) => { - console.info(msg); - this.app.project.removePendingChange(this); - sound.uploading = false; - this.app.project.updateSoundList(); - return this.checkNameFieldActivation(); + audioContext = new AudioContext(); + return audioContext.decodeAudioData(reader.result, function(decoded) { + var ext, name, r2, sound, thumbnailer; + console.info(decoded); + thumbnailer = new SoundThumbnailer(decoded, 96, 64); + name = file.name.split(".")[0]; + ext = file.name.split(".")[1].toLowerCase(); + name = _this.findNewFilename(name, "getSound", folder); + if (folder != null) { + name = folder.getFullDashPath() + "-" + name; + } + if (folder != null) { + folder.setOpen(true); + } + sound = _this.app.project.createSound(name, thumbnailer.canvas.toDataURL(), file_size); + sound.uploading = true; + _this.setSelectedItem(name); + r2 = new FileReader(); + r2.addEventListener("load", function() { + var data; + sound.local_url = r2.result; + data = r2.result.split(",")[1]; + _this.app.project.addPendingChange(_this); + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "sounds/" + name + "." + ext, + properties: {}, + content: data, + thumbnail: thumbnailer.canvas.toDataURL().split(",")[1] + }, function(msg) { + console.info(msg); + _this.app.project.removePendingChange(_this); + sound.uploading = false; + _this.app.project.updateSoundList(); + return _this.checkNameFieldActivation(); + }); }); + return r2.readAsDataURL(file); }); - return r2.readAsDataURL(file); - }); - }); + }; + })(this)); return reader.readAsArrayBuffer(file); - } + }; + + return SoundEditor; -}; +})(Manager); diff --git a/static/js/spriteeditor/colorpicker.js b/static/js/spriteeditor/colorpicker.js index 8b1a2d90..f9bd269f 100644 --- a/static/js/spriteeditor/colorpicker.js +++ b/static/js/spriteeditor/colorpicker.js @@ -1,5 +1,5 @@ -this.ColorPicker = class ColorPicker { - constructor(editor) { +this.ColorPicker = (function() { + function ColorPicker(editor) { this.editor = editor; this.canvas = document.createElement("canvas"); this.canvas.width = 146; @@ -12,18 +12,24 @@ this.ColorPicker = class ColorPicker { this.lightness = this.num_blocks - 2; this.updateColor(); this.update(); - this.canvas.addEventListener("mousedown", (event) => { - return this.mouseDown(event); - }); - this.canvas.addEventListener("mousemove", (event) => { - return this.mouseMove(event); - }); - document.addEventListener("mouseup", (event) => { - return this.mouseUp(event); - }); + this.canvas.addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.mouseDown(event); + }; + })(this)); + this.canvas.addEventListener("mousemove", (function(_this) { + return function(event) { + return _this.mouseMove(event); + }; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function(event) { + return _this.mouseUp(event); + }; + })(this)); } - colorPicked(c) { + ColorPicker.prototype.colorPicked = function(c) { var col, i, j, match; if (typeof c === "string") { match = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/.exec(c.replace(/ /g, "")); @@ -36,7 +42,7 @@ this.ColorPicker = class ColorPicker { for (i = j = 0; j <= 2; i = ++j) { c[i] = Math.max(0, Math.min(255, c[i])); } - this.color = `rgb(${c[0]},${c[1]},${c[2]})`; + this.color = "rgb(" + c[0] + "," + c[1] + "," + c[2] + ")"; this.editor.setColor(this.color); col = this.RGBtoHSV(c[0], c[1], c[2]); this.hue = Math.round(col.h * this.num_blocks * 2) % (this.num_blocks * 2); @@ -51,32 +57,32 @@ this.ColorPicker = class ColorPicker { this.lightness -= 1; } return this.update(); - } + }; - updateColor() { + ColorPicker.prototype.updateColor = function() { var col, h, s, v; if (this.type === "gray") { v = Math.floor(255 * this.valueToLight(this.lightness * 2 / (this.num_blocks * 2 - 1))); - this.color = `rgb(${v},${v},${v})`; + this.color = "rgb(" + v + "," + v + "," + v + ")"; } else { h = this.hue / (this.num_blocks * 2); s = (this.saturation + 1) / this.num_blocks; v = this.valueToLight((this.lightness + 1) / this.num_blocks); col = this.HSVtoRGB(h, s, v); - this.color = `rgb(${col.r},${col.g},${col.b})`; + this.color = "rgb(" + col.r + "," + col.g + "," + col.b + ")"; } return this.editor.setColor(this.color); - } + }; - valueToLight(v) { + ColorPicker.prototype.valueToLight = function(v) { return Math.pow(Math.max(0, v), 2.2); - } + }; - lightToValue(l) { + ColorPicker.prototype.lightToValue = function(l) { return Math.pow(Math.max(0, l), 1 / 2.2); - } + }; - update() { + ColorPicker.prototype.update = function() { var ay, col, context, grd, h, hue, j, k, l, light, m, n, ref, ref1, ref2, ref3, s, v, x, y; context = this.canvas.getContext("2d"); context.clearRect(0, 0, this.canvas.width, this.canvas.height); @@ -101,15 +107,13 @@ this.ColorPicker = class ColorPicker { grd.addColorStop(0, 'rgba(255,255,255,0)'); grd.addColorStop(1, "rgba(255,255,255,.5)"); context.fillStyle = grd; -//context.fillRect 0,@canvas.height-@block*2,@canvas.width,@block*2 -//context.fillRect 0,@block*7,@canvas.width,@block*@num_blocks for (light = j = 0, ref = this.num_blocks * 2 - 1; j <= ref; light = j += 1) { if (this.type === "gray" && this.lightness * 2 === light) { context.fillStyle = "#FFF"; context.fillRoundRect(light * this.block * .5 - 1, 3 * this.block - 1, this.block * .5 + 2, this.block + 2, 1); } l = this.valueToLight(light / (this.num_blocks * 2 - 1)); - context.fillStyle = `hsl(0,0%,${l * 100}%)`; + context.fillStyle = "hsl(0,0%," + (l * 100) + "%)"; context.fillRoundRect(light * this.block * .5 + 1, 3 * this.block + 1, this.block * .5 - 2, this.block - 2, 1); } for (hue = k = 0, ref1 = this.num_blocks * 2 - 1; k <= ref1; hue = k += 1) { @@ -117,7 +121,7 @@ this.ColorPicker = class ColorPicker { context.fillStyle = "#FFF"; context.fillRoundRect(hue * this.block * .5 - 1, 5 * this.block - 1, this.block * .5 + 2, this.block + 2, 1); } - context.fillStyle = `hsl(${hue / this.num_blocks * 180},60%,50%)`; + context.fillStyle = "hsl(" + (hue / this.num_blocks * 180) + ",60%,50%)"; context.fillRoundRect(hue * this.block * .5 + 1, 5 * this.block + 1, this.block * .5 - 2, this.block - 2, 1); } for (y = m = 0, ref2 = this.num_blocks - 1; m <= ref2; y = m += 1) { @@ -131,19 +135,19 @@ this.ColorPicker = class ColorPicker { s = (x + 1) / this.num_blocks; v = this.valueToLight((ay + 1) / this.num_blocks); col = this.HSVtoRGB(h, s, v); - context.fillStyle = `rgb(${col.r},${col.g},${col.b})`; + context.fillStyle = "rgb(" + col.r + "," + col.g + "," + col.b + ")"; l = this.num_blocks - 1 - light; context.fillRoundRect(x * this.block + 1, (y + 7) * this.block + 1, this.block - 2, this.block - 2, 2); } } - } + }; - mouseDown(event) { + ColorPicker.prototype.mouseDown = function(event) { this.mousepressed = true; return this.mouseMove(event); - } + }; - mouseMove(event) { + ColorPicker.prototype.mouseMove = function(event) { var b, hue, lightness, min, saturation, x, y; if (this.mousepressed) { b = this.canvas.getBoundingClientRect(); @@ -182,13 +186,13 @@ this.ColorPicker = class ColorPicker { } } return false; - } + }; - mouseUp(event) { + ColorPicker.prototype.mouseUp = function(event) { return this.mousepressed = false; - } + }; - rgbToHsl(r, g, b) { + ColorPicker.prototype.rgbToHsl = function(r, g, b) { var d, h, l, max, min, s; r /= 255; g /= 255; @@ -201,7 +205,6 @@ this.ColorPicker = class ColorPicker { if (max === min) { h = s = 0; } else { - // achromatic d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { @@ -217,9 +220,9 @@ this.ColorPicker = class ColorPicker { h /= 6; } return [h, s, l]; - } + }; - HSVtoRGB(h, s, v) { + ColorPicker.prototype.HSVtoRGB = function(h, s, v) { var b, f, g, i, p, q, r, t; i = Math.floor(h * 6); f = h * 6 - i; @@ -262,9 +265,9 @@ this.ColorPicker = class ColorPicker { g: Math.round(g * 255), b: Math.round(b * 255) }; - } + }; - RGBtoHSV(r, g, b) { + ColorPicker.prototype.RGBtoHSV = function(r, g, b) { var d, h, max, min, s, v; max = Math.max(r, g, b); min = Math.min(r, g, b); @@ -293,6 +296,8 @@ this.ColorPicker = class ColorPicker { s: s, v: v }; - } + }; + + return ColorPicker; -}; +})(); diff --git a/static/js/spriteeditor/drawtool.js b/static/js/spriteeditor/drawtool.js index e0861eb6..6800c2e6 100644 --- a/static/js/spriteeditor/drawtool.js +++ b/static/js/spriteeditor/drawtool.js @@ -1,139 +1,147 @@ +var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + this.DrawTool = (function() { - class DrawTool { - constructor(name, icon) { - this.name = name; - this.icon = icon; - this.parameters = {}; - this.hsymmetry = false; - this.vsymmetry = false; - this.tile = true; - } + function DrawTool(name, icon) { + this.name = name; + this.icon = icon; + this.parameters = {}; + this.hsymmetry = false; + this.vsymmetry = false; + this.tile = true; + } - getSize(sprite) { - var size; - if (this.parameters["Size"]) { - size = Math.min(sprite.width - 1, sprite.height - 1, 99) * this.parameters["Size"].value / 100; - size = 1 + Math.floor(size); - return size; - } else { - return 1; - } + DrawTool.prototype.getSize = function(sprite) { + var size; + if (this.parameters["Size"]) { + size = Math.min(sprite.width - 1, sprite.height - 1, 99) * this.parameters["Size"].value / 100; + size = 1 + Math.floor(size); + return size; + } else { + return 1; } + }; - getRoundness() { - if (this.shape === "round") { - return 1; - } else { - return 0; - } + DrawTool.prototype.getRoundness = function() { + if (this.shape === "round") { + return 1; + } else { + return 0; } + }; - start(sprite, x, y, button, shiftkey) { - this.pixels = {}; - if (!shiftkey) { - this.last_x = x; - this.last_y = y; - } - return this.move(sprite, x, y, button); + DrawTool.prototype.start = function(sprite, x, y, button, shiftkey) { + this.pixels = {}; + if (!shiftkey) { + this.last_x = x; + this.last_y = y; } + return this.move(sprite, x, y, button); + }; - move(sprite, x, y, button, pass = 0) { - var d, i, k, ref1, xx, yy; - if (Math.abs(x - this.last_x) < 2 && Math.abs(y - this.last_y) < 2) { - this.domove(sprite, x, y, button, pass); - } else { - d = Math.max(Math.abs(x - this.last_x), Math.abs(y - this.last_y)); - for (i = k = 1, ref1 = d; k <= ref1; i = k += 1) { - xx = Math.round(this.last_x + (x - this.last_x) * i / d); - yy = Math.round(this.last_y + (y - this.last_y) * i / d); - this.domove(sprite, xx, yy, button, pass); - } + DrawTool.prototype.move = function(sprite, x, y, button, pass) { + var d, i, k, ref1, xx, yy; + if (pass == null) { + pass = 0; + } + if (Math.abs(x - this.last_x) < 2 && Math.abs(y - this.last_y) < 2) { + this.domove(sprite, x, y, button, pass); + } else { + d = Math.max(Math.abs(x - this.last_x), Math.abs(y - this.last_y)); + for (i = k = 1, ref1 = d; k <= ref1; i = k += 1) { + xx = Math.round(this.last_x + (x - this.last_x) * i / d); + yy = Math.round(this.last_y + (y - this.last_y) * i / d); + this.domove(sprite, xx, yy, button, pass); } - this.last_x = x; - return this.last_y = y; } + this.last_x = x; + return this.last_y = y; + }; - domove(sprite, x, y, button, pass = 0) { - var d, d1, d2, di, dj, dn, i, ii, j, jj, k, m, nx, ny, r2, ref1, ref2, results, roundness, size, xx, yy; - size = this.getSize(sprite); - dn = size % 2 === 0 ? 1 : 0; - if (pass < 1 && this.vsymmetry) { - nx = sprite.width - 1 - x - dn; - this.domove(sprite, nx, y, button, 1); - } - if (pass < 2 && this.hsymmetry) { - ny = sprite.height - 1 - y - dn; - this.domove(sprite, x, ny, button, 2); - } - d = (size - 1) / 2; - d1 = Math.ceil(-d); - d2 = Math.ceil(d); - m = (d1 + d2) / 2; - roundness = this.getRoundness(); - r2 = (d + .5) * (d + .5); - r2 *= 1 + (1 - roundness); - results = []; - for (i = k = ref1 = d1, ref2 = d2; k <= ref2; i = k += 1) { - results.push((function() { - var l, ref3, ref4, results1; - results1 = []; - for (j = l = ref3 = d1, ref4 = d2; l <= ref4; j = l += 1) { - di = i - m; - dj = j - m; - if (di * di + dj * dj > r2) { - continue; - } - xx = x + i; - yy = y + j; - if (this.tile) { - results1.push((function() { - var n, results2; - results2 = []; - for (ii = n = -1; n <= 1; ii = n += 1) { - results2.push((function() { - var o, results3; - results3 = []; - for (jj = o = -1; o <= 1; jj = o += 1) { - results3.push(this.preprocessPixel(sprite, xx + ii * sprite.width, yy + jj * sprite.height, button)); - } - return results3; - }).call(this)); - } - return results2; - }).call(this)); - } else { - results1.push(this.preprocessPixel(sprite, xx, yy, button)); - } + DrawTool.prototype.domove = function(sprite, x, y, button, pass) { + var d, d1, d2, di, dj, dn, i, ii, j, jj, k, m, nx, ny, r2, ref1, ref2, results, roundness, size, xx, yy; + if (pass == null) { + pass = 0; + } + size = this.getSize(sprite); + dn = size % 2 === 0 ? 1 : 0; + if (pass < 1 && this.vsymmetry) { + nx = sprite.width - 1 - x - dn; + this.domove(sprite, nx, y, button, 1); + } + if (pass < 2 && this.hsymmetry) { + ny = sprite.height - 1 - y - dn; + this.domove(sprite, x, ny, button, 2); + } + d = (size - 1) / 2; + d1 = Math.ceil(-d); + d2 = Math.ceil(d); + m = (d1 + d2) / 2; + roundness = this.getRoundness(); + r2 = (d + .5) * (d + .5); + r2 *= 1 + (1 - roundness); + results = []; + for (i = k = ref1 = d1, ref2 = d2; k <= ref2; i = k += 1) { + results.push((function() { + var l, ref3, ref4, results1; + results1 = []; + for (j = l = ref3 = d1, ref4 = d2; l <= ref4; j = l += 1) { + di = i - m; + dj = j - m; + if (di * di + dj * dj > r2) { + continue; } - return results1; - }).call(this)); - } - return results; + xx = x + i; + yy = y + j; + if (this.tile) { + results1.push((function() { + var n, results2; + results2 = []; + for (ii = n = -1; n <= 1; ii = n += 1) { + results2.push((function() { + var o, results3; + results3 = []; + for (jj = o = -1; o <= 1; jj = o += 1) { + results3.push(this.preprocessPixel(sprite, xx + ii * sprite.width, yy + jj * sprite.height, button)); + } + return results3; + }).call(this)); + } + return results2; + }).call(this)); + } else { + results1.push(this.preprocessPixel(sprite, xx, yy, button)); + } + } + return results1; + }).call(this)); } + return results; + }; - preprocessPixel(sprite, x, y, button) { - if (x < 0 || x >= sprite.width || y < 0 || y >= sprite.height) { - return; - } - if (this.pixels[`${x}-${y}`] == null) { - this.pixels[`${x}-${y}`] = true; - return this.processPixel(sprite, x, y, button); - } + DrawTool.prototype.preprocessPixel = function(sprite, x, y, button) { + if (x < 0 || x >= sprite.width || y < 0 || y >= sprite.height) { + return; + } + if (this.pixels[x + "-" + y] == null) { + this.pixels[x + "-" + y] = true; + return this.processPixel(sprite, x, y, button); } - - processPixel(sprite, x, y) {} - }; + DrawTool.prototype.processPixel = function(sprite, x, y) {}; + DrawTool.tools = []; return DrawTool; -}).call(this); +})(); + +this.PencilTool = (function(superClass) { + extend(PencilTool, superClass); -this.PencilTool = class PencilTool extends this.DrawTool { - constructor() { - super("Pencil", "fa-pencil-alt"); + function PencilTool() { + PencilTool.__super__.constructor.call(this, "Pencil", "fa-pencil-alt"); this.parameters["Size"] = { type: "size_shape", value: 0 @@ -148,7 +156,7 @@ this.PencilTool = class PencilTool extends this.DrawTool { }; } - processPixel(sprite, x, y, button) { + PencilTool.prototype.processPixel = function(sprite, x, y, button) { var c; if (button === 2) { return sprite.erasePixel(x, y, this.parameters["Opacity"].value / 100); @@ -159,15 +167,19 @@ this.PencilTool = class PencilTool extends this.DrawTool { c.fillRect(x, y, 1, 1); return c.globalAlpha = 1; } - } + }; -}; + return PencilTool; + +})(this.DrawTool); this.DrawTool.tools.push(new this.PencilTool()); -this.EraserTool = class EraserTool extends this.DrawTool { - constructor() { - super("Eraser", "fa-eraser"); +this.EraserTool = (function(superClass) { + extend(EraserTool, superClass); + + function EraserTool() { + EraserTool.__super__.constructor.call(this, "Eraser", "fa-eraser"); this.parameters["Size"] = { type: "size_shape", value: 0 @@ -178,17 +190,21 @@ this.EraserTool = class EraserTool extends this.DrawTool { }; } - processPixel(sprite, x, y) { + EraserTool.prototype.processPixel = function(sprite, x, y) { return sprite.erasePixel(x, y, this.parameters["Opacity"].value / 100); - } + }; + + return EraserTool; -}; +})(this.DrawTool); this.DrawTool.tools.push(new this.EraserTool()); -this.FillTool = class FillTool extends this.DrawTool { - constructor() { - super("Fill", "fa-fill-drip"); +this.FillTool = (function(superClass) { + extend(FillTool, superClass); + + function FillTool() { + FillTool.__super__.constructor.call(this, "Fill", "fa-fill-drip"); this.parameters["Threshold"] = { type: "range", value: 0 @@ -203,7 +219,7 @@ this.FillTool = class FillTool extends this.DrawTool { }; } - start(sprite, x, y) { + FillTool.prototype.start = function(sprite, x, y) { var alpha, c, check, data, fill, index, list, p, ref, table, threshold; if (x < 0 || y < 0 || x >= sprite.width || y >= sprite.height) { return; @@ -221,13 +237,13 @@ this.FillTool = class FillTool extends this.DrawTool { fill = c.getImageData(x, y, 1, 1); list = [[x, y]]; table = {}; - table[`${x}-${y}`] = true; + table[x + "-" + y] = true; check = function(x, y) { var da, db, dg, dr, index; if (x < 0 || y < 0 || x >= sprite.width || y >= sprite.height) { return false; } - if (table[`${x}-${y}`]) { + if (table[x + "-" + y]) { return false; } index = 4 * (x + y * sprite.width); @@ -247,38 +263,42 @@ this.FillTool = class FillTool extends this.DrawTool { data.data[index + 2] = fill.data[2]; data.data[index + 3] = fill.data[3]; if (check(x - 1, y)) { - table[`${x - 1}-${y}`] = true; + table[(x - 1) + "-" + y] = true; list.push([x - 1, y]); } if (check(x + 1, y)) { - table[`${x + 1}-${y}`] = true; + table[(x + 1) + "-" + y] = true; list.push([x + 1, y]); } if (check(x, y - 1)) { - table[`${x}-${y - 1}`] = true; + table[x + "-" + (y - 1)] = true; list.push([x, y - 1]); } if (check(x, y + 1)) { - table[`${x}-${y + 1}`] = true; + table[x + "-" + (y + 1)] = true; list.push([x, y + 1]); } } c.putImageData(data, 0, 0); - } + }; + + FillTool.prototype.move = function(sprite, x, y) {}; - move(sprite, x, y) {} + return FillTool; -}; +})(this.DrawTool); this.DrawTool.tools.push(new this.FillTool()); -this.BrightenTool = class BrightenTool extends this.DrawTool { - constructor(parent) { - super("Brighten", "fa-sun"); +this.BrightenTool = (function(superClass) { + extend(BrightenTool, superClass); + + function BrightenTool(parent) { + BrightenTool.__super__.constructor.call(this, "Brighten", "fa-sun"); this.parameters = parent.parameters; } - processPixel(sprite, x, y) { + BrightenTool.prototype.processPixel = function(sprite, x, y) { var amount, b, c, data, db, dg, dr, g, r, v; amount = this.parameters["Amount"].value / 100; c = sprite.getContext(); @@ -295,18 +315,21 @@ this.BrightenTool = class BrightenTool extends this.DrawTool { data.data[1] = Math.min(255, v + dg); data.data[2] = Math.min(255, v + db); return c.putImageData(data, x, y); - } + }; + + return BrightenTool; + +})(this.DrawTool); -}; +this.DarkenTool = (function(superClass) { + extend(DarkenTool, superClass); -//@DrawTool.tools.push new @BrightenTool() -this.DarkenTool = class DarkenTool extends this.DrawTool { - constructor(parent) { - super("Darken", "fa-moon"); + function DarkenTool(parent) { + DarkenTool.__super__.constructor.call(this, "Darken", "fa-moon"); this.parameters = parent.parameters; } - processPixel(sprite, x, y) { + DarkenTool.prototype.processPixel = function(sprite, x, y) { var amount, b, c, data, db, dg, dr, g, r, v; amount = this.parameters["Amount"].value / 100; c = sprite.getContext(); @@ -323,18 +346,21 @@ this.DarkenTool = class DarkenTool extends this.DrawTool { data.data[1] = Math.max(0, v + dg); data.data[2] = Math.max(0, v + db); return c.putImageData(data, x, y); - } + }; + + return DarkenTool; + +})(this.DrawTool); -}; +this.SmoothenTool = (function(superClass) { + extend(SmoothenTool, superClass); -//@DrawTool.tools.push new @DarkenTool() -this.SmoothenTool = class SmoothenTool extends this.DrawTool { - constructor(parent) { - super("Smoothen", "fa-brush"); + function SmoothenTool(parent) { + SmoothenTool.__super__.constructor.call(this, "Smoothen", "fa-brush"); this.parameters = parent.parameters; } - processPixel(sprite, x, y) { + SmoothenTool.prototype.processPixel = function(sprite, x, y) { var amount, c, co, coef, data, i, j, k, l, ref, sum, xx, yy; amount = this.parameters["Amount"].value / 100; c = sprite.getContext(); @@ -362,18 +388,21 @@ this.SmoothenTool = class SmoothenTool extends this.DrawTool { data.data[2] = sum[2] / coef * amount + (1 - amount) * ref.data[2]; data.data[3] = sum[3] / coef * amount + (1 - amount) * ref.data[3]; return c.putImageData(data, x, y); - } + }; + + return SmoothenTool; -}; +})(this.DrawTool); -//@DrawTool.tools.push new @SmoothenTool() -this.SharpenTool = class SharpenTool extends this.DrawTool { - constructor(parent) { - super("Sharpen", "fa-adjust"); +this.SharpenTool = (function(superClass) { + extend(SharpenTool, superClass); + + function SharpenTool(parent) { + SharpenTool.__super__.constructor.call(this, "Sharpen", "fa-adjust"); this.parameters = parent.parameters; } - processPixel(sprite, x, y) { + SharpenTool.prototype.processPixel = function(sprite, x, y) { var amount, c, co, coef, data, i, j, k, l, ref, sum, xx, yy; amount = this.parameters["Amount"].value / 100; c = sprite.getContext(); @@ -404,18 +433,21 @@ this.SharpenTool = class SharpenTool extends this.DrawTool { ref.data[2] += sum[2] / coef * amount; ref.data[3] += sum[3] / coef * amount; return c.putImageData(ref, x, y); - } + }; + + return SharpenTool; -}; +})(this.DrawTool); -//@DrawTool.tools.push new @EnhanceTool() -this.SaturationTool = class SaturationTool extends this.DrawTool { - constructor(parent) { - super("Saturation", "fa-palette"); +this.SaturationTool = (function(superClass) { + extend(SaturationTool, superClass); + + function SaturationTool(parent) { + SaturationTool.__super__.constructor.call(this, "Saturation", "fa-palette"); this.parameters = parent.parameters; } - processPixel(sprite, x, y) { + SaturationTool.prototype.processPixel = function(sprite, x, y) { var amount, b, c, data, db, dg, dr, g, r, v; amount = this.parameters["Amount"].value / 100; amount = amount > .5 ? amount * 2 : .5 + amount; @@ -432,14 +464,17 @@ this.SaturationTool = class SaturationTool extends this.DrawTool { data.data[1] = Math.max(0, v + dg * amount); data.data[2] = Math.max(0, v + db * amount); return c.putImageData(data, x, y); - } + }; + + return SaturationTool; -}; +})(this.DrawTool); -//@DrawTool.tools.push new @SaturationTool() -this.EnhanceTool = class EnhanceTool extends this.DrawTool { - constructor() { - super("Enhance", "fa-magic"); +this.EnhanceTool = (function(superClass) { + extend(EnhanceTool, superClass); + + function EnhanceTool() { + EnhanceTool.__super__.constructor.call(this, "Enhance", "fa-magic"); this.parameters["Tool"] = { type: "tool", set: [new BrightenTool(this), new DarkenTool(this), new SmoothenTool(this), new SharpenTool(this), new SaturationTool(this)], @@ -455,22 +490,28 @@ this.EnhanceTool = class EnhanceTool extends this.DrawTool { }; } - processPixel(sprite, x, y) { + EnhanceTool.prototype.processPixel = function(sprite, x, y) { return this.parameters.Tool.set[this.parameters.Tool.value].processPixel(sprite, x, y); - } + }; + + return EnhanceTool; -}; +})(this.DrawTool); this.DrawTool.tools.push(new this.EnhanceTool()); -this.SelectTool = class SelectTool extends this.DrawTool { - constructor() { - super("Select", "fa-vector-square"); +this.SelectTool = (function(superClass) { + extend(SelectTool, superClass); + + function SelectTool() { + SelectTool.__super__.constructor.call(this, "Select", "fa-vector-square"); this.selectiontool = true; } - processPixel(sprite, x, y) {} + SelectTool.prototype.processPixel = function(sprite, x, y) {}; + + return SelectTool; -}; +})(this.DrawTool); this.DrawTool.tools.push(new this.SelectTool()); diff --git a/static/js/spriteeditor/spriteeditor.js b/static/js/spriteeditor/spriteeditor.js index 96e9cdbd..c2496fe1 100644 --- a/static/js/spriteeditor/spriteeditor.js +++ b/static/js/spriteeditor/spriteeditor.js @@ -1,7 +1,12 @@ -this.SpriteEditor = class SpriteEditor extends Manager { - constructor(app) { +var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +this.SpriteEditor = (function(superClass) { + extend(SpriteEditor, superClass); + + function SpriteEditor(app) { var i, l, len, ref, tool; - super(app); + SpriteEditor.__super__.constructor.call(this, app); this.folder = "sprites"; this.item = "sprite"; this.list_change_event = "spritelist"; @@ -18,110 +23,152 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.animation_panel = new AnimationPanel(this); this.save_delay = 1000; this.save_time = 0; - setInterval((() => { - return this.checkSave(); - }), this.save_delay / 2); - document.getElementById("sprite-width").addEventListener("input", (event) => { - return this.spriteDimensionChanged("width"); - }); - document.getElementById("sprite-height").addEventListener("input", (event) => { - return this.spriteDimensionChanged("height"); - }); - document.getElementById("colortext").addEventListener("input", (event) => { - return this.colortextChanged(); - }); - document.getElementById("colortext-copy").addEventListener("click", (event) => { - return this.colortextCopy(); - }); - this.sprite_size_validator = new InputValidator([document.getElementById("sprite-width"), document.getElementById("sprite-height")], document.getElementById("sprite-size-button"), null, (value) => { - return this.saveDimensionChange(value); - }); + setInterval(((function(_this) { + return function() { + return _this.checkSave(); + }; + })(this)), this.save_delay / 2); + document.getElementById("sprite-width").addEventListener("input", (function(_this) { + return function(event) { + return _this.spriteDimensionChanged("width"); + }; + })(this)); + document.getElementById("sprite-height").addEventListener("input", (function(_this) { + return function(event) { + return _this.spriteDimensionChanged("height"); + }; + })(this)); + document.getElementById("colortext").addEventListener("input", (function(_this) { + return function(event) { + return _this.colortextChanged(); + }; + })(this)); + document.getElementById("colortext-copy").addEventListener("click", (function(_this) { + return function(event) { + return _this.colortextCopy(); + }; + })(this)); + this.sprite_size_validator = new InputValidator([document.getElementById("sprite-width"), document.getElementById("sprite-height")], document.getElementById("sprite-size-button"), null, (function(_this) { + return function(value) { + return _this.saveDimensionChange(value); + }; + })(this)); this.selected_sprite = null; - this.app.appui.setAction("undo-sprite", () => { - return this.undo(); - }); - this.app.appui.setAction("redo-sprite", () => { - return this.redo(); - }); - this.app.appui.setAction("copy-sprite", () => { - return this.copy(); - }); - this.app.appui.setAction("cut-sprite", () => { - return this.cut(); - }); - this.app.appui.setAction("paste-sprite", () => { - return this.paste(); - }); - this.app.appui.setAction("sprite-helper-tile", () => { - return this.toggleTile(); - }); - this.app.appui.setAction("sprite-helper-vsymmetry", () => { - return this.toggleVSymmetry(); - }); - this.app.appui.setAction("sprite-helper-hsymmetry", () => { - return this.toggleHSymmetry(); - }); - this.app.appui.setAction("selection-operation-film", () => { - return this.stripToAnimation(); - }); - this.app.appui.setAction("selection-action-horizontal-flip", () => { - return this.flipHSprite(); - }); - this.app.appui.setAction("selection-action-vertical-flip", () => { - return this.flipVSprite(); - }); - this.app.appui.setAction("selection-action-rotate-left", () => { - return this.rotateSprite(-1); - }); - this.app.appui.setAction("selection-action-rotate-right", () => { - return this.rotateSprite(1); - }); - document.addEventListener("keydown", (event) => { - if (document.getElementById("spriteeditor").offsetParent == null) { - return; - } - //console.info event - if ((document.activeElement != null) && document.activeElement.tagName.toLowerCase() === "input") { - return; - } - if (event.key === "Alt" && !this.tool.selectiontool) { - this.setColorPicker(true); - this.alt_pressed = true; - } - if (event.metaKey || event.ctrlKey) { - switch (event.key) { - case "z": - this.undo(); - break; - case "Z": - this.redo(); - break; - case "c": - this.copy(); - break; - case "x": - this.cut(); - break; - case "v": - this.paste(); - break; - default: - return; + this.app.appui.setAction("undo-sprite", (function(_this) { + return function() { + return _this.undo(); + }; + })(this)); + this.app.appui.setAction("redo-sprite", (function(_this) { + return function() { + return _this.redo(); + }; + })(this)); + this.app.appui.setAction("copy-sprite", (function(_this) { + return function() { + return _this.copy(); + }; + })(this)); + this.app.appui.setAction("cut-sprite", (function(_this) { + return function() { + return _this.cut(); + }; + })(this)); + this.app.appui.setAction("paste-sprite", (function(_this) { + return function() { + return _this.paste(); + }; + })(this)); + this.app.appui.setAction("sprite-helper-tile", (function(_this) { + return function() { + return _this.toggleTile(); + }; + })(this)); + this.app.appui.setAction("sprite-helper-vsymmetry", (function(_this) { + return function() { + return _this.toggleVSymmetry(); + }; + })(this)); + this.app.appui.setAction("sprite-helper-hsymmetry", (function(_this) { + return function() { + return _this.toggleHSymmetry(); + }; + })(this)); + this.app.appui.setAction("selection-operation-film", (function(_this) { + return function() { + return _this.stripToAnimation(); + }; + })(this)); + this.app.appui.setAction("selection-action-horizontal-flip", (function(_this) { + return function() { + return _this.flipHSprite(); + }; + })(this)); + this.app.appui.setAction("selection-action-vertical-flip", (function(_this) { + return function() { + return _this.flipVSprite(); + }; + })(this)); + this.app.appui.setAction("selection-action-rotate-left", (function(_this) { + return function() { + return _this.rotateSprite(-1); + }; + })(this)); + this.app.appui.setAction("selection-action-rotate-right", (function(_this) { + return function() { + return _this.rotateSprite(1); + }; + })(this)); + document.addEventListener("keydown", (function(_this) { + return function(event) { + if (document.getElementById("spriteeditor").offsetParent == null) { + return; } - event.preventDefault(); - return event.stopPropagation(); - } - }); - //console.info event - document.addEventListener("keyup", (event) => { - if (event.key === "Alt" && !this.tool.selectiontool) { - this.setColorPicker(false); - return this.alt_pressed = false; - } - }); - document.getElementById("eyedropper").addEventListener("click", () => { - return this.setColorPicker(!this.spriteview.colorpicker); - }); + if ((document.activeElement != null) && document.activeElement.tagName.toLowerCase() === "input") { + return; + } + if (event.key === "Alt" && !_this.tool.selectiontool) { + _this.setColorPicker(true); + _this.alt_pressed = true; + } + if (event.metaKey || event.ctrlKey) { + switch (event.key) { + case "z": + _this.undo(); + break; + case "Z": + _this.redo(); + break; + case "c": + _this.copy(); + break; + case "x": + _this.cut(); + break; + case "v": + _this.paste(); + break; + default: + return; + } + event.preventDefault(); + return event.stopPropagation(); + } + }; + })(this)); + document.addEventListener("keyup", (function(_this) { + return function(event) { + if (event.key === "Alt" && !_this.tool.selectiontool) { + _this.setColorPicker(false); + return _this.alt_pressed = false; + } + }; + })(this)); + document.getElementById("eyedropper").addEventListener("click", (function(_this) { + return function() { + return _this.setColorPicker(!_this.spriteview.colorpicker); + }; + })(this)); ref = DrawTool.tools; for (i = l = 0, len = ref.length; l < len; i = ++l) { tool = ref[i]; @@ -129,111 +176,141 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.createToolOptions(tool); } this.setSelectedTool(DrawTool.tools[0].icon); - document.getElementById("spritelist").addEventListener("dragover", (event) => { - return event.preventDefault(); - }); - //console.info event + document.getElementById("spritelist").addEventListener("dragover", (function(_this) { + return function(event) { + return event.preventDefault(); + }; + })(this)); this.code_tip = new CodeSnippetField(this.app, "#sprite-code-tip"); - this.background_color_picker = new BackgroundColorPicker(this, ((color) => { - this.spriteview.updateBackgroundColor(); - return document.getElementById("sprite-background-color").style.background = color; - }), "sprite"); - document.getElementById("sprite-background-color").addEventListener("mousedown", (event) => { - if (this.background_color_picker.shown) { - return this.background_color_picker.hide(); - } else { - this.background_color_picker.show(); - return event.stopPropagation(); - } - }); + this.background_color_picker = new BackgroundColorPicker(this, ((function(_this) { + return function(color) { + _this.spriteview.updateBackgroundColor(); + return document.getElementById("sprite-background-color").style.background = color; + }; + })(this)), "sprite"); + document.getElementById("sprite-background-color").addEventListener("mousedown", (function(_this) { + return function(event) { + if (_this.background_color_picker.shown) { + return _this.background_color_picker.hide(); + } else { + _this.background_color_picker.show(); + return event.stopPropagation(); + } + }; + })(this)); } - createToolButton(tool) { + SpriteEditor.prototype.createToolButton = function(tool) { var div, parent; parent = document.getElementById("spritetools"); div = document.createElement("div"); div.classList.add("spritetoolbutton"); div.title = tool.name; - div.innerHTML = `
${this.app.translator.get(tool.name)}`; - div.addEventListener("click", () => { - return this.setSelectedTool(tool.icon); - }); - div.id = `spritetoolbutton-${tool.icon}`; + div.innerHTML = "
" + (this.app.translator.get(tool.name)); + div.addEventListener("click", (function(_this) { + return function() { + return _this.setSelectedTool(tool.icon); + }; + })(this)); + div.id = "spritetoolbutton-" + tool.icon; return parent.appendChild(div); - } + }; - createToolOptions(tool) { - var button, div, i, k, key, l, len, p, parent, ref, ref1, t, toolbox; + SpriteEditor.prototype.createToolOptions = function(tool) { + var button, div, fn, i, k, key, l, len, p, parent, ref, ref1, t, toolbox; parent = document.getElementById("spritetooloptionslist"); div = document.createElement("div"); ref = tool.parameters; for (key in ref) { p = ref[key]; if (p.type === "range") { - ((p, key) => { - var input, label; - label = document.createElement("label"); - label.innerText = key; - div.appendChild(label); - input = document.createElement("input"); - input.type = "range"; - input.min = "0"; - input.max = "100"; - input.value = p.value; - input.addEventListener("input", (event) => { - p.value = input.value; - if (key === "Size") { - return this.spriteview.showBrushSize(); - } + (function(_this) { + return (function(p, key) { + var input, label; + label = document.createElement("label"); + label.innerText = key; + div.appendChild(label); + input = document.createElement("input"); + input.type = "range"; + input.min = "0"; + input.max = "100"; + input.value = p.value; + input.addEventListener("input", function(event) { + p.value = input.value; + if (key === "Size") { + return _this.spriteview.showBrushSize(); + } + }); + return div.appendChild(input); }); - return div.appendChild(input); - })(p, key); + })(this)(p, key); } else if (p.type === "size_shape") { - ((p, key) => { - var input, label, shape; - label = document.createElement("label"); - label.innerText = key; - div.appendChild(label); - div.appendChild(document.createElement("br")); - input = document.createElement("input"); - input.style = "width:70% ; vertical-align: top"; - input.type = "range"; - input.min = "0"; - input.max = "100"; - input.value = p.value; - input.addEventListener("input", (event) => { - p.value = input.value; - if (key === "Size") { - return this.spriteview.showBrushSize(); - } - }); - div.appendChild(input); - shape = document.createElement("i"); - shape.style = "verticla-align: top ; padding: 6px 8px ; background: hsl(200,50%,50%) ; border-radius: 4px ;margin-left: 5px ; cursor: pointer ; width: 15px"; - shape.classList.add("fas"); - shape.classList.add("fa-circle"); - shape.title = this.app.translator.get("Shape"); - tool.shape = "round"; - shape.addEventListener("click", () => { - if (tool.shape === "round") { - tool.shape = "square"; - shape.classList.remove("fa-circle"); - shape.classList.add("fa-square-full"); - } else { - tool.shape = "round"; - shape.classList.add("fa-circle"); - shape.classList.remove("fa-square-full"); - } - return this.spriteview.showBrushSize(); + (function(_this) { + return (function(p, key) { + var input, label, shape; + label = document.createElement("label"); + label.innerText = key; + div.appendChild(label); + div.appendChild(document.createElement("br")); + input = document.createElement("input"); + input.style = "width:70% ; vertical-align: top"; + input.type = "range"; + input.min = "0"; + input.max = "100"; + input.value = p.value; + input.addEventListener("input", function(event) { + p.value = input.value; + if (key === "Size") { + return _this.spriteview.showBrushSize(); + } + }); + div.appendChild(input); + shape = document.createElement("i"); + shape.style = "verticla-align: top ; padding: 6px 8px ; background: hsl(200,50%,50%) ; border-radius: 4px ;margin-left: 5px ; cursor: pointer ; width: 15px"; + shape.classList.add("fas"); + shape.classList.add("fa-circle"); + shape.title = _this.app.translator.get("Shape"); + tool.shape = "round"; + shape.addEventListener("click", function() { + if (tool.shape === "round") { + tool.shape = "square"; + shape.classList.remove("fa-circle"); + shape.classList.add("fa-square-full"); + } else { + tool.shape = "round"; + shape.classList.add("fa-circle"); + shape.classList.remove("fa-square-full"); + } + return _this.spriteview.showBrushSize(); + }); + div.appendChild(shape); + return div.appendChild(document.createElement("br")); }); - div.appendChild(shape); - return div.appendChild(document.createElement("br")); - })(p, key); + })(this)(p, key); } else if (p.type === "tool") { toolbox = document.createElement("div"); toolbox.classList.add("toolbox"); div.appendChild(toolbox); ref1 = p.set; + fn = (function(_this) { + return function(p, k) { + return button.addEventListener("click", function() { + var i, len1, o, ref2, results; + p.value = k; + ref2 = p.set; + results = []; + for (i = o = 0, len1 = ref2.length; o < len1; i = ++o) { + t = ref2[i]; + if (i === k) { + results.push(t.button.classList.add("selected")); + } else { + results.push(t.button.classList.remove("selected")); + } + } + return results; + }); + }; + })(this); for (k = l = 0, len = ref1.length; l < len; k = ++l) { t = ref1[k]; button = document.createElement("div"); @@ -242,7 +319,7 @@ this.SpriteEditor = class SpriteEditor extends Manager { button.classList.add("selected"); } button.title = t.name; - button.id = `spritetoolbutton-${t.icon}`; + button.id = "spritetoolbutton-" + t.icon; i = document.createElement("i"); i.classList.add("fa"); i.classList.add(t.icon); @@ -251,43 +328,27 @@ this.SpriteEditor = class SpriteEditor extends Manager { button.appendChild(document.createTextNode(t.name)); toolbox.appendChild(button); t.button = button; - ((p, k) => { - return button.addEventListener("click", () => { - var len1, o, ref2, results; - p.value = k; - ref2 = p.set; - results = []; - for (i = o = 0, len1 = ref2.length; o < len1; i = ++o) { - t = ref2[i]; - if (i === k) { - results.push(t.button.classList.add("selected")); - } else { - results.push(t.button.classList.remove("selected")); - } - } - return results; - }); - })(p, k); + fn(p, k); } } } - div.id = `spritetooloptions-${tool.icon}`; + div.id = "spritetooloptions-" + tool.icon; return parent.appendChild(div); - } + }; - setSelectedTool(id) { + SpriteEditor.prototype.setSelectedTool = function(id) { var e, l, len, ref, tool; ref = DrawTool.tools; for (l = 0, len = ref.length; l < len; l++) { tool = ref[l]; - e = document.getElementById(`spritetoolbutton-${tool.icon}`); + e = document.getElementById("spritetoolbutton-" + tool.icon); if (tool.icon === id) { this.tool = tool; e.classList.add("selected"); } else { e.classList.remove("selected"); } - e = document.getElementById(`spritetooloptions-${tool.icon}`); + e = document.getElementById("spritetooloptions-" + tool.icon); if (tool.icon === id) { e.style.display = "block"; } else { @@ -297,9 +358,9 @@ this.SpriteEditor = class SpriteEditor extends Manager { document.getElementById("colorpicker-group").style.display = this.tool.parameters["Color"] != null ? "block" : "none"; this.spriteview.update(); return this.updateSelectionHints(); - } + }; - toggleTile() { + SpriteEditor.prototype.toggleTile = function() { this.spriteview.tile = !this.spriteview.tile; this.spriteview.update(); if (this.spriteview.tile) { @@ -307,9 +368,9 @@ this.SpriteEditor = class SpriteEditor extends Manager { } else { return document.getElementById("sprite-helper-tile").classList.remove("selected"); } - } + }; - toggleVSymmetry() { + SpriteEditor.prototype.toggleVSymmetry = function() { this.spriteview.vsymmetry = !this.spriteview.vsymmetry; this.spriteview.update(); if (this.spriteview.vsymmetry) { @@ -317,9 +378,9 @@ this.SpriteEditor = class SpriteEditor extends Manager { } else { return document.getElementById("sprite-helper-vsymmetry").classList.remove("selected"); } - } + }; - toggleHSymmetry() { + SpriteEditor.prototype.toggleHSymmetry = function() { this.spriteview.hsymmetry = !this.spriteview.hsymmetry; this.spriteview.update(); if (this.spriteview.hsymmetry) { @@ -327,29 +388,30 @@ this.SpriteEditor = class SpriteEditor extends Manager { } else { return document.getElementById("sprite-helper-hsymmetry").classList.remove("selected"); } - } + }; - spriteChanged() { + SpriteEditor.prototype.spriteChanged = function() { var s; if (this.ignore_changes) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); this.save_time = Date.now(); s = this.app.project.getSprite(this.selected_sprite); if (s != null) { s.updated(this.spriteview.sprite.saveData()); } - // s.loaded() # triggers update of all maps this.app.project.addPendingChange(this); this.animation_panel.frameUpdated(); this.auto_palette.update(); this.app.project.notifyListeners(s); return this.app.runwindow.updateSprite(this.selected_sprite); - } + }; - //@updateLocalSprites() - checkSave(immediate = false, callback) { + SpriteEditor.prototype.checkSave = function(immediate, callback) { + if (immediate == null) { + immediate = false; + } if (this.save_time > 0 && (immediate || Date.now() > this.save_time + this.save_delay)) { this.saveSprite(callback); return this.save_time = 0; @@ -358,21 +420,21 @@ this.SpriteEditor = class SpriteEditor extends Manager { return callback(); } } - } + }; - forceSave(callback) { + SpriteEditor.prototype.forceSave = function(callback) { return this.checkSave(true, callback); - } + }; - projectOpened() { - super.projectOpened(); + SpriteEditor.prototype.projectOpened = function() { + SpriteEditor.__super__.projectOpened.call(this); this.app.project.addListener(this); return this.setSelectedSprite(null); - } + }; - projectUpdate(change) { + SpriteEditor.prototype.projectUpdate = function(change) { var c, name, sprite; - super.projectUpdate(change); + SpriteEditor.__super__.projectUpdate.call(this, change); switch (change) { case "locks": this.updateCurrentFileLock(); @@ -380,30 +442,30 @@ this.SpriteEditor = class SpriteEditor extends Manager { } if (change instanceof ProjectSprite) { name = change.name; - c = document.querySelector(`#sprite-image-${name}`); + c = document.querySelector("#sprite-image-" + name); sprite = change; if ((c != null) && (c.updateSprite != null)) { return c.updateSprite(); } } - } + }; - updateCurrentFileLock() { + SpriteEditor.prototype.updateCurrentFileLock = function() { var lock, user; if (this.selected_sprite != null) { - this.spriteview.editable = !this.app.project.isLocked(`sprites/${this.selected_sprite}.png`); + this.spriteview.editable = !this.app.project.isLocked("sprites/" + this.selected_sprite + ".png"); } lock = document.getElementById("sprite-editor-locked"); - if ((this.selected_sprite != null) && this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { - user = this.app.project.isLocked(`sprites/${this.selected_sprite}.png`).user; - lock.style = `display: block; background: ${this.app.appui.createFriendColor(user)}`; - return lock.innerHTML = ` Locked by ${user}`; + if ((this.selected_sprite != null) && this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { + user = this.app.project.isLocked("sprites/" + this.selected_sprite + ".png").user; + lock.style = "display: block; background: " + (this.app.appui.createFriendColor(user)); + return lock.innerHTML = " Locked by " + user; } else { return lock.style = "display: none"; } - } + }; - saveSprite(callback) { + SpriteEditor.prototype.saveSprite = function(callback) { var data, pixels, saved, sprite; if ((this.selected_sprite == null) || !this.spriteview.sprite) { return; @@ -416,73 +478,87 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.app.client.sendRequest({ name: "write_project_file", project: this.app.project.id, - file: `sprites/${this.selected_sprite}.png`, + file: "sprites/" + this.selected_sprite + ".png", pixels: pixels, properties: { frames: this.spriteview.sprite.frames.length, fps: this.spriteview.sprite.fps }, content: data - }, (msg) => { - saved = true; - if (this.save_time === 0) { - this.app.project.removePendingChange(this); - } - sprite.size = msg.size; - if (callback != null) { - return callback(); - } - }); - return setTimeout((() => { - if (!saved) { - this.save_time = Date.now(); - return console.info("retrying sprite save..."); - } - }), 10000); - } - - createAsset(folder, name = "sprite", content = "") { - return this.checkSave(true, () => { - if (folder != null) { - name = folder.getFullDashPath() + `-${name}`; - folder.setOpen(true); - } - return this.createSprite(name, null); - }); - } - - createSprite(name, img, callback) { - return this.checkSave(true, () => { - var height, sprite, width; - if (img != null) { - width = img.width; - height = img.height; - } else if (this.spriteview.selection != null) { - width = Math.max(8, this.spriteview.selection.w); - height = Math.max(8, this.spriteview.selection.h); - } else { - width = Math.max(8, this.spriteview.sprite.width); - height = Math.max(8, this.spriteview.sprite.height); - } - sprite = this.app.project.createSprite(width, height, name); - this.spriteview.setSprite(sprite); - this.animation_panel.spriteChanged(); - if (img != null) { - this.spriteview.getFrame().getContext().drawImage(img, 0, 0); - } - this.spriteview.update(); - this.setSelectedItem(sprite.name); - this.spriteview.editable = true; - return this.saveSprite(() => { - this.rebuildList(); + }, (function(_this) { + return function(msg) { + saved = true; + if (_this.save_time === 0) { + _this.app.project.removePendingChange(_this); + } + sprite.size = msg.size; if (callback != null) { return callback(); } - }); - }); - } + }; + })(this)); + return setTimeout(((function(_this) { + return function() { + if (!saved) { + _this.save_time = Date.now(); + return console.info("retrying sprite save..."); + } + }; + })(this)), 10000); + }; + + SpriteEditor.prototype.createAsset = function(folder, name, content) { + if (name == null) { + name = "sprite"; + } + if (content == null) { + content = ""; + } + return this.checkSave(true, (function(_this) { + return function() { + if (folder != null) { + name = folder.getFullDashPath() + ("-" + name); + folder.setOpen(true); + } + return _this.createSprite(name, null); + }; + })(this)); + }; + + SpriteEditor.prototype.createSprite = function(name, img, callback) { + return this.checkSave(true, (function(_this) { + return function() { + var height, sprite, width; + if (img != null) { + width = img.width; + height = img.height; + } else if (_this.spriteview.selection != null) { + width = Math.max(8, _this.spriteview.selection.w); + height = Math.max(8, _this.spriteview.selection.h); + } else { + width = Math.max(8, _this.spriteview.sprite.width); + height = Math.max(8, _this.spriteview.sprite.height); + } + sprite = _this.app.project.createSprite(width, height, name); + _this.spriteview.setSprite(sprite); + _this.animation_panel.spriteChanged(); + if (img != null) { + _this.spriteview.getFrame().getContext().drawImage(img, 0, 0); + } + _this.spriteview.update(); + _this.setSelectedItem(sprite.name); + _this.spriteview.editable = true; + return _this.saveSprite(function() { + _this.rebuildList(); + if (callback != null) { + return callback(); + } + }); + }; + })(this)); + }; - setSelectedItem(name) { + SpriteEditor.prototype.setSelectedItem = function(name) { var sprite; this.checkSave(true); sprite = this.app.project.getSprite(name); @@ -493,10 +569,10 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.spriteview.update(); this.spriteview.editable = true; this.setSelectedSprite(name); - return super.setSelectedItem(name); - } + return SpriteEditor.__super__.setSelectedItem.call(this, name); + }; - setSelectedSprite(sprite) { + SpriteEditor.prototype.setSelectedSprite = function(sprite) { var e; this.selected_sprite = sprite; this.animation_panel.spriteChanged(); @@ -526,36 +602,38 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.auto_palette.update(); this.updateCodeTip(); return this.setCoordinates(-1, -1); - } + }; - setSprite(data) { + SpriteEditor.prototype.setSprite = function(data) { var img; data = "data:image/png;base64," + data; this.ignore_changes = true; img = new Image; img.src = data; img.crossOrigin = "Anonymous"; - return img.onload = () => { - this.spriteview.sprite.load(img); - this.spriteview.windowResized(); - this.spriteview.update(); - this.spriteview.editable = true; - this.ignore_changes = false; - this.spriteview.windowResized(); - document.getElementById("sprite-width").value = this.spriteview.sprite.width; - document.getElementById("sprite-height").value = this.spriteview.sprite.height; - return this.sprite_size_validator.update(); - }; - } + return img.onload = (function(_this) { + return function() { + _this.spriteview.sprite.load(img); + _this.spriteview.windowResized(); + _this.spriteview.update(); + _this.spriteview.editable = true; + _this.ignore_changes = false; + _this.spriteview.windowResized(); + document.getElementById("sprite-width").value = _this.spriteview.sprite.width; + document.getElementById("sprite-height").value = _this.spriteview.sprite.height; + return _this.sprite_size_validator.update(); + }; + })(this); + }; - setColor(color1) { + SpriteEditor.prototype.setColor = function(color1) { this.color = color1; this.spriteview.setColor(this.color); this.auto_palette.colorPicked(this.color); return document.getElementById("colortext").value = this.color; - } + }; - spriteDimensionChanged(dim) { + SpriteEditor.prototype.spriteDimensionChanged = function(dim) { if (this.selected_sprite === "icon") { if (dim === "width") { return document.getElementById("sprite-height").value = document.getElementById("sprite-width").value; @@ -563,31 +641,33 @@ this.SpriteEditor = class SpriteEditor extends Manager { return document.getElementById("sprite-width").value = document.getElementById("sprite-height").value; } } - } + }; - colortextChanged() { + SpriteEditor.prototype.colortextChanged = function() { return this.colorpicker.colorPicked(document.getElementById("colortext").value); - } + }; - colortextCopy() { + SpriteEditor.prototype.colortextCopy = function() { var colortext, copy; copy = document.getElementById("colortext-copy"); colortext = document.getElementById("colortext"); copy.classList.remove("fa-copy"); copy.classList.add("fa-check"); - setTimeout((() => { - copy.classList.remove("fa-check"); - return copy.classList.add("fa-copy"); - }), 3000); - return navigator.clipboard.writeText(`"${colortext.value}"`); - } + setTimeout(((function(_this) { + return function() { + copy.classList.remove("fa-check"); + return copy.classList.add("fa-copy"); + }; + })(this)), 3000); + return navigator.clipboard.writeText("\"" + colortext.value + "\""); + }; - saveDimensionChange(value) { + SpriteEditor.prototype.saveDimensionChange = function(value) { var err, h, w; - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); w = value[0]; h = value[1]; try { @@ -617,18 +697,20 @@ this.SpriteEditor = class SpriteEditor extends Manager { document.getElementById("sprite-height").value = this.spriteview.sprite.height; return this.sprite_size_validator.update(); } - } + }; - undo() { + SpriteEditor.prototype.undo = function() { var s; - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); if (this.spriteview.sprite && (this.spriteview.sprite.undo != null)) { - s = this.spriteview.sprite.undo.undo(() => { - return this.spriteview.sprite.clone(); - }); + s = this.spriteview.sprite.undo.undo((function(_this) { + return function() { + return _this.spriteview.sprite.clone(); + }; + })(this)); this.spriteview.selection = null; if (s != null) { this.spriteview.sprite.copyFrom(s); @@ -641,14 +723,14 @@ this.SpriteEditor = class SpriteEditor extends Manager { return this.animation_panel.updateFrames(); } } - } + }; - redo() { + SpriteEditor.prototype.redo = function() { var s; - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); if (this.spriteview.sprite && (this.spriteview.sprite.undo != null)) { s = this.spriteview.sprite.undo.redo(); this.spriteview.selection = null; @@ -663,9 +745,9 @@ this.SpriteEditor = class SpriteEditor extends Manager { return this.animation_panel.updateFrames(); } } - } + }; - copy() { + SpriteEditor.prototype.copy = function() { if (this.tool.selectiontool && (this.spriteview.selection != null)) { this.clipboard = new Sprite(this.spriteview.selection.w, this.spriteview.selection.h); this.clipboard.frames[0].getContext().drawImage(this.spriteview.getFrame().canvas, -this.spriteview.selection.x, -this.spriteview.selection.y); @@ -673,14 +755,14 @@ this.SpriteEditor = class SpriteEditor extends Manager { } else { return this.clipboard = this.spriteview.sprite.clone(); } - } + }; - cut() { + SpriteEditor.prototype.cut = function() { var sel; - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); if (this.spriteview.sprite.undo == null) { this.spriteview.sprite.undo = new Undo(); } @@ -700,14 +782,14 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.spriteview.sprite.undo.pushState(this.spriteview.sprite.clone()); this.currentSpriteUpdated(); return this.spriteChanged(); - } + }; - paste() { + SpriteEditor.prototype.paste = function() { var x, y; - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); if (this.clipboard != null) { if (this.spriteview.sprite.undo == null) { this.spriteview.sprite.undo = new Undo(); @@ -741,31 +823,29 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.currentSpriteUpdated(); return this.spriteChanged(); } - } + }; - currentSpriteUpdated() { + SpriteEditor.prototype.currentSpriteUpdated = function() { this.spriteview.update(); document.getElementById("sprite-width").value = this.spriteview.sprite.width; document.getElementById("sprite-height").value = this.spriteview.sprite.height; this.animation_panel.updateFrames(); this.sprite_size_validator.update(); return this.spriteview.windowResized(); - } + }; - setColorPicker(picker) { + SpriteEditor.prototype.setColorPicker = function(picker) { this.spriteview.colorpicker = picker; if (picker) { - //@spriteview.canvas.classList.add "colorpicker" this.spriteview.canvas.style.cursor = "url( '/img/eyedropper.svg' ) 0 24, pointer"; return document.getElementById("eyedropper").classList.add("selected"); } else { - //@spriteview.canvas.classList.remove "colorpicker" this.spriteview.canvas.style.cursor = "crosshair"; return document.getElementById("eyedropper").classList.remove("selected"); } - } + }; - updateSelectionHints() { + SpriteEditor.prototype.updateSelectionHints = function() { var h, w; if ((this.spriteview.selection != null) && this.tool.selectiontool) { document.getElementById("selection-group").style.display = "block"; @@ -779,9 +859,9 @@ this.SpriteEditor = class SpriteEditor extends Manager { } else { return document.getElementById("selection-group").style.display = "none"; } - } + }; - stripToAnimation() { + SpriteEditor.prototype.stripToAnimation = function() { var h, i, index, j, l, m, n, o, ref, ref1, sprite, w; w = this.spriteview.selection.w; h = this.spriteview.selection.h; @@ -809,103 +889,107 @@ this.SpriteEditor = class SpriteEditor extends Manager { this.spriteChanged(); return this.animation_panel.spriteChanged(); } - } + }; - flipHSprite() { - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + SpriteEditor.prototype.flipHSprite = function() { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); return this.spriteview.flipSprite("horizontal"); - } + }; - flipVSprite() { - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + SpriteEditor.prototype.flipVSprite = function() { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); return this.spriteview.flipSprite("vertical"); - } + }; - rotateSprite(direction) { - if (this.app.project.isLocked(`sprites/${this.selected_sprite}.png`)) { + SpriteEditor.prototype.rotateSprite = function(direction) { + if (this.app.project.isLocked("sprites/" + this.selected_sprite + ".png")) { return; } - this.app.project.lockFile(`sprites/${this.selected_sprite}.png`); + this.app.project.lockFile("sprites/" + this.selected_sprite + ".png"); return this.spriteview.rotateSprite(direction); - } + }; - fileDropped(file, folder) { + SpriteEditor.prototype.fileDropped = function(file, folder) { var reader; - console.info(`processing ${file.name}`); + console.info("processing " + file.name); console.info("folder: " + folder); reader = new FileReader(); - reader.addEventListener("load", () => { - var img; - console.info("file read, size = " + reader.result.byteLength); - if (reader.result.byteLength > 5000000) { - this.app.appui.showNotification(this.app.translator.get("Image file is too heavy")); - return; - } - img = new Image; - img.src = reader.result; - return img.onload = () => { - var name, sprite; - if (img.complete && img.width > 0 && img.height > 0 && img.width <= 2048 && img.height <= 2048) { - name = file.name.split(".")[0]; - name = this.findNewFilename(name, "getSprite", folder); - if (folder != null) { - name = folder.getFullDashPath() + "-" + name; - } - if (folder != null) { - folder.setOpen(true); - } - sprite = this.app.project.createSprite(name, img); - this.setSelectedItem(name); - return this.app.client.sendRequest({ - name: "write_project_file", - project: this.app.project.id, - file: `sprites/${name}.png`, - properties: {}, - content: reader.result.split(",")[1] - }, (msg) => { - console.info(msg); - this.app.project.removePendingChange(this); - this.app.project.updateSpriteList(); - return this.checkNameFieldActivation(); - }); - } else { - return this.app.appui.showNotification(this.app.translator.get("Image size is too large")); + reader.addEventListener("load", (function(_this) { + return function() { + var img; + console.info("file read, size = " + reader.result.byteLength); + if (reader.result.byteLength > 5000000) { + _this.app.appui.showNotification(_this.app.translator.get("Image file is too heavy")); + return; } + img = new Image; + img.src = reader.result; + return img.onload = function() { + var name, sprite; + if (img.complete && img.width > 0 && img.height > 0 && img.width <= 2048 && img.height <= 2048) { + name = file.name.split(".")[0]; + name = _this.findNewFilename(name, "getSprite", folder); + if (folder != null) { + name = folder.getFullDashPath() + "-" + name; + } + if (folder != null) { + folder.setOpen(true); + } + sprite = _this.app.project.createSprite(name, img); + _this.setSelectedItem(name); + return _this.app.client.sendRequest({ + name: "write_project_file", + project: _this.app.project.id, + file: "sprites/" + name + ".png", + properties: {}, + content: reader.result.split(",")[1] + }, function(msg) { + console.info(msg); + _this.app.project.removePendingChange(_this); + _this.app.project.updateSpriteList(); + return _this.checkNameFieldActivation(); + }); + } else { + return _this.app.appui.showNotification(_this.app.translator.get("Image size is too large")); + } + }; }; - }); + })(this)); return reader.readAsDataURL(file); - } + }; - updateCodeTip() { + SpriteEditor.prototype.updateCodeTip = function() { var code, sprite; if ((this.selected_sprite != null) && (this.app.project.getSprite(this.selected_sprite) != null)) { sprite = this.app.project.getSprite(this.selected_sprite); - code = `screen.drawSprite( "${this.selected_sprite.replace(/-/g, "/")}", x, y, ${sprite.width}, ${sprite.height} )`; + code = "screen.drawSprite( \"" + (this.selected_sprite.replace(/-/g, "/")) + "\", x, y, " + sprite.width + ", " + sprite.height + " )"; } else { code = ""; } return this.code_tip.set(code); - } + }; - setCoordinates(x, y) { + SpriteEditor.prototype.setCoordinates = function(x, y) { var e; e = document.getElementById("sprite-coordinates"); if (x < 0 || y < 0) { return e.innerText = ""; } else { - return e.innerText = `${x} , ${y}`; + return e.innerText = x + " , " + y; } - } + }; - renameItem(item, name) { - this.app.project.changeSpriteName(item.name, name); // needed to trigger updating of maps - return super.renameItem(item, name); - } + SpriteEditor.prototype.renameItem = function(item, name) { + this.app.project.changeSpriteName(item.name, name); + return SpriteEditor.__super__.renameItem.call(this, item, name); + }; + + return SpriteEditor; -}; +})(Manager); diff --git a/static/js/spriteeditor/spriteframe.js b/static/js/spriteeditor/spriteframe.js index c69b21d0..f837344b 100644 --- a/static/js/spriteeditor/spriteframe.js +++ b/static/js/spriteeditor/spriteframe.js @@ -1,5 +1,5 @@ -this.SpriteFrame = class SpriteFrame { - constructor(sprite, width, height) { +this.SpriteFrame = (function() { + function SpriteFrame(sprite, width, height) { this.sprite = sprite; this.width = width; this.height = height; @@ -9,21 +9,21 @@ this.SpriteFrame = class SpriteFrame { this.canvas.height = this.height; } - clone() { + SpriteFrame.prototype.clone = function() { var sf; sf = new SpriteFrame(this.sprite, this.width, this.height); sf.getContext().drawImage(this.canvas, 0, 0); return sf; - } + }; - getContext() { + SpriteFrame.prototype.getContext = function() { if (this.canvas == null) { return null; } return this.context = this.getCanvas().getContext("2d"); - } + }; - getCanvas() { + SpriteFrame.prototype.getCanvas = function() { var c; if (this.canvas == null) { return null; @@ -36,26 +36,32 @@ this.SpriteFrame = class SpriteFrame { this.canvas = c; } return this.canvas; - } + }; - setPixel(x, y, color, alpha = 1) { + SpriteFrame.prototype.setPixel = function(x, y, color, alpha) { var c; + if (alpha == null) { + alpha = 1; + } c = this.getContext(); c.globalAlpha = alpha; c.fillStyle = color; c.fillRect(x, y, 1, 1); return c.globalAlpha = 1; - } + }; - erasePixel(x, y, alpha = 1) { + SpriteFrame.prototype.erasePixel = function(x, y, alpha) { var c, data; + if (alpha == null) { + alpha = 1; + } c = this.getContext(); data = c.getImageData(x, y, 1, 1); data.data[3] *= 1 - alpha; return c.putImageData(data, x, y); - } + }; - getRGB(x, y) { + SpriteFrame.prototype.getRGB = function(x, y) { var c, data; if (x < 0 || x >= this.width || y < 0 || y >= this.height) { return [0, 0, 0]; @@ -63,13 +69,13 @@ this.SpriteFrame = class SpriteFrame { c = this.getContext(); data = c.getImageData(x, y, 1, 1); return data.data; - } + }; - clear() { + SpriteFrame.prototype.clear = function() { return this.getContext().clearRect(0, 0, this.canvas.width, this.canvas.height); - } + }; - resize(w, h) { + SpriteFrame.prototype.resize = function(w, h) { var c; if (w === this.width && h === this.height) { return; @@ -79,18 +85,20 @@ this.SpriteFrame = class SpriteFrame { this.context = null; this.width = w; return this.height = h; - } + }; - load(img) { + SpriteFrame.prototype.load = function(img) { this.resize(img.width, img.height); this.clear(); return this.canvas.getContext("2d").drawImage(img, 0, 0); - } + }; - copyFrom(frame) { + SpriteFrame.prototype.copyFrom = function(frame) { this.resize(frame.width, frame.height); this.clear(); return this.getContext().drawImage(frame.canvas, 0, 0); - } + }; + + return SpriteFrame; -}; +})(); diff --git a/static/js/spriteeditor/spriteview.js b/static/js/spriteeditor/spriteview.js index 5932f6eb..8c7fca19 100644 --- a/static/js/spriteeditor/spriteview.js +++ b/static/js/spriteeditor/spriteview.js @@ -1,48 +1,68 @@ -this.SpriteView = class SpriteView { - constructor(editor) { +this.SpriteView = (function() { + function SpriteView(editor) { this.editor = editor; this.canvas = document.querySelector("#spriteeditor canvas"); this.canvas.width = 400; this.canvas.height = 400; this.sprite = new Sprite(32, 32); - this.canvas.addEventListener("touchstart", (event) => { - if ((event.touches != null) && (event.touches[0] != null)) { - event.preventDefault(); // prevents a mousedown event from being triggered - event.touches[0].stopPropagation = function() { - return event.stopPropagation(); - }; - return this.mouseDown(event.touches[0]); - } - }); - document.addEventListener("touchmove", (event) => { - if ((event.touches != null) && (event.touches[0] != null)) { - return this.mouseMove(event.touches[0]); - } - }); - document.addEventListener("touchend", (event) => { - return this.mouseUp(); - }); - this.canvas.addEventListener("touchcancel", (event) => { - return this.mouseOut(); - }); - this.canvas.addEventListener("mousedown", (event) => { - return this.mouseDown(event); - }); - document.addEventListener("mousemove", (event) => { - return this.mouseMove(event); - }); - this.canvas.addEventListener("mouseout", (event) => { - return this.mouseOut(event); - }); - document.addEventListener("mouseup", (event) => { - return this.mouseUp(event); - }); - this.canvas.addEventListener("contextmenu", (event) => { - return event.preventDefault(); - }); - this.canvas.addEventListener("mouseenter", (event) => { - return this.mouseEnter(event); - }); + this.canvas.addEventListener("touchstart", (function(_this) { + return function(event) { + if ((event.touches != null) && (event.touches[0] != null)) { + event.preventDefault(); + event.touches[0].stopPropagation = function() { + return event.stopPropagation(); + }; + return _this.mouseDown(event.touches[0]); + } + }; + })(this)); + document.addEventListener("touchmove", (function(_this) { + return function(event) { + if ((event.touches != null) && (event.touches[0] != null)) { + return _this.mouseMove(event.touches[0]); + } + }; + })(this)); + document.addEventListener("touchend", (function(_this) { + return function(event) { + return _this.mouseUp(); + }; + })(this)); + this.canvas.addEventListener("touchcancel", (function(_this) { + return function(event) { + return _this.mouseOut(); + }; + })(this)); + this.canvas.addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.mouseDown(event); + }; + })(this)); + document.addEventListener("mousemove", (function(_this) { + return function(event) { + return _this.mouseMove(event); + }; + })(this)); + this.canvas.addEventListener("mouseout", (function(_this) { + return function(event) { + return _this.mouseOut(event); + }; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function(event) { + return _this.mouseUp(event); + }; + })(this)); + this.canvas.addEventListener("contextmenu", (function(_this) { + return function(event) { + return event.preventDefault(); + }; + })(this)); + this.canvas.addEventListener("mouseenter", (function(_this) { + return function(event) { + return _this.mouseEnter(event); + }; + })(this)); this.brush_opacity = 1; this.brush_type = "paint"; this.brush_size = 1; @@ -50,58 +70,74 @@ this.SpriteView = class SpriteView { this.mouse_x = 0; this.mouse_y = 0; this.pixels_drawn = 0; - window.addEventListener("resize", () => { - return this.windowResized(); - }); + window.addEventListener("resize", (function(_this) { + return function() { + return _this.windowResized(); + }; + })(this)); this.editable = false; this.tile = false; this.vsymmetry = false; this.hsymmetry = false; this.zoom = 1; - document.getElementById("spriteeditor").addEventListener("mousewheel", ((e) => { - return this.mouseWheel(e); - }), false); - document.getElementById("spriteeditor").addEventListener("DOMMouseScroll", ((e) => { - return this.mouseWheel(e); - }), false); - document.getElementById("spriteeditor").addEventListener("mousedown", () => { - if (this.selection != null) { - this.selection = null; - return this.update(); - } - }); - document.getElementById("spriteeditor").addEventListener("keydown", (e) => { - if (e.keyCode === 32) { - this.space_pressed = true; - this.canvas.style.cursor = "grab"; - e.preventDefault(); - return document.getElementById("sprite-grab-info").classList.add("active"); - } else if (e.keyCode === 18) { // Alt - return document.getElementById("selection-hint-clone").classList.add("active"); - } else if (e.keyCode === 16) { // Shift - return document.getElementById("selection-hint-move").classList.add("active"); - } - }); - document.addEventListener("keyup", (e) => { - if (e.keyCode === 32) { - this.space_pressed = false; - this.canvas.style.cursor = "crosshair"; - return document.getElementById("sprite-grab-info").classList.remove("active"); - } else if (e.keyCode === 18) { // Alt - return document.getElementById("selection-hint-clone").classList.remove("active"); - } else if (e.keyCode === 16) { // Shift - return document.getElementById("selection-hint-move").classList.remove("active"); - } - }); - document.getElementById("sprite-zoom-plus").addEventListener("click", () => { - return this.scaleZoom(1.1); - }); - document.getElementById("sprite-zoom-minus").addEventListener("click", () => { - return this.scaleZoom(1 / 1.100001); - }); + document.getElementById("spriteeditor").addEventListener("mousewheel", ((function(_this) { + return function(e) { + return _this.mouseWheel(e); + }; + })(this)), false); + document.getElementById("spriteeditor").addEventListener("DOMMouseScroll", ((function(_this) { + return function(e) { + return _this.mouseWheel(e); + }; + })(this)), false); + document.getElementById("spriteeditor").addEventListener("mousedown", (function(_this) { + return function() { + if (_this.selection != null) { + _this.selection = null; + return _this.update(); + } + }; + })(this)); + document.getElementById("spriteeditor").addEventListener("keydown", (function(_this) { + return function(e) { + if (e.keyCode === 32) { + _this.space_pressed = true; + _this.canvas.style.cursor = "grab"; + e.preventDefault(); + return document.getElementById("sprite-grab-info").classList.add("active"); + } else if (e.keyCode === 18) { + return document.getElementById("selection-hint-clone").classList.add("active"); + } else if (e.keyCode === 16) { + return document.getElementById("selection-hint-move").classList.add("active"); + } + }; + })(this)); + document.addEventListener("keyup", (function(_this) { + return function(e) { + if (e.keyCode === 32) { + _this.space_pressed = false; + _this.canvas.style.cursor = "crosshair"; + return document.getElementById("sprite-grab-info").classList.remove("active"); + } else if (e.keyCode === 18) { + return document.getElementById("selection-hint-clone").classList.remove("active"); + } else if (e.keyCode === 16) { + return document.getElementById("selection-hint-move").classList.remove("active"); + } + }; + })(this)); + document.getElementById("sprite-zoom-plus").addEventListener("click", (function(_this) { + return function() { + return _this.scaleZoom(1.1); + }; + })(this)); + document.getElementById("sprite-zoom-minus").addEventListener("click", (function(_this) { + return function() { + return _this.scaleZoom(1 / 1.100001); + }; + })(this)); } - setSprite(sprite) { + SpriteView.prototype.setSprite = function(sprite) { if (sprite !== this.sprite) { if (this.sprite != null) { this.saveZoom(); @@ -116,20 +152,20 @@ this.SpriteView = class SpriteView { this.selection = this.sprite.selection || null; return this.floating_selection = null; } - } + }; - setCurrentFrame(index) { + SpriteView.prototype.setCurrentFrame = function(index) { if (index !== this.sprite.current_frame) { this.sprite.setCurrentFrame(index); return this.selection = null; } - } + }; - getFrame() { + SpriteView.prototype.getFrame = function() { return this.sprite.frames[this.sprite.current_frame]; - } + }; - mouseWheel(e) { + SpriteView.prototype.mouseWheel = function(e) { e.preventDefault(); if (this.next_wheel_action == null) { this.next_wheel_action = Date.now(); @@ -143,9 +179,9 @@ this.SpriteView = class SpriteView { } else { return this.scaleZoom(1.1, e); } - } + }; - scaleZoom(scale, e) { + SpriteView.prototype.scaleZoom = function(scale, e) { var b, max_zoom, scroll_x, scroll_y, view, x, y; view = document.getElementById("spriteeditor").getBoundingClientRect(); max_zoom = 4096 / Math.max(view.width, view.height); @@ -170,9 +206,9 @@ this.SpriteView = class SpriteView { } else { return document.getElementById("sprite-grab-info").style.display = "none"; } - } + }; - saveZoom() { + SpriteView.prototype.saveZoom = function() { var view; if (this.sprite != null) { view = document.getElementById("spriteeditor"); @@ -182,18 +218,18 @@ this.SpriteView = class SpriteView { top: view.scrollTop }; } - } + }; - restoreZoom() { + SpriteView.prototype.restoreZoom = function() { var view; if (this.sprite.zoom != null) { view = document.getElementById("spriteeditor"); this.scaleZoom(this.sprite.zoom.zoom / this.zoom); return view.scrollTo(this.sprite.zoom.left, this.sprite.zoom.top); } - } + }; - addPattern() { + SpriteView.prototype.addPattern = function() { var c, context, data, i, k, l, line, ref, ref1, value; if (this.pattern != null) { return; @@ -214,12 +250,12 @@ this.SpriteView = class SpriteView { context.putImageData(data, 0, line); } this.pattern = c.toDataURL(); - document.querySelector(".spriteeditor canvas").style["background-image"] = `url(${this.pattern})`; + document.querySelector(".spriteeditor canvas").style["background-image"] = "url(" + this.pattern + ")"; document.querySelector(".spriteeditor canvas").style["background-repeat"] = "repeat"; return this.updateBackgroundColor(); - } + }; - updateBackgroundColor() { + SpriteView.prototype.updateBackgroundColor = function() { var c; if (this.editor.background_color_picker != null) { c = this.editor.background_color_picker.color; @@ -227,13 +263,13 @@ this.SpriteView = class SpriteView { } else { return document.querySelector(".spriteeditor canvas").style["background-color"] = "#000"; } - } + }; - setColor(color) { + SpriteView.prototype.setColor = function(color) { this.color = color; - } + }; - windowResized() { + SpriteView.prototype.windowResized = function() { var c, h, ratio, w; c = this.canvas.parentElement; if (c == null) { @@ -254,14 +290,14 @@ this.SpriteView = class SpriteView { } h = Math.max(40, (c.clientHeight - h) / 2); return this.canvas.style["margin-top"] = h + "px"; - } + }; - showBrushSize() { + SpriteView.prototype.showBrushSize = function() { this.show_brush_size = Date.now() + 2000; return this.update(); - } + }; - drawGrid(ctx) { + SpriteView.prototype.drawGrid = function(ctx) { var context, hblock, hoffset, i, k, l, lw, m, modulo, n, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, wblock, woffset; if ((this.grid_buffer == null) || this.grid_buffer.width !== this.canvas.width || this.grid_buffer.height !== this.canvas.height || this.tile !== this.grid_tile || this.grid_sw !== this.sprite.width || this.grid_sh !== this.sprite.height) { if (this.grid_buffer == null) { @@ -288,7 +324,7 @@ this.SpriteView = class SpriteView { if (wblock < 3) { return; } - for (i = k = 0, ref = this.canvas.width, ref1 = wblock; ref1 !== 0 && (ref1 > 0 ? k <= ref : k >= ref); i = k += ref1) { + for (i = k = 0, ref = this.canvas.width, ref1 = wblock; ref1 > 0 ? k <= ref : k >= ref; i = k += ref1) { lw = Math.round(i / hblock) % modulo === 0 ? 2 : 1; context.lineWidth = lw; context.beginPath(); @@ -296,7 +332,7 @@ this.SpriteView = class SpriteView { context.lineTo(i + .25 * lw + woffset, this.canvas.height); context.stroke(); } - for (i = l = 0, ref2 = this.canvas.height, ref3 = hblock; ref3 !== 0 && (ref3 > 0 ? l <= ref2 : l >= ref2); i = l += ref3) { + for (i = l = 0, ref2 = this.canvas.height, ref3 = hblock; ref3 > 0 ? l <= ref2 : l >= ref2; i = l += ref3) { lw = Math.round(i / hblock) % modulo === 0 ? 2 : 1; context.lineWidth = lw; context.beginPath(); @@ -305,7 +341,7 @@ this.SpriteView = class SpriteView { context.stroke(); } context.strokeStyle = "rgba(255,255,255,.1)"; - for (i = m = 0, ref4 = this.canvas.width, ref5 = wblock; ref5 !== 0 && (ref5 > 0 ? m <= ref4 : m >= ref4); i = m += ref5) { + for (i = m = 0, ref4 = this.canvas.width, ref5 = wblock; ref5 > 0 ? m <= ref4 : m >= ref4; i = m += ref5) { lw = Math.round(i / hblock) % modulo === 0 ? 2 : 1; context.lineWidth = lw; context.beginPath(); @@ -313,7 +349,7 @@ this.SpriteView = class SpriteView { context.lineTo(i - .25 * lw + woffset, this.canvas.height); context.stroke(); } - for (i = n = 0, ref6 = this.canvas.height, ref7 = hblock; ref7 !== 0 && (ref7 > 0 ? n <= ref6 : n >= ref6); i = n += ref7) { + for (i = n = 0, ref6 = this.canvas.height, ref7 = hblock; ref7 > 0 ? n <= ref6 : n >= ref6; i = n += ref7) { lw = Math.round(i / hblock) % modulo === 0 ? 2 : 1; context.lineWidth = lw; context.beginPath(); @@ -323,9 +359,9 @@ this.SpriteView = class SpriteView { } } return ctx.drawImage(this.grid_buffer, 0, 0); - } + }; - update() { + SpriteView.prototype.update = function() { var bs, context, d, f, grd, h, hblock, hoffset, i, j, k, l, m, mx, my, n, w, wblock, woffset; this.brush_size = this.editor.tool.getSize(this.sprite); context = this.canvas.getContext("2d"); @@ -453,21 +489,21 @@ this.SpriteView = class SpriteView { context.strokeRect(this.selection.x * wblock, this.selection.y * hblock, this.selection.w * wblock, this.selection.h * hblock); context.setLineDash([]); if (this.selection.w > 1 || this.selection.h > 1) { - context.font = `${Math.max(12, wblock)}pt Ubuntu Mono`; + context.font = (Math.max(12, wblock)) + "pt Ubuntu Mono"; context.fillStyle = "#FFF"; context.shadowBlur = 2; context.shadowColor = "#000"; context.shadowOpacity = 1; context.textAlign = "center"; context.textBaseline = "middle"; - context.fillText(`${this.selection.w} x ${this.selection.h}`, (this.selection.x + this.selection.w / 2) * wblock, (this.selection.y + this.selection.h / 2) * hblock); + context.fillText(this.selection.w + " x " + this.selection.h, (this.selection.x + this.selection.w / 2) * wblock, (this.selection.y + this.selection.h / 2) * hblock); context.shadowBlur = 0; } return context.restore(); } - } + }; - mouseDown(event) { + SpriteView.prototype.mouseDown = function(event) { var b, bg, c, context, fg, min, x, y; event.stopPropagation(); if (!this.editable || (this.sprite == null)) { @@ -565,13 +601,13 @@ this.SpriteView = class SpriteView { this.update(); this.editor.spriteChanged(); return this.floating_selection = null; - } + }; - mouseEnter(event) { + SpriteView.prototype.mouseEnter = function(event) { return document.getElementById("spriteeditor").focus(); - } + }; - mouseMove(event) { + SpriteView.prototype.mouseMove = function(event) { var b, context, dx, dy, min, view, x, y; if (this.grabbing) { dx = event.clientX - this.grab_x; @@ -678,9 +714,9 @@ this.SpriteView = class SpriteView { } } return false; - } + }; - mouseUp(event) { + SpriteView.prototype.mouseUp = function(event) { if (this.grabbing) { this.grabbing = false; } else if (this.mousepressed && !this.editor.tool.selectiontool) { @@ -699,15 +735,15 @@ this.SpriteView = class SpriteView { } this.mousepressed = false; return this.editor.updateSelectionHints(); - } + }; - mouseOut(event) { + SpriteView.prototype.mouseOut = function(event) { this.mouse_over = false; this.update(); return this.editor.setCoordinates(-1, -1); - } + }; - flipSprite(direction) { + SpriteView.prototype.flipSprite = function(direction) { var bg, context, fg; if (this.editor.tool.selectiontool) { if (this.selection != null) { @@ -754,9 +790,9 @@ this.SpriteView = class SpriteView { return this.editor.spriteChanged(); } } - } + }; - rotateSprite(direction) { + SpriteView.prototype.rotateSprite = function(direction) { var bg, context, cx, cy, fg, nh, nw, nx, ny; if (this.editor.tool.selectiontool) { if (this.selection != null) { @@ -812,6 +848,8 @@ this.SpriteView = class SpriteView { return this.editor.spriteChanged(); } } - } + }; + + return SpriteView; -}; +})(); diff --git a/static/js/terminal/terminal.js b/static/js/terminal/terminal.js index 2532f4c6..b7961c4c 100644 --- a/static/js/terminal/terminal.js +++ b/static/js/terminal/terminal.js @@ -1,12 +1,14 @@ -this.Terminal = class Terminal { - constructor(runwindow, tid = "terminal") { +this.Terminal = (function() { + function Terminal(runwindow, tid) { this.runwindow = runwindow; - this.tid = tid; + this.tid = tid != null ? tid : "terminal"; this.localStorage = localStorage; this.commands = { - clear: () => { - return this.clear(); - } + clear: (function(_this) { + return function() { + return _this.clear(); + }; + })(this) }; this.loadHistory(); this.buffer = []; @@ -14,7 +16,7 @@ this.Terminal = class Terminal { this.error_lines = 0; } - loadHistory() { + Terminal.prototype.loadHistory = function() { var err; this.history = []; try { @@ -24,98 +26,108 @@ this.Terminal = class Terminal { } catch (error) { err = error; } - } + }; - saveHistory() { + Terminal.prototype.saveHistory = function() { return this.localStorage.setItem("console_history", JSON.stringify(this.history)); - } + }; - start() { + Terminal.prototype.start = function() { if (this.started) { return; } this.started = true; - document.getElementById(`${this.tid}`).addEventListener("mousedown", (event) => { - this.pressed = true; - this.moved = false; - return true; - }); - document.getElementById(`${this.tid}`).addEventListener("mousemove", (event) => { - if (this.pressed) { - this.moved = true; - } - return true; - }); - document.getElementById(`${this.tid}`).addEventListener("mouseup", (event) => { - if (!this.moved) { - document.getElementById(`${this.tid}-input`).focus(); - } - this.moved = false; - this.pressed = false; - return true; - }); - document.getElementById(`${this.tid}-input`).addEventListener("paste", (event) => { - var j, len, line, s, text; - text = event.clipboardData.getData("text/plain"); - s = text.split("\n"); - if (s.length > 1) { - event.preventDefault(); - for (j = 0, len = s.length; j < len; j++) { - line = s[j]; - document.getElementById(`${this.tid}-input`).value = ""; - this.validateLine(line); - } - } else { - return false; - } - }); - //document.getElementById("#{@tid}-input").value = s[0] - document.getElementById(`${this.tid}-input`).addEventListener("keydown", (event) => { - var v; - // console.info event.key - if (event.key === "Enter") { - v = document.getElementById(`${this.tid}-input`).value; - document.getElementById(`${this.tid}-input`).value = ""; - this.validateLine(v); - return this.force_scroll = true; - } else if (event.key === "ArrowUp") { - if (this.history_index == null) { - this.history_index = this.history.length - 1; - this.current_input = document.getElementById(`${this.tid}-input`).value; - } else { - this.history_index = Math.max(0, this.history_index - 1); - } - if (this.history_index === this.history.length - 1) { - this.current_input = document.getElementById(`${this.tid}-input`).value; - } - if (this.history_index >= 0 && this.history_index < this.history.length) { - document.getElementById(`${this.tid}-input`).value = this.history[this.history_index]; - return this.setTrailingCaret(); + document.getElementById("" + this.tid).addEventListener("mousedown", (function(_this) { + return function(event) { + _this.pressed = true; + _this.moved = false; + return true; + }; + })(this)); + document.getElementById("" + this.tid).addEventListener("mousemove", (function(_this) { + return function(event) { + if (_this.pressed) { + _this.moved = true; } - } else if (event.key === "ArrowDown") { - if (this.history_index === this.history.length) { - return; + return true; + }; + })(this)); + document.getElementById("" + this.tid).addEventListener("mouseup", (function(_this) { + return function(event) { + if (!_this.moved) { + document.getElementById(_this.tid + "-input").focus(); } - if (this.history_index != null) { - this.history_index = Math.min(this.history.length, this.history_index + 1); + _this.moved = false; + _this.pressed = false; + return true; + }; + })(this)); + document.getElementById(this.tid + "-input").addEventListener("paste", (function(_this) { + return function(event) { + var j, len, line, s, text; + text = event.clipboardData.getData("text/plain"); + s = text.split("\n"); + if (s.length > 1) { + event.preventDefault(); + for (j = 0, len = s.length; j < len; j++) { + line = s[j]; + document.getElementById(_this.tid + "-input").value = ""; + _this.validateLine(line); + } } else { - return; + return false; } - if (this.history_index >= 0 && this.history_index < this.history.length) { - document.getElementById(`${this.tid}-input`).value = this.history[this.history_index]; - return this.setTrailingCaret(); - } else if (this.history_index === this.history.length) { - document.getElementById(`${this.tid}-input`).value = this.current_input; - return this.setTrailingCaret(); + }; + })(this)); + document.getElementById(this.tid + "-input").addEventListener("keydown", (function(_this) { + return function(event) { + var v; + if (event.key === "Enter") { + v = document.getElementById(_this.tid + "-input").value; + document.getElementById(_this.tid + "-input").value = ""; + _this.validateLine(v); + return _this.force_scroll = true; + } else if (event.key === "ArrowUp") { + if (_this.history_index == null) { + _this.history_index = _this.history.length - 1; + _this.current_input = document.getElementById(_this.tid + "-input").value; + } else { + _this.history_index = Math.max(0, _this.history_index - 1); + } + if (_this.history_index === _this.history.length - 1) { + _this.current_input = document.getElementById(_this.tid + "-input").value; + } + if (_this.history_index >= 0 && _this.history_index < _this.history.length) { + document.getElementById(_this.tid + "-input").value = _this.history[_this.history_index]; + return _this.setTrailingCaret(); + } + } else if (event.key === "ArrowDown") { + if (_this.history_index === _this.history.length) { + return; + } + if (_this.history_index != null) { + _this.history_index = Math.min(_this.history.length, _this.history_index + 1); + } else { + return; + } + if (_this.history_index >= 0 && _this.history_index < _this.history.length) { + document.getElementById(_this.tid + "-input").value = _this.history[_this.history_index]; + return _this.setTrailingCaret(); + } else if (_this.history_index === _this.history.length) { + document.getElementById(_this.tid + "-input").value = _this.current_input; + return _this.setTrailingCaret(); + } } - } - }); - return setInterval((() => { - return this.update(); - }), 16); - } + }; + })(this)); + return setInterval(((function(_this) { + return function() { + return _this.update(); + }; + })(this)), 16); + }; - validateLine(v) { + Terminal.prototype.validateLine = function(v) { var i, j, ref; this.history_index = null; if (v.trim().length > 0 && v !== this.history[this.history.length - 1]) { @@ -125,39 +137,41 @@ this.Terminal = class Terminal { } this.saveHistory(); } - this.echo(`${v}`, true, "input"); + this.echo("" + v, true, "input"); if (this.commands[v.trim()] != null) { return this.commands[v.trim()](); } else { this.runwindow.runCommand(v); if (this.runwindow.multiline) { - document.querySelector(`#${this.tid}-input-gt i`).classList.add("fa-ellipsis-v"); + document.querySelector("#" + this.tid + "-input-gt i").classList.add("fa-ellipsis-v"); for (i = j = 0, ref = this.runwindow.nesting * 2 - 1; j <= ref; i = j += 1) { - document.getElementById(`${this.tid}-input`).value += " "; + document.getElementById(this.tid + "-input").value += " "; } return this.setTrailingCaret(); } else { - return document.querySelector(`#${this.tid}-input-gt i`).classList.remove("fa-ellipsis-v"); + return document.querySelector("#" + this.tid + "-input-gt i").classList.remove("fa-ellipsis-v"); } } - } + }; - setTrailingCaret() { - return setTimeout((() => { - var val; - val = document.getElementById(`${this.tid}-input`).value; - return document.getElementById(`${this.tid}-input`).setSelectionRange(val.length, val.length); - }), 0); - } + Terminal.prototype.setTrailingCaret = function() { + return setTimeout(((function(_this) { + return function() { + var val; + val = document.getElementById(_this.tid + "-input").value; + return document.getElementById(_this.tid + "-input").setSelectionRange(val.length, val.length); + }; + })(this)), 0); + }; - update() { + Terminal.prototype.update = function() { var container, div, e, element, j, len, ref, t; if (this.buffer.length > 0) { if (this.force_scroll) { this.scroll = true; this.force_scroll = false; } else { - e = document.getElementById(`${this.tid}-view`); + e = document.getElementById(this.tid + "-view"); this.scroll = Math.abs(e.getBoundingClientRect().height + e.scrollTop - e.scrollHeight) < 10; } div = document.createDocumentFragment(); @@ -168,23 +182,26 @@ this.Terminal = class Terminal { t = ref[j]; container.appendChild(element = this.echoReal(t.text, t.classname)); } - document.getElementById(`${this.tid}-lines`).appendChild(div); + document.getElementById(this.tid + "-lines").appendChild(div); if (this.scroll) { element.scrollIntoView(); } this.length += this.buffer.length; return this.buffer = []; } - } + }; - echo(text, scroll = false, classname) { + Terminal.prototype.echo = function(text, scroll, classname) { + if (scroll == null) { + scroll = false; + } this.buffer.push({ text: text, classname: classname }); - } + }; - echoReal(text, classname) { + Terminal.prototype.echoReal = function(text, classname) { var d, div, i; div = document.createElement("div"); if (classname === "input") { @@ -202,30 +219,35 @@ this.Terminal = class Terminal { } this.truncate(); return div; - } + }; - error(text, scroll = false) { + Terminal.prototype.error = function(text, scroll) { + if (scroll == null) { + scroll = false; + } this.echo(text, scroll, "error"); return this.error_lines += 1; - } + }; - truncate() { + Terminal.prototype.truncate = function() { var c, e; - e = document.getElementById(`${this.tid}-lines`); + e = document.getElementById(this.tid + "-lines"); while (this.length > 10000 && (e.firstChild != null)) { c = e.firstChild.children.length; e.removeChild(e.firstChild); this.length -= c; } - } + }; - clear() { - document.getElementById(`${this.tid}-lines`).innerHTML = ""; + Terminal.prototype.clear = function() { + document.getElementById(this.tid + "-lines").innerHTML = ""; this.buffer = []; this.length = 0; this.error_lines = 0; - document.querySelector(`#${this.tid}-input-gt i`).classList.remove("fa-ellipsis-v"); + document.querySelector("#" + this.tid + "-input-gt i").classList.remove("fa-ellipsis-v"); return delete this.runwindow.multiline; - } + }; + + return Terminal; -}; +})(); diff --git a/static/js/tutorial/highlighter.js b/static/js/tutorial/highlighter.js index 61a0241c..4d51fd24 100644 --- a/static/js/tutorial/highlighter.js +++ b/static/js/tutorial/highlighter.js @@ -1,18 +1,17 @@ -this.Highlighter = class Highlighter { - constructor(tutorial) { +this.Highlighter = (function() { + function Highlighter(tutorial) { this.tutorial = tutorial; this.shown = false; this.canvas = document.getElementById("highlighter"); this.arrow = document.getElementById("highlighter-arrow"); } - highlight(ref, auto) { + Highlighter.prototype.highlight = function(ref, auto) { var element, h, rect, w, x, y; if (ref != null) { element = document.querySelector(ref); } if (element != null) { - // open main menu when it is collapsed if (ref.indexOf(".titlemenu") >= 0 && (document.getElementById("main-menu-button").offsetParent != null)) { element = document.getElementById("main-menu-button"); } @@ -28,19 +27,21 @@ this.Highlighter = class Highlighter { h = Math.floor(rect.height * 1) + 40; this.canvas.width = w; this.canvas.height = h; - this.canvas.style.width = `${w}px`; - this.canvas.style.height = `${h}px`; - this.canvas.style.top = `${Math.round(y - h / 2)}px`; - this.canvas.style.left = `${Math.round(x - w / 2)}px`; + this.canvas.style.width = w + "px"; + this.canvas.style.height = h + "px"; + this.canvas.style.top = (Math.round(y - h / 2)) + "px"; + this.canvas.style.left = (Math.round(x - w / 2)) + "px"; this.canvas.style.display = "block"; this.shown = true; this.updateCanvas(); if (this.timeout != null) { clearTimeout(this.timeout); } - this.timeout = setTimeout((() => { - return this.justHide(); - }), 6000); + this.timeout = setTimeout(((function(_this) { + return function() { + return _this.justHide(); + }; + })(this)), 6000); if (auto) { return this.setAuto(element); } else { @@ -51,60 +52,70 @@ this.Highlighter = class Highlighter { } else { return this.hide(); } - } + }; - setAuto(element) { + Highlighter.prototype.setAuto = function(element) { var f; if (element.tagName === "INPUT" && element.type === "text") { - f = (event) => { - if (event.key === "Enter") { - this.tutorial.nextStep(); - return element.removeEventListener("keydown", f); - } - }; + f = (function(_this) { + return function(event) { + if (event.key === "Enter") { + _this.tutorial.nextStep(); + return element.removeEventListener("keydown", f); + } + }; + })(this); element.addEventListener("keydown", f); if (this.remove_event_listener != null) { this.remove_event_listener(); } - return this.remove_event_listener = () => { - return element.removeEventListener("keydown", f); - }; + return this.remove_event_listener = (function(_this) { + return function() { + return element.removeEventListener("keydown", f); + }; + })(this); } else { - f = () => { - this.tutorial.nextStep(); - return element.removeEventListener("click", f); - }; + f = (function(_this) { + return function() { + _this.tutorial.nextStep(); + return element.removeEventListener("click", f); + }; + })(this); element.addEventListener("click", f); if (this.remove_event_listener != null) { this.remove_event_listener(); } - return this.remove_event_listener = () => { - return element.removeEventListener("click", f); - }; + return this.remove_event_listener = (function(_this) { + return function() { + return element.removeEventListener("click", f); + }; + })(this); } - } + }; - hide() { + Highlighter.prototype.hide = function() { this.shown = false; this.canvas.style.display = "none"; if (this.remove_event_listener != null) { return this.remove_event_listener(); } - } + }; - justHide() { + Highlighter.prototype.justHide = function() { this.shown = false; return this.canvas.style.display = "none"; - } + }; - updateCanvas() { + Highlighter.prototype.updateCanvas = function() { var amount, context, grd, h, i, j, ref1, w, x, y; if (!this.shown) { return; } - requestAnimationFrame(() => { - return this.updateCanvas(); - }); + requestAnimationFrame((function(_this) { + return function() { + return _this.updateCanvas(); + }; + })(this)); context = this.canvas.getContext("2d"); context.clearRect(0, 0, this.canvas.width, this.canvas.height); if (this.highlighted.getBoundingClientRect().width === 0) { @@ -133,8 +144,9 @@ this.Highlighter = class Highlighter { y = y > 0 ? Math.sqrt(y) : -Math.sqrt(-y); context.lineTo(this.canvas.width / 2 + x * w, this.canvas.height / 2 + y * h); } - //context.ellipse(@canvas.width/2,@canvas.height/2,w,h,Math.PI,Math.PI*2*Math.min(1,amount),0,true) return context.stroke(); - } + }; + + return Highlighter; -}; +})(); diff --git a/static/js/tutorial/tutorials.js b/static/js/tutorial/tutorials.js index 9001a55e..dd1cbe92 100644 --- a/static/js/tutorial/tutorials.js +++ b/static/js/tutorial/tutorials.js @@ -1,19 +1,21 @@ -this.Tutorials = class Tutorials { - constructor(app) { +this.Tutorials = (function() { + function Tutorials(app) { this.app = app; this.tutorials_page = new TutorialsPage(this); } - load() { + Tutorials.prototype.load = function() { var origin, req; req = new XMLHttpRequest(); - req.onreadystatechange = (event) => { - if (req.readyState === XMLHttpRequest.DONE) { - if (req.status === 200) { - return this.update(req.responseText); + req.onreadystatechange = (function(_this) { + return function(event) { + if (req.readyState === XMLHttpRequest.DONE) { + if (req.status === 200) { + return _this.update(req.responseText); + } } - } - }; + }; + })(this); origin = window.ms_tutorials_root_url || location.origin + "/tutorials/"; switch (this.app.translator.lang) { case "fr": @@ -29,9 +31,9 @@ this.Tutorials = class Tutorials { req.open("GET", origin + "en/toc.md"); } return req.send(); - } + }; - update(doc) { + Tutorials.prototype.update = function(doc) { var e, e2, element, j, k, len, len1, list, ref, ref1; element = document.createElement("div"); element.innerHTML = DOMPurify.sanitize(marked(doc)); @@ -40,7 +42,6 @@ this.Tutorials = class Tutorials { ref = element.childNodes; for (j = 0, len = ref.length; j < len; j++) { e = ref[j]; - //console.info e switch (e.tagName) { case "H2": list = { @@ -72,11 +73,10 @@ this.Tutorials = class Tutorials { } } } - //console.info @tutorials this.build(); - } + }; - checkCompletion() { + Tutorials.prototype.checkCompletion = function() { var all, course, hasAchievement, i, id, j, k, len, len1, list, progress, ref, ref1, results, tuto; list = ["tour", "programming", "drawing", "game"]; ref = this.tutorials; @@ -93,18 +93,20 @@ this.Tutorials = class Tutorials { } } if (all) { - id = `tutorials/tutorial_${list[i]}`; - hasAchievement = (id) => { - var a, l, len2, ref2; - ref2 = this.app.user.info.achievements; - for (l = 0, len2 = ref2.length; l < len2; l++) { - a = ref2[l]; - if (a.id === id) { - return true; + id = "tutorials/tutorial_" + list[i]; + hasAchievement = (function(_this) { + return function(id) { + var a, l, len2, ref2; + ref2 = _this.app.user.info.achievements; + for (l = 0, len2 = ref2.length; l < len2; l++) { + a = ref2[l]; + if (a.id === id) { + return true; + } } - } - return false; - }; + return false; + }; + })(this); if (!hasAchievement(id)) { console.info("sending tutorial completion " + id); results.push(this.app.client.send({ @@ -119,9 +121,9 @@ this.Tutorials = class Tutorials { } } return results; - } + }; - build() { + Tutorials.prototype.build = function() { var div, j, len, ref, t; document.getElementById("tutorials-content").innerHTML = ""; ref = this.tutorials; @@ -131,11 +133,11 @@ this.Tutorials = class Tutorials { } this.checkCompletion(); div = document.createElement("div"); - div.innerHTML = `
\n

${this.app.translator.get("More Tutorials")}

\n

${this.app.translator.get("Check this great series of microStudio tutorials by mrLman:")}

\n
`; + div.innerHTML = "
\n

" + (this.app.translator.get("More Tutorials")) + "

\n

" + (this.app.translator.get("Check this great series of microStudio tutorials by mrLman:")) + "

\n
"; document.getElementById("tutorials-content").appendChild(div); - } + }; - buildCourse(course) { + Tutorials.prototype.buildCourse = function(course) { var div, h2, j, len, p, ref, t, ul; div = document.createElement("div"); div.classList.add("course"); @@ -153,23 +155,25 @@ this.Tutorials = class Tutorials { div.appendChild(this.buildTutorial(t)); } return document.getElementById("tutorials-content").appendChild(div); - } + }; - buildTutorial(t) { + Tutorials.prototype.buildTutorial = function(t) { var a, code, li, progress; li = document.createElement("li"); - li.innerHTML = ` ${t.title}`; - li.addEventListener("click", () => { - return this.startTutorial(t); - }); + li.innerHTML = " " + t.title; + li.addEventListener("click", (function(_this) { + return function() { + return _this.startTutorial(t); + }; + })(this)); progress = this.app.getTutorialProgress(t.link); if (progress > 0) { - li.style.background = `linear-gradient(90deg,hsl(160,50%,70%) 0%,hsl(160,50%,70%) ${progress}%,rgba(0,0,0,.1) ${progress}%)`; + li.style.background = "linear-gradient(90deg,hsl(160,50%,70%) 0%,hsl(160,50%,70%) " + progress + "%,rgba(0,0,0,.1) " + progress + "%)"; li.addEventListener("mouseover", function() { return li.style.background = "hsl(200,50%,70%)"; }); li.addEventListener("mouseout", function() { - return li.style.background = `linear-gradient(90deg,hsl(160,50%,70%) 0%,hsl(160,50%,70%) ${progress}%,rgba(0,0,0,.1) ${progress}%)`; + return li.style.background = "linear-gradient(90deg,hsl(160,50%,70%) 0%,hsl(160,50%,70%) " + progress + "%,rgba(0,0,0,.1) " + progress + "%)"; }); } if (progress === 100) { @@ -185,18 +189,24 @@ this.Tutorials = class Tutorials { code.classList.add("fa-file-code"); a.appendChild(code); li.appendChild(a); - a.addEventListener("click", (event) => { - return event.stopPropagation(); - }); + a.addEventListener("click", (function(_this) { + return function(event) { + return event.stopPropagation(); + }; + })(this)); return li; - } + }; - startTutorial(t) { + Tutorials.prototype.startTutorial = function(t) { var tuto; tuto = new Tutorial(t.link.replace("https://microstudio.dev", location.origin)); - return tuto.load(() => { - return this.app.tutorial.start(tuto); - }); - } + return tuto.load((function(_this) { + return function() { + return _this.app.tutorial.start(tuto); + }; + })(this)); + }; + + return Tutorials; -}; +})(); diff --git a/static/js/tutorial/tutorialspage.js b/static/js/tutorial/tutorialspage.js index d16c6a87..0c4b30fa 100644 --- a/static/js/tutorial/tutorialspage.js +++ b/static/js/tutorial/tutorialspage.js @@ -1,75 +1,88 @@ var TutorialsPage; -TutorialsPage = class TutorialsPage { - constructor(tutorials) { +TutorialsPage = (function() { + function TutorialsPage(tutorials) { this.tutorials = tutorials; this.app = this.tutorials.app; this.sections = ["core", "community", "examples"]; this.initSections(); this.setSection(this.sections[0], false); this.search = ""; - document.querySelector("#tutorials-example-view-topbar i").addEventListener("click", () => { - this.closeExampleView(); - return this.pushState(); - }); - document.getElementById("example-search-input").addEventListener("input", () => { - this.search = document.getElementById("example-search-input").value; - return this.planExamplesUpdate(); - }); - document.querySelector("#tutorials-content-examples .project-search-bar select").addEventListener("change", () => { - return this.planExamplesUpdate(); - }); + document.querySelector("#tutorials-example-view-topbar i").addEventListener("click", (function(_this) { + return function() { + _this.closeExampleView(); + return _this.pushState(); + }; + })(this)); + document.getElementById("example-search-input").addEventListener("input", (function(_this) { + return function() { + _this.search = document.getElementById("example-search-input").value; + return _this.planExamplesUpdate(); + }; + })(this)); + document.querySelector("#tutorials-content-examples .project-search-bar select").addEventListener("change", (function(_this) { + return function() { + return _this.planExamplesUpdate(); + }; + })(this)); } - planExamplesUpdate() { + TutorialsPage.prototype.planExamplesUpdate = function() { if (this.search_timeout != null) { clearTimeout(this.search_timeout); } - this.search_timeout = setTimeout((() => { - return this.queryExamples(0, (list) => { - return this.displayExamples(list); - }); - }), 1500); + this.search_timeout = setTimeout(((function(_this) { + return function() { + return _this.queryExamples(0, function(list) { + return _this.displayExamples(list); + }); + }; + })(this)), 1500); return document.querySelector("#tutorials-examples-list").style.opacity = .25; - } + }; - initSections() { + TutorialsPage.prototype.initSections = function() { var j, len, ref, results, s; ref = this.sections; results = []; for (j = 0, len = ref.length; j < len; j++) { s = ref[j]; - results.push(((s) => { - return document.getElementById(`tutorials-${s}`).addEventListener("click", () => { - if (window.ms_standalone) { - if (s === "community") { - return window.open("https://microstudio.dev/tutorials/community/", "_blank"); - } else if (s === "examples") { - return window.open("https://microstudio.dev/tutorials/examples/", "_blank"); + results.push((function(_this) { + return function(s) { + return document.getElementById("tutorials-" + s).addEventListener("click", function() { + if (window.ms_standalone) { + if (s === "community") { + return window.open("https://microstudio.dev/tutorials/community/", "_blank"); + } else if (s === "examples") { + return window.open("https://microstudio.dev/tutorials/examples/", "_blank"); + } + } else { + return _this.setSection(s); } - } else { - return this.setSection(s); - } - }); - })(s)); + }); + }; + })(this)(s)); } return results; - } + }; - pushState() { + TutorialsPage.prototype.pushState = function() { if (this.current === "core") { return this.app.app_state.pushState("tutorials", "/tutorials/"); } else { if (this.current === "examples" && (this.current_project != null)) { - return this.app.app_state.pushState(`tutorials.${this.current}.${this.current_project.owner}.${this.current_project.slug}`, `/tutorials/${this.current}/${this.current_project.owner}/${this.current_project.slug}/`); + return this.app.app_state.pushState("tutorials." + this.current + "." + this.current_project.owner + "." + this.current_project.slug, "/tutorials/" + this.current + "/" + this.current_project.owner + "/" + this.current_project.slug + "/"); } else { - return this.app.app_state.pushState(`tutorials.${this.current}`, `/tutorials/${this.current}/`); + return this.app.app_state.pushState("tutorials." + this.current, "/tutorials/" + this.current + "/"); } } - } + }; - setSection(section, push_state = true) { + TutorialsPage.prototype.setSection = function(section, push_state) { var j, len, ref, s; + if (push_state == null) { + push_state = true; + } console.info(section); this.current = section; if (push_state) { @@ -79,11 +92,11 @@ TutorialsPage = class TutorialsPage { for (j = 0, len = ref.length; j < len; j++) { s = ref[j]; if (s === section) { - document.getElementById(`tutorials-${s}`).classList.add("selected"); - document.getElementById(`tutorials-content-${s}`).style.display = "block"; + document.getElementById("tutorials-" + s).classList.add("selected"); + document.getElementById("tutorials-content-" + s).style.display = "block"; } else { - document.getElementById(`tutorials-${s}`).classList.remove("selected"); - document.getElementById(`tutorials-content-${s}`).style.display = "none"; + document.getElementById("tutorials-" + s).classList.remove("selected"); + document.getElementById("tutorials-content-" + s).style.display = "none"; } } if (section === "community") { @@ -91,10 +104,16 @@ TutorialsPage = class TutorialsPage { } else if (section === "examples") { return this.updateExamples(); } - } + }; - queryExamples(offset = 0, callback, list = []) { + TutorialsPage.prototype.queryExamples = function(offset, callback, list) { var language; + if (offset == null) { + offset = 0; + } + if (list == null) { + list = []; + } language = document.querySelector("#tutorials-content-examples .project-search-bar select").value.toLowerCase(); return this.app.client.sendRequest({ name: "get_public_projects", @@ -105,38 +124,48 @@ TutorialsPage = class TutorialsPage { search: this.search.toLowerCase(), position: 0, offset: offset - }, (msg) => { - if (msg.list.length === 0) { - if (callback != null) { - return callback(list); + }, (function(_this) { + return function(msg) { + if (msg.list.length === 0) { + if (callback != null) { + return callback(list); + } + } else { + list = list.concat(msg.list); + return _this.queryExamples(msg.offset, callback, list); } - } else { - list = list.concat(msg.list); - return this.queryExamples(msg.offset, callback, list); - } - }); - } + }; + })(this)); + }; - fetchAll(type, offset = 0, callback, list = []) { + TutorialsPage.prototype.fetchAll = function(type, offset, callback, list) { + if (offset == null) { + offset = 0; + } + if (list == null) { + list = []; + } return this.app.client.sendRequest({ name: "get_public_projects", ranking: "hot", type: type, tags: [], - search: "", //@search.toLowerCase() + search: "", position: 0, offset: offset - }, (msg) => { - if (msg.list.length === 0) { - return callback(list); - } else { - list = list.concat(msg.list); - return this.fetchAll(type, msg.offset, callback, list); - } - }); - } + }, (function(_this) { + return function(msg) { + if (msg.list.length === 0) { + return callback(list); + } else { + list = list.concat(msg.list); + return _this.fetchAll(type, msg.offset, callback, list); + } + }; + })(this)); + }; - createProjectBox(p) { + TutorialsPage.prototype.createProjectBox = function(p) { var div, i, icon, title; console.info(p); if (!p.flags.approved && !p.owner_info.approved && window.ms_project_moderation) { @@ -148,9 +177,9 @@ TutorialsPage = class TutorialsPage { title.innerText = p.title; icon = new Image; if (p.icon) { - icon.src = `${run_domain}/${p.owner}/${p.slug}/sprites/icon.png`; + icon.src = run_domain + "/" + p.owner + "/" + p.slug + "/sprites/icon.png"; } else { - icon.src = `${dev_domain}/img/lightbulb16.png`; + icon.src = dev_domain + "/img/lightbulb16.png"; } icon.classList.add("pixelated"); div.appendChild(icon); @@ -160,40 +189,44 @@ TutorialsPage = class TutorialsPage { div.appendChild(title); div.appendChild(i); return div; - } + }; - updateCommunity() { + TutorialsPage.prototype.updateCommunity = function() { var parent; parent = document.getElementById("tutorials-content-community"); parent.innerHTML = ""; - return this.fetchAll("tutorial", 0, (list) => { - var box, j, len, p, results; - results = []; - for (j = 0, len = list.length; j < len; j++) { - p = list[j]; - box = this.createProjectBox(p); - if (box) { - parent.appendChild(box); - results.push(((p) => { - return box.addEventListener("click", () => { - return window.open(dev_domain + `/tutorial/${p.owner}/${p.slug}/`, "_blank"); - }); - })(p)); - } else { - results.push(void 0); + return this.fetchAll("tutorial", 0, (function(_this) { + return function(list) { + var box, j, len, p, results; + results = []; + for (j = 0, len = list.length; j < len; j++) { + p = list[j]; + box = _this.createProjectBox(p); + if (box) { + parent.appendChild(box); + results.push((function(p) { + return box.addEventListener("click", function() { + return window.open(dev_domain + ("/tutorial/" + p.owner + "/" + p.slug + "/"), "_blank"); + }); + })(p)); + } else { + results.push(void 0); + } } - } - return results; - }); - } + return results; + }; + })(this)); + }; - updateExamples() { - return this.queryExamples(0, (list) => { - return this.displayExamples(list); - }); - } + TutorialsPage.prototype.updateExamples = function() { + return this.queryExamples(0, (function(_this) { + return function(list) { + return _this.displayExamples(list); + }; + })(this)); + }; - displayExamples(list) { + TutorialsPage.prototype.displayExamples = function(list) { var box, j, len, p, parent; parent = document.getElementById("tutorials-examples-list"); parent.innerHTML = ""; @@ -203,48 +236,52 @@ TutorialsPage = class TutorialsPage { box = this.createProjectBox(p); if (box) { parent.appendChild(box); - ((p, box) => { - return box.addEventListener("click", () => { - this.current_project = { - owner: p.owner, - slug: p.slug - }; - this.loadExample(p); - this.openExampleView(); - return this.pushState(); + (function(_this) { + return (function(p, box) { + return box.addEventListener("click", function() { + _this.current_project = { + owner: p.owner, + slug: p.slug + }; + _this.loadExample(p); + _this.openExampleView(); + return _this.pushState(); + }); }); - })(p, box); + })(this)(p, box); } } - } + }; - reloadExample(owner, slug) { + TutorialsPage.prototype.reloadExample = function(owner, slug) { return this.app.client.sendRequest({ name: "get_public_project", owner: owner, project: slug - }, (msg) => { - var project; - project = msg.project; - if (project != null) { - this.loadExample(project); - this.openExampleView(); - return this.current_project = { - owner: project.owner, - slug: project.slug - }; - } - }); - } + }, (function(_this) { + return function(msg) { + var project; + project = msg.project; + if (project != null) { + _this.loadExample(project); + _this.openExampleView(); + return _this.current_project = { + owner: project.owner, + slug: project.slug + }; + } + }; + })(this)); + }; - openExampleView() { + TutorialsPage.prototype.openExampleView = function() { document.getElementById("tutorials-examples-list").style.display = "none"; document.querySelector("#tutorials-content-examples .project-search-bar").style.display = "none"; document.getElementById("tutorials-examples-view").style.display = "block"; return document.getElementById("tutorials-example-view-topbar").style.display = "block"; - } + }; - closeExampleView() { + TutorialsPage.prototype.closeExampleView = function() { var device; document.getElementById("tutorials-examples-list").style.display = "block"; document.querySelector("#tutorials-content-examples .project-search-bar").style.display = "block"; @@ -253,9 +290,9 @@ TutorialsPage = class TutorialsPage { device = document.getElementById("tutorials-examples-run"); device.innerHTML = ""; return delete this.current_project; - } + }; - loadExample(project) { + TutorialsPage.prototype.loadExample = function(project) { var icon; delete this.selected_source; if (!this.examples_initialized) { @@ -272,16 +309,18 @@ TutorialsPage = class TutorialsPage { this.examples_editor.getSession().setOptions({ tabSize: 2, useSoftTabs: true, - useWorker: false // disables lua autocorrection ; preserves syntax coloring - }); - this.examples_editor.getSession().on("change", () => { - return this.codeEdited(); + useWorker: false }); + this.examples_editor.getSession().on("change", (function(_this) { + return function() { + return _this.codeEdited(); + }; + })(this)); } if (project.icon) { - icon = run_domain + `/${project.owner}/${project.slug}/sprites/icon.png`; + icon = run_domain + ("/" + project.owner + "/" + project.slug + "/sprites/icon.png"); } else { - icon = `${dev_domain}/img/lightbulb16.png`; + icon = dev_domain + "/img/lightbulb16.png"; } document.querySelector("#tutorials-example-view-topbar img").src = icon; document.querySelector("#tutorials-example-view-topbar span").innerText = project.title; @@ -290,26 +329,28 @@ TutorialsPage = class TutorialsPage { name: "list_public_project_files", project: project.id, folder: "ms" - }, (msg) => { - var device, origin, url; - this.setSourceList(msg.files, project); - this.examples_splitbar.update(); - this.examples_code_splitbar.update(); - this.examples_splitbar.update(); - device = document.getElementById("tutorials-examples-run"); - origin = run_domain; - url = `${run_domain}/${project.owner}/${project.slug}/`; - device.innerHTML = ``; - return device.querySelector("i").addEventListener("click", () => { - return this.postMessage({ - name: "command", - line: "init()" + }, (function(_this) { + return function(msg) { + var device, origin, url; + _this.setSourceList(msg.files, project); + _this.examples_splitbar.update(); + _this.examples_code_splitbar.update(); + _this.examples_splitbar.update(); + device = document.getElementById("tutorials-examples-run"); + origin = run_domain; + url = run_domain + "/" + project.owner + "/" + project.slug + "/"; + device.innerHTML = ""; + return device.querySelector("i").addEventListener("click", function() { + return _this.postMessage({ + name: "command", + line: "init()" + }); }); - }); - }); - } + }; + })(this)); + }; - setSelectedSource(file) { + TutorialsPage.prototype.setSelectedSource = function(file) { var lang, source; this.selected_source = file; this.source_folder.setSelectedItem(file); @@ -326,31 +367,35 @@ TutorialsPage = class TutorialsPage { this.examples_editor.getSession().setMode(lang.ace_mode); } return this.examples_editor.setValue(this.sources[file], -1); - } + }; - setSourceList(files, project) { + TutorialsPage.prototype.setSourceList = function(files, project) { var f, folder, j, len, manager, s, table, view; table = {}; manager = { folder: "ms", item: "source", - openItem: (item) => { - return this.setSelectedSource(item); - } + openItem: (function(_this) { + return function(item) { + return _this.setSelectedSource(item); + }; + })(this) }; this.project_sources = {}; this.sources = {}; - project = JSON.parse(JSON.stringify(project)); // create a clone + project = JSON.parse(JSON.stringify(project)); project.app = this.app; - project.notifyListeners = (source) => { - this.sources[source.name] = source.content; - if (this.selected_source == null) { - return this.setSelectedSource(source.name); - } - }; + project.notifyListeners = (function(_this) { + return function(source) { + _this.sources[source.name] = source.content; + if (_this.selected_source == null) { + return _this.setSelectedSource(source.name); + } + }; + })(this); project.getFullURL = function() { var url; - return url = location.origin + `/${project.owner}/${project.slug}/`; + return url = location.origin + ("/" + project.owner + "/" + project.slug + "/"); }; folder = new ProjectFolder(null, "source"); for (j = 0, len = files.length; j < len; j++) { @@ -365,28 +410,30 @@ TutorialsPage = class TutorialsPage { view.editable = false; view.rebuildList(folder); this.project = project; - } + }; - codeEdited() { + TutorialsPage.prototype.codeEdited = function() { if (this.selected_source) { return this.updateCode(this.selected_source + ".ms", this.examples_editor.getValue()); } - } + }; - updateCode(file, src) { + TutorialsPage.prototype.updateCode = function(file, src) { return this.postMessage({ name: "code_updated", file: file, code: src }); - } + }; - postMessage(data) { + TutorialsPage.prototype.postMessage = function(data) { var iframe; iframe = document.getElementById("exampleiframe"); if (iframe != null) { return iframe.contentWindow.postMessage(JSON.stringify(data), "*"); } - } + }; + + return TutorialsPage; -}; +})(); diff --git a/static/js/tutorial/tutorialwindow.js b/static/js/tutorial/tutorialwindow.js index bf30d7c6..75e1e604 100644 --- a/static/js/tutorial/tutorialwindow.js +++ b/static/js/tutorial/tutorialwindow.js @@ -1,44 +1,64 @@ -this.TutorialWindow = class TutorialWindow { - constructor(app) { +this.TutorialWindow = (function() { + function TutorialWindow(app) { this.app = app; this.window = document.getElementById("tutorial-window"); - document.querySelector("#tutorial-window").addEventListener("mousedown", (event) => { - return this.moveToFront(); - }); - document.querySelector("#tutorial-window .titlebar").addEventListener("click", (event) => { - return this.uncollapse(); - }); - document.querySelector("#tutorial-window .titlebar").addEventListener("mousedown", (event) => { - return this.startMove(event); - }); - document.querySelector("#tutorial-window .navigation .resize").addEventListener("mousedown", (event) => { - return this.startResize(event); - }); - document.addEventListener("mousemove", (event) => { - return this.mouseMove(event); - }); - document.addEventListener("mouseup", (event) => { - return this.mouseUp(event); - }); - window.addEventListener("resize", () => { - var b; - b = this.window.getBoundingClientRect(); - return this.setPosition(b.x, b.y); - }); - document.querySelector("#tutorial-window .navigation .previous").addEventListener("click", () => { - return this.previousStep(); - }); - document.querySelector("#tutorial-window .navigation .next").addEventListener("click", () => { - return this.nextStep(); - }); - document.querySelector("#tutorial-window .titlebar .minify").addEventListener("click", () => { - return this.close(); - }); + document.querySelector("#tutorial-window").addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.moveToFront(); + }; + })(this)); + document.querySelector("#tutorial-window .titlebar").addEventListener("click", (function(_this) { + return function(event) { + return _this.uncollapse(); + }; + })(this)); + document.querySelector("#tutorial-window .titlebar").addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.startMove(event); + }; + })(this)); + document.querySelector("#tutorial-window .navigation .resize").addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.startResize(event); + }; + })(this)); + document.addEventListener("mousemove", (function(_this) { + return function(event) { + return _this.mouseMove(event); + }; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function(event) { + return _this.mouseUp(event); + }; + })(this)); + window.addEventListener("resize", (function(_this) { + return function() { + var b; + b = _this.window.getBoundingClientRect(); + return _this.setPosition(b.x, b.y); + }; + })(this)); + document.querySelector("#tutorial-window .navigation .previous").addEventListener("click", (function(_this) { + return function() { + return _this.previousStep(); + }; + })(this)); + document.querySelector("#tutorial-window .navigation .next").addEventListener("click", (function(_this) { + return function() { + return _this.nextStep(); + }; + })(this)); + document.querySelector("#tutorial-window .titlebar .minify").addEventListener("click", (function(_this) { + return function() { + return _this.close(); + }; + })(this)); this.highlighter = new Highlighter(this); this.max_ratio = .75; } - moveToFront() { + TutorialWindow.prototype.moveToFront = function() { var e, i, len, list; list = document.getElementsByClassName("floating-window"); for (i = 0, len = list.length; i < len; i++) { @@ -49,17 +69,19 @@ this.TutorialWindow = class TutorialWindow { e.style["z-index"] = 10; } } - } + }; - start(tutorial) { + TutorialWindow.prototype.start = function(tutorial) { var progress; this.tutorial = tutorial; this.shown = true; this.uncollapse(); if ((this.tutorial.project_title != null) && (this.app.user == null)) { - this.app.appui.accountRequired(() => { - return this.start(this.tutorial); - }); + this.app.appui.accountRequired((function(_this) { + return function() { + return _this.start(_this.tutorial); + }; + })(this)); return; } this.openProject(); @@ -71,9 +93,9 @@ this.TutorialWindow = class TutorialWindow { this.current_step = 0; } return this.setStep(this.current_step); - } + }; - openProject() { + TutorialWindow.prototype.openProject = function() { var err, i, i1, i2, len, options, p, project, ref, slug; if (this.tutorial.project_title != null) { slug = RegexLib.slugify(this.tutorial.project_title.split("{")[0]); @@ -100,14 +122,18 @@ this.TutorialWindow = class TutorialWindow { err = error; console.error(err); } - this.app.createProject(this.tutorial.project_title.substring(0, i1).trim(), slug, options, () => { - return this.start(this.tutorial); - }); + this.app.createProject(this.tutorial.project_title.substring(0, i1).trim(), slug, options, (function(_this) { + return function() { + return _this.start(_this.tutorial); + }; + })(this)); return; } else { - this.app.createProject(this.tutorial.project_title, slug, () => { - return this.start(this.tutorial); - }); + this.app.createProject(this.tutorial.project_title, slug, (function(_this) { + return function() { + return _this.start(_this.tutorial); + }; + })(this)); return; } } @@ -115,15 +141,15 @@ this.TutorialWindow = class TutorialWindow { this.app.appui.setMainSection("projects"); return this.app.appui.setSection("code"); } - } + }; - update() { + TutorialWindow.prototype.update = function() { if (this.tutorial != null) { return this.setStep(this.current_step); } - } + }; - setStep(index) { + TutorialWindow.prototype.setStep = function(index) { var c, e, element, h, i, len, percent, progress, ref, s, step, w; if (this.tutorial != null) { index = Math.max(0, Math.min(this.tutorial.steps.length - 1, index)); @@ -139,7 +165,7 @@ this.TutorialWindow = class TutorialWindow { e.scrollTo(0, 0); document.querySelector("#tutorial-window .navigation .step").innerText = (index + 1) + " / " + this.tutorial.steps.length; percent = Math.round(this.current_step / (this.tutorial.steps.length - 1) * 100); - document.querySelector("#tutorial-window .navigation .step").style.background = `linear-gradient(90deg,hsl(200,50%,80%) 0%,hsl(200,50%,80%) ${percent}%,transparent ${percent}%)`; + document.querySelector("#tutorial-window .navigation .step").style.background = "linear-gradient(90deg,hsl(200,50%,80%) 0%,hsl(200,50%,80%) " + percent + "%,transparent " + percent + "%)"; if (step.navigate != null) { s = step.navigate.split("."); this.app.appui.setMainSection(s[0]); @@ -157,8 +183,8 @@ this.TutorialWindow = class TutorialWindow { if (s.length === 4) { w = Math.floor(Math.max(200, Math.min(window.innerWidth * s[2] / 100))); h = Math.floor(Math.max(200, Math.min(window.innerHeight * s[3] / 100))); - this.window.style.width = `${w}px`; - this.window.style.height = `${h}px`; + this.window.style.width = w + "px"; + this.window.style.height = h + "px"; this.setPosition(s[0] * window.innerWidth / 100, s[1] * window.innerHeight / 100); } } @@ -179,10 +205,8 @@ this.TutorialWindow = class TutorialWindow { document.getElementById("tutorial-overlay").style.display = "none"; } } - //if @current_step>0 progress = this.app.getTutorialProgress(this.tutorial.link); percent = Math.round(this.current_step / (this.tutorial.steps.length - 1) * 100); - //if percent>progress this.app.setTutorialProgress(this.tutorial.link, percent); if (this.current_step === this.tutorial.steps.length - 1) { document.querySelector("#tutorial-window .navigation .next").classList.add("fa-check"); @@ -191,21 +215,21 @@ this.TutorialWindow = class TutorialWindow { document.querySelector("#tutorial-window .navigation .next").classList.remove("fa-check"); document.querySelector("#tutorial-window .navigation .next").classList.add("fa-arrow-right"); } - } + }; - nextStep() { + TutorialWindow.prototype.nextStep = function() { if (this.current_step === this.tutorial.steps.length - 1) { return this.close(); } else { return this.setStep(this.current_step + 1); } - } + }; - previousStep() { + TutorialWindow.prototype.previousStep = function() { return this.setStep(this.current_step - 1); - } + }; - close() { + TutorialWindow.prototype.close = function() { var b, button; if (this.current_step === this.tutorial.steps.length - 1) { this.shown = false; @@ -225,22 +249,24 @@ this.TutorialWindow = class TutorialWindow { button = document.getElementById("menu-tutorials"); b = button.getBoundingClientRect(); this.window.classList.add("minimized"); - return setTimeout((() => { - if (b.x < 0) { // Main bar is collapsed - this.window.style.top = "20px"; - this.window.style.left = "240px"; - } else { - this.window.style.top = Math.max(0, b.y + b.height - 10) + "px"; - this.window.style.left = Math.max(0, b.x + b.width / 2 + 20) + "px"; - } - this.window.style.width = "30px"; - this.window.style.height = "30px"; - return this.collapsed = true; - }), 100); + return setTimeout(((function(_this) { + return function() { + if (b.x < 0) { + _this.window.style.top = "20px"; + _this.window.style.left = "240px"; + } else { + _this.window.style.top = Math.max(0, b.y + b.height - 10) + "px"; + _this.window.style.left = Math.max(0, b.x + b.width / 2 + 20) + "px"; + } + _this.window.style.width = "30px"; + _this.window.style.height = "30px"; + return _this.collapsed = true; + }; + })(this)), 100); } - } + }; - uncollapse() { + TutorialWindow.prototype.uncollapse = function() { if (this.collapsed) { this.collapsed = false; this.openProject(); @@ -248,30 +274,32 @@ this.TutorialWindow = class TutorialWindow { this.window.style.left = this.pos_left; this.window.style.width = this.pos_width; this.window.style.height = this.pos_height; - return setTimeout((() => { - this.window.classList.remove("minimized"); - return this.setStep(this.current_step); - }), 100); + return setTimeout(((function(_this) { + return function() { + _this.window.classList.remove("minimized"); + return _this.setStep(_this.current_step); + }; + })(this)), 100); } - } + }; - startMove(event) { + TutorialWindow.prototype.startMove = function(event) { this.moving = true; this.drag_start_x = event.clientX; this.drag_start_y = event.clientY; this.drag_pos_x = this.window.getBoundingClientRect().x; return this.drag_pos_y = this.window.getBoundingClientRect().y; - } + }; - startResize(event) { + TutorialWindow.prototype.startResize = function(event) { this.resizing = true; this.drag_start_x = event.clientX; this.drag_start_y = event.clientY; this.drag_size_w = this.window.getBoundingClientRect().width; return this.drag_size_h = this.window.getBoundingClientRect().height; - } + }; - mouseMove(event) { + TutorialWindow.prototype.mouseMove = function(event) { var b, dx, dy, h, w; if (this.moving) { dx = event.clientX - this.drag_start_x; @@ -283,27 +311,29 @@ this.TutorialWindow = class TutorialWindow { dy = event.clientY - this.drag_start_y; w = Math.floor(Math.max(200, Math.min(window.innerWidth * this.max_ratio, this.drag_size_w + dx))); h = Math.floor(Math.max(200, Math.min(window.innerHeight * this.max_ratio, this.drag_size_h + dy))); - this.window.style.width = `${w}px`; - this.window.style.height = `${h}px`; + this.window.style.width = w + "px"; + this.window.style.height = h + "px"; b = this.window.getBoundingClientRect(); if (w > window.innerWidth - b.x || h > window.innerHeight - b.y) { return this.setPosition(Math.min(b.x, window.innerWidth - w - 4), Math.min(b.y, window.innerHeight - h - 4)); } } - } + }; - mouseUp(event) { + TutorialWindow.prototype.mouseUp = function(event) { this.moving = false; return this.resizing = false; - } + }; - setPosition(x, y) { + TutorialWindow.prototype.setPosition = function(x, y) { var b; b = this.window.getBoundingClientRect(); x = Math.max(4, Math.min(window.innerWidth - b.width - 4, x)); y = Math.max(4, Math.min(window.innerHeight - b.height - 4, y)); this.window.style.top = y + "px"; return this.window.style.left = x + "px"; - } + }; + + return TutorialWindow; -}; +})(); diff --git a/static/js/user/usersettings.js b/static/js/user/usersettings.js index 63a30cce..c5abefbe 100644 --- a/static/js/user/usersettings.js +++ b/static/js/user/usersettings.js @@ -1,176 +1,213 @@ -this.UserSettings = class UserSettings { - constructor(app) { +this.UserSettings = (function() { + function UserSettings(app) { var checkDeleteButton; this.app = app; - document.getElementById("resend-validation-email").addEventListener("click", () => { - return this.resendValidationEMail(); - }); - //document.getElementById("change-password").addEventListener "click",()=>@changePassword() - document.getElementById("subscribe-newsletter").addEventListener("change", () => { - return this.newsletterChange(); - }); - document.getElementById("experimental-features").addEventListener("change", () => { - return this.experimentalChange(); - }); - document.getElementById("usersetting-email").addEventListener("input", () => { - return this.emailChange(); - }); - document.getElementById("open-translation-app").addEventListener("click", () => { - return this.openTranslationApp(); - }); - document.getElementById("translation-app-back-button").addEventListener("click", () => { - return this.closeTranslationApp(); - }); + document.getElementById("resend-validation-email").addEventListener("click", (function(_this) { + return function() { + return _this.resendValidationEMail(); + }; + })(this)); + document.getElementById("subscribe-newsletter").addEventListener("change", (function(_this) { + return function() { + return _this.newsletterChange(); + }; + })(this)); + document.getElementById("experimental-features").addEventListener("change", (function(_this) { + return function() { + return _this.experimentalChange(); + }; + })(this)); + document.getElementById("usersetting-email").addEventListener("input", (function(_this) { + return function() { + return _this.emailChange(); + }; + })(this)); + document.getElementById("open-translation-app").addEventListener("click", (function(_this) { + return function() { + return _this.openTranslationApp(); + }; + })(this)); + document.getElementById("translation-app-back-button").addEventListener("click", (function(_this) { + return function() { + return _this.closeTranslationApp(); + }; + })(this)); if (window.ms_standalone) { this.hideChangePassword(); } else { - document.getElementById("usersetting-change-password").addEventListener("click", () => { - return this.changePasswordClick(); - }); - document.getElementById("usersetting-password-new2").addEventListener("keyup", (event) => { - if (event.keyCode === 13) { - return this.changePasswordClick(); - } - }); - document.getElementById("show-account-deletion").addEventListener("click", () => { - var e; - e = document.getElementById("delete-account-form"); - if (e.style.display !== "block") { - e.style.display = "block"; - return document.getElementById("delete-account").scrollIntoView(); - } else { - return e.style.display = "none"; - } - }); - document.getElementById("delete-account-button").addEventListener("click", () => { - return this.deleteAccount(); - }); - checkDeleteButton = () => { - if (document.getElementById("delete-account-confirm").value === "DELETE MY ACCOUNT" && document.getElementById("delete-account-password").value.length > 0) { - return document.getElementById("delete-account-button").classList.add("enabled"); - } else { - return document.getElementById("delete-account-button").classList.remove("enabled"); - } - }; + document.getElementById("usersetting-change-password").addEventListener("click", (function(_this) { + return function() { + return _this.changePasswordClick(); + }; + })(this)); + document.getElementById("usersetting-password-new2").addEventListener("keyup", (function(_this) { + return function(event) { + if (event.keyCode === 13) { + return _this.changePasswordClick(); + } + }; + })(this)); + document.getElementById("show-account-deletion").addEventListener("click", (function(_this) { + return function() { + var e; + e = document.getElementById("delete-account-form"); + if (e.style.display !== "block") { + e.style.display = "block"; + return document.getElementById("delete-account").scrollIntoView(); + } else { + return e.style.display = "none"; + } + }; + })(this)); + document.getElementById("delete-account-button").addEventListener("click", (function(_this) { + return function() { + return _this.deleteAccount(); + }; + })(this)); + checkDeleteButton = (function(_this) { + return function() { + if (document.getElementById("delete-account-confirm").value === "DELETE MY ACCOUNT" && document.getElementById("delete-account-password").value.length > 0) { + return document.getElementById("delete-account-button").classList.add("enabled"); + } else { + return document.getElementById("delete-account-button").classList.remove("enabled"); + } + }; + })(this); document.getElementById("delete-account-confirm").addEventListener("keyup", checkDeleteButton); document.getElementById("delete-account-password").addEventListener("keyup", checkDeleteButton); } - this.nick_validator = new InputValidator(document.getElementById("usersetting-nick"), document.getElementById("usersetting-nick-button"), document.getElementById("usersetting-nick-error"), (value) => { - var nick; - nick = value[0]; - return this.app.client.sendRequest({ - name: "change_nick", - nick: nick - }, (msg) => { - if (msg.name === "error" && (msg.value != null)) { - this.nick_validator.reset(); - return this.nick_validator.showError(this.app.translator.get(msg.value)); - } else { - this.nick_validator.set(nick); - this.app.user.nick = nick; - document.getElementById("user-nick").innerText = nick; - return this.nickUpdated(); - } - }); - }); + this.nick_validator = new InputValidator(document.getElementById("usersetting-nick"), document.getElementById("usersetting-nick-button"), document.getElementById("usersetting-nick-error"), (function(_this) { + return function(value) { + var nick; + nick = value[0]; + return _this.app.client.sendRequest({ + name: "change_nick", + nick: nick + }, function(msg) { + if (msg.name === "error" && (msg.value != null)) { + _this.nick_validator.reset(); + return _this.nick_validator.showError(_this.app.translator.get(msg.value)); + } else { + _this.nick_validator.set(nick); + _this.app.user.nick = nick; + document.getElementById("user-nick").innerText = nick; + return _this.nickUpdated(); + } + }); + }; + })(this)); this.nick_validator.regex = RegexLib.nick; - this.email_validator = new InputValidator(document.getElementById("usersetting-email"), document.getElementById("usersetting-email-button"), document.getElementById("usersetting-email-error"), (value) => { - var email; - email = value[0]; - return this.app.client.sendRequest({ - name: "change_email", - email: email - }, (msg) => { - if (msg.name === "error" && (msg.value != null)) { - this.email_validator.reset(); - return this.email_validator.showError(this.app.translator.get(msg.value)); - } else { - this.email_validator.set(email); - return this.app.user.email = email; - } - }); - }); + this.email_validator = new InputValidator(document.getElementById("usersetting-email"), document.getElementById("usersetting-email-button"), document.getElementById("usersetting-email-error"), (function(_this) { + return function(value) { + var email; + email = value[0]; + return _this.app.client.sendRequest({ + name: "change_email", + email: email + }, function(msg) { + if (msg.name === "error" && (msg.value != null)) { + _this.email_validator.reset(); + return _this.email_validator.showError(_this.app.translator.get(msg.value)); + } else { + _this.email_validator.set(email); + return _this.app.user.email = email; + } + }); + }; + })(this)); this.email_validator.regex = RegexLib.email; this.sections = ["settings", "profile", "progress"]; this.initSections(); - document.getElementById("usersettings-profile").addEventListener("dragover", (event) => { - event.preventDefault(); - return document.querySelector("#usersettings-profile-image .fa-user-circle").classList.add("dragover"); - }); - //console.info event - document.getElementById("usersettings-profile").addEventListener("dragleave", (event) => { - event.preventDefault(); - return document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove("dragover"); - }); - //console.info event - document.getElementById("usersettings-profile").addEventListener("drop", (event) => { - var err, file, i, j, len, list, ref; - event.preventDefault(); - document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove("dragover"); - try { - list = []; - ref = event.dataTransfer.items; - for (j = 0, len = ref.length; j < len; j++) { - i = ref[j]; - list.push(i.getAsFile()); - } - if (list.length > 0) { - file = list[0]; - return this.profileImageDropped(file); - } - } catch (error) { - err = error; - return console.error(err); - } - }); - document.querySelector("#usersettings-profile-image").addEventListener("click", () => { - var input; - input = document.createElement("input"); - input.type = "file"; - input.addEventListener("change", (event) => { - var f, files; - files = event.target.files; - if (files.length >= 1) { - f = files[0]; - return this.profileImageDropped(f); + document.getElementById("usersettings-profile").addEventListener("dragover", (function(_this) { + return function(event) { + event.preventDefault(); + return document.querySelector("#usersettings-profile-image .fa-user-circle").classList.add("dragover"); + }; + })(this)); + document.getElementById("usersettings-profile").addEventListener("dragleave", (function(_this) { + return function(event) { + event.preventDefault(); + return document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove("dragover"); + }; + })(this)); + document.getElementById("usersettings-profile").addEventListener("drop", (function(_this) { + return function(event) { + var err, file, i, j, len, list, ref; + event.preventDefault(); + document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove("dragover"); + try { + list = []; + ref = event.dataTransfer.items; + for (j = 0, len = ref.length; j < len; j++) { + i = ref[j]; + list.push(i.getAsFile()); + } + if (list.length > 0) { + file = list[0]; + return _this.profileImageDropped(file); + } + } catch (error) { + err = error; + return console.error(err); } - }); - return input.click(); - }); - document.querySelector("#usersettings-profile .fa-times-circle").addEventListener("click", () => { - return this.removeProfileImage(); - }); - document.getElementById("usersettings-profile-description").addEventListener("input", () => { - return this.profileDescriptionChanged(); - }); + }; + })(this)); + document.querySelector("#usersettings-profile-image").addEventListener("click", (function(_this) { + return function() { + var input; + input = document.createElement("input"); + input.type = "file"; + input.addEventListener("change", function(event) { + var f, files; + files = event.target.files; + if (files.length >= 1) { + f = files[0]; + return _this.profileImageDropped(f); + } + }); + return input.click(); + }; + })(this)); + document.querySelector("#usersettings-profile .fa-times-circle").addEventListener("click", (function(_this) { + return function() { + return _this.removeProfileImage(); + }; + })(this)); + document.getElementById("usersettings-profile-description").addEventListener("input", (function(_this) { + return function() { + return _this.profileDescriptionChanged(); + }; + })(this)); if (window.ms_standalone) { document.getElementById("usersettings-menu-profile").style.display = "none"; } } - initSections() { + UserSettings.prototype.initSections = function() { var j, len, ref, results, s; ref = this.sections; results = []; for (j = 0, len = ref.length; j < len; j++) { s = ref[j]; - results.push(((s) => { - return document.getElementById(`usersettings-menu-${s}`).addEventListener("click", () => { - switch (s) { - case "settings": - return this.app.openUserSettings(); - case "profile": - return this.app.openUserProfile(); - case "progress": - return this.app.openUserProgress(); - } - }); - })(s)); + results.push((function(_this) { + return function(s) { + return document.getElementById("usersettings-menu-" + s).addEventListener("click", function() { + switch (s) { + case "settings": + return _this.app.openUserSettings(); + case "profile": + return _this.app.openUserProfile(); + case "progress": + return _this.app.openUserProgress(); + } + }); + }; + })(this)(s)); } return results; - } + }; - isSectionAllowed(section) { + UserSettings.prototype.isSectionAllowed = function(section) { if (this.app.user.flags.guest) { return section === "progress"; } else if (window.ms_standalone) { @@ -178,9 +215,9 @@ this.UserSettings = class UserSettings { } else { return true; } - } + }; - setSection(section) { + UserSettings.prototype.setSection = function(section) { var j, len, ref, s; if (!this.isSectionAllowed(section)) { section = "progress"; @@ -190,11 +227,11 @@ this.UserSettings = class UserSettings { for (j = 0, len = ref.length; j < len; j++) { s = ref[j]; if (s === section) { - document.getElementById(`usersettings-menu-${s}`).classList.add("selected"); - document.getElementById(`usersettings-${s}`).style.display = "block"; + document.getElementById("usersettings-menu-" + s).classList.add("selected"); + document.getElementById("usersettings-" + s).style.display = "block"; } else { - document.getElementById(`usersettings-menu-${s}`).classList.remove("selected"); - document.getElementById(`usersettings-${s}`).style.display = "none"; + document.getElementById("usersettings-menu-" + s).classList.remove("selected"); + document.getElementById("usersettings-" + s).style.display = "none"; } } if (this.current === "progress") { @@ -202,9 +239,9 @@ this.UserSettings = class UserSettings { this.app.user_progress.updateStatsPage(); } this.resetChangePassword(); - } + }; - update() { + UserSettings.prototype.update = function() { var account_type, div, icon, key, ref, span, translator, value; if (this.app.user.flags.guest) { this.hideChangePassword(); @@ -239,7 +276,7 @@ this.UserSettings = class UserSettings { } if (this.app.user.flags.tier) { icon = new Image; - icon.src = location.origin + `/microstudio/patreon/badges/sprites/${this.app.user.flags.tier}.png`; + icon.src = location.origin + ("/microstudio/patreon/badges/sprites/" + this.app.user.flags.tier + ".png"); icon.classList.add("pixelated"); icon.style = "width: 32px; height: 32px; vertical-align: middle ; margin-right: 5px"; div = document.getElementById("usersettings-account-type"); @@ -260,9 +297,9 @@ this.UserSettings = class UserSettings { return document.getElementById("delete-account").style.display = "block"; } } - } + }; - updateStorage() { + UserSettings.prototype.updateStorage = function() { var percent, str; percent = Math.floor(this.app.user.info.size / this.app.user.info.max_storage * 100); str = this.app.translator.get("[STORAGE] used of [MAX_STORAGE] ([PERCENT] %)"); @@ -270,25 +307,25 @@ this.UserSettings = class UserSettings { str = str.replace("[MAX_STORAGE]", this.app.appui.displayByteSize(this.app.user.info.max_storage)); str = str.replace("[PERCENT]", percent); return document.getElementById("usersettings-storage").innerText = str; - } + }; - nickUpdated() { - document.getElementById("user-public-page").href = location.origin.replace(".dev", ".io") + `/${this.app.user.nick}/`; - return document.getElementById("user-public-page").innerHTML = location.host.replace(".dev", ".io") + `/${this.app.user.nick} `; - } + UserSettings.prototype.nickUpdated = function() { + document.getElementById("user-public-page").href = location.origin.replace(".dev", ".io") + ("/" + this.app.user.nick + "/"); + return document.getElementById("user-public-page").innerHTML = location.host.replace(".dev", ".io") + ("/" + this.app.user.nick + " "); + }; - resendValidationEMail() { + UserSettings.prototype.resendValidationEMail = function() { return this.app.client.sendRequest({ name: "send_validation_mail" }, function(msg) { document.getElementById("resend-validation-email").style.display = "none"; return document.getElementById("validation-email-resent").style.display = "block"; }); - } + }; - changePassword() {} + UserSettings.prototype.changePassword = function() {}; - newsletterChange() { + UserSettings.prototype.newsletterChange = function() { var checked; checked = document.getElementById("subscribe-newsletter").checked; this.app.user.flags.newsletter = checked; @@ -296,9 +333,9 @@ this.UserSettings = class UserSettings { name: "change_newsletter", newsletter: checked }); - } + }; - experimentalChange() { + UserSettings.prototype.experimentalChange = function() { var checked; checked = document.getElementById("experimental-features").checked; this.app.user.flags.experimental = checked; @@ -306,13 +343,13 @@ this.UserSettings = class UserSettings { name: "change_experimental", experimental: checked }); - } + }; - nickChange() {} + UserSettings.prototype.nickChange = function() {}; - emailChange() {} + UserSettings.prototype.emailChange = function() {}; - openTranslationApp() { + UserSettings.prototype.openTranslationApp = function() { document.getElementById("usersettings").style.display = "none"; document.getElementById("translation-app").style.display = "block"; if (this.translation_app != null) { @@ -320,85 +357,94 @@ this.UserSettings = class UserSettings { } else { return this.translation_app = new TranslationApp(this.app); } - } + }; - closeTranslationApp() { + UserSettings.prototype.closeTranslationApp = function() { document.getElementById("usersettings").style.display = "block"; return document.getElementById("translation-app").style.display = "none"; - } + }; - profileImageDropped(file) { + UserSettings.prototype.profileImageDropped = function(file) { var img, reader; reader = new FileReader(); img = new Image; - reader.addEventListener("load", () => { - return img.src = reader.result; - }); + reader.addEventListener("load", (function(_this) { + return function() { + return img.src = reader.result; + }; + })(this)); reader.readAsDataURL(file); - //url = "data:application/javascript;base64,"+btoa(Audio.processor) - return img.onload = () => { - var canvas, context, h, r, w; - if (img.complete && img.width > 0 && img.height > 0) { - canvas = document.createElement("canvas"); - canvas.width = 128; - canvas.height = 128; - context = canvas.getContext("2d"); - if (img.width < 128 && img.height < 128) { - context.imageSmoothingEnabled = false; + return img.onload = (function(_this) { + return function() { + var canvas, context, h, r, w; + if (img.complete && img.width > 0 && img.height > 0) { + canvas = document.createElement("canvas"); + canvas.width = 128; + canvas.height = 128; + context = canvas.getContext("2d"); + if (img.width < 128 && img.height < 128) { + context.imageSmoothingEnabled = false; + } + w = img.width; + h = img.height; + r = Math.max(128 / w, 128 / h); + w *= r; + h *= r; + context.drawImage(img, 64 - w / 2, 64 - h / 2, w, h); + document.querySelector("#usersettings-profile-image img").src = canvas.toDataURL(); + document.querySelector("#usersettings-profile-image img").style.display = "block"; + return _this.app.client.sendRequest({ + name: "set_user_profile", + image: canvas.toDataURL().split(",")[1] + }, function() { + _this.app.user.flags.profile_image = true; + return _this.updateProfileImage(); + }); } - w = img.width; - h = img.height; - r = Math.max(128 / w, 128 / h); - w *= r; - h *= r; - context.drawImage(img, 64 - w / 2, 64 - h / 2, w, h); - document.querySelector("#usersettings-profile-image img").src = canvas.toDataURL(); - document.querySelector("#usersettings-profile-image img").style.display = "block"; - return this.app.client.sendRequest({ - name: "set_user_profile", - image: canvas.toDataURL().split(",")[1] - }, () => { - this.app.user.flags.profile_image = true; - return this.updateProfileImage(); - }); - } - }; - } + }; + })(this); + }; - removeProfileImage() { + UserSettings.prototype.removeProfileImage = function() { return this.app.client.sendRequest({ name: "set_user_profile", image: 0 - }, (msg) => { - this.app.user.flags.profile_image = false; - document.querySelector("#usersettings-profile-image img").style.display = "none"; - document.querySelector("#usersettings-profile-image img").src = ""; - return this.updateProfileImage(); - }); - } + }, (function(_this) { + return function(msg) { + _this.app.user.flags.profile_image = false; + document.querySelector("#usersettings-profile-image img").style.display = "none"; + document.querySelector("#usersettings-profile-image img").src = ""; + return _this.updateProfileImage(); + }; + })(this)); + }; - profileDescriptionChanged() { + UserSettings.prototype.profileDescriptionChanged = function() { if (this.description_timeout != null) { clearTimeout(this.description_timeout); } - return this.description_timeout = setTimeout((() => { - return this.saveProfileDescription(); - }), 2000); - } + return this.description_timeout = setTimeout(((function(_this) { + return function() { + return _this.saveProfileDescription(); + }; + })(this)), 2000); + }; - saveProfileDescription() { + UserSettings.prototype.saveProfileDescription = function() { return this.app.client.sendRequest({ name: "set_user_profile", description: document.getElementById("usersettings-profile-description").value - }, (msg) => {}); - } + }, (function(_this) { + return function(msg) {}; + })(this)); + }; - updateProfileImage() { + UserSettings.prototype.updateProfileImage = function() { if (this.app.user.flags.profile_image) { document.querySelector("#login-info img").style.display = "inline-block"; - document.querySelector("#login-info img").src = `/${this.app.user.nick}.png?v=${Date.now()}`; + document.querySelector("#login-info img").src = "/" + this.app.user.nick + ".png?v=" + (Date.now()); document.querySelector("#login-info i").style.display = "none"; - document.querySelector("#usersettings-profile-image img").src = `/${this.app.user.nick}.png?v=${Date.now()}`; + document.querySelector("#usersettings-profile-image img").src = "/" + this.app.user.nick + ".png?v=" + (Date.now()); document.querySelector("#usersettings-profile-image img").style.display = "block"; return document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "block"; } else { @@ -406,13 +452,13 @@ this.UserSettings = class UserSettings { document.querySelector("#login-info i").style.display = "inline-block"; return document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "none"; } - } + }; - resetChangePassword() { + UserSettings.prototype.resetChangePassword = function() { return this.setChangePasswordOpen(false); - } + }; - setChangePasswordOpen(open) { + UserSettings.prototype.setChangePasswordOpen = function(open) { var view; view = document.getElementById("usersetting-change-password-view"); if (open) { @@ -424,9 +470,9 @@ this.UserSettings = class UserSettings { document.getElementById("usersetting-password-new1").value = ""; document.getElementById("usersetting-password-new2").value = ""; return document.getElementById("usersetting-password-error").innerText = ""; - } + }; - changePasswordClick() { + UserSettings.prototype.changePasswordClick = function() { var current, open, pw1, pw2, view; view = document.getElementById("usersetting-change-password-view"); open = view.getBoundingClientRect().height > 0; @@ -439,16 +485,18 @@ this.UserSettings = class UserSettings { return this.app.client.sendRequest({ name: "change_password", current: current.value, - new: pw1.value - }, (msg) => { - console.info(msg); - if (msg.name === "error") { - return document.getElementById("usersetting-password-error").innerText = this.app.translator.get("Wrong Password"); - } else { - this.resetChangePassword(); - return this.app.appui.showNotification(this.app.translator.get("You have changed your password!")); - } - }); + "new": pw1.value + }, (function(_this) { + return function(msg) { + console.info(msg); + if (msg.name === "error") { + return document.getElementById("usersetting-password-error").innerText = _this.app.translator.get("Wrong Password"); + } else { + _this.resetChangePassword(); + return _this.app.appui.showNotification(_this.app.translator.get("You have changed your password!")); + } + }; + })(this)); } else { return document.getElementById("usersetting-password-error").innerText = this.app.translator.get("Passwords do not match"); } @@ -458,13 +506,13 @@ this.UserSettings = class UserSettings { } else { return this.setChangePasswordOpen(true); } - } + }; - hideChangePassword() { + UserSettings.prototype.hideChangePassword = function() { return document.getElementById("usersetting-change-password").style.display = "none"; - } + }; - deleteAccount() { + UserSettings.prototype.deleteAccount = function() { var password, text; if (!document.getElementById("delete-account-button").classList.contains("enabled")) { return; @@ -477,18 +525,22 @@ this.UserSettings = class UserSettings { name: "delete_account", confirm: text, password: password - }, (msg) => { - console.info(msg); - if (msg.name === "error") { - return document.getElementById("delete-account-error").innerText = this.app.translator.get(msg.error); - } else { - document.getElementById("delete-account-error").innerText = this.app.translator.get("Account Deleted Successfully. You will be redirected."); - return setTimeout((() => { - return window.location.href = "/"; - }), 4000); - } - }); + }, (function(_this) { + return function(msg) { + console.info(msg); + if (msg.name === "error") { + return document.getElementById("delete-account-error").innerText = _this.app.translator.get(msg.error); + } else { + document.getElementById("delete-account-error").innerText = _this.app.translator.get("Account Deleted Successfully. You will be redirected."); + return setTimeout((function() { + return window.location.href = "/"; + }), 4000); + } + }; + })(this)); } - } + }; + + return UserSettings; -}; +})(); diff --git a/static/js/util/confirm.js b/static/js/util/confirm.js index d25f0bf4..123e4527 100644 --- a/static/js/util/confirm.js +++ b/static/js/util/confirm.js @@ -7,21 +7,25 @@ this.ConfirmDialog = { } }; -this.ConfirmDialogWindow = class ConfirmDialogWindow { - constructor() { +this.ConfirmDialogWindow = (function() { + function ConfirmDialogWindow() { this.overlay = document.getElementById("confirm-message-overlay"); this.text = document.getElementById("confirm-message-text"); this.ok = document.getElementById("confirm-message-ok"); this.cancel = document.getElementById("confirm-message-cancel"); - this.ok.addEventListener("click", () => { - return this.okPressed(); - }); - this.cancel.addEventListener("click", () => { - return this.cancelPressed(); - }); + this.ok.addEventListener("click", (function(_this) { + return function() { + return _this.okPressed(); + }; + })(this)); + this.cancel.addEventListener("click", (function(_this) { + return function() { + return _this.cancelPressed(); + }; + })(this)); } - show(message, ok, cancel, callback1, dismiss1) { + ConfirmDialogWindow.prototype.show = function(message, ok, cancel, callback1, dismiss1) { this.callback = callback1; this.dismiss = dismiss1; if (document.fullscreenElement != null) { @@ -33,22 +37,24 @@ this.ConfirmDialogWindow = class ConfirmDialogWindow { this.ok.innerText = ok; this.cancel.innerText = cancel; return this.overlay.style.display = "block"; - } + }; - okPressed() { + ConfirmDialogWindow.prototype.okPressed = function() { this.overlay.style.display = "none"; if (this.callback != null) { this.callback(); return this.callback = null; } - } + }; - cancelPressed() { + ConfirmDialogWindow.prototype.cancelPressed = function() { this.overlay.style.display = "none"; if (this.dismiss != null) { this.dismiss(); return this.dismiss = null; } - } + }; -}; + return ConfirmDialogWindow; + +})(); diff --git a/static/js/util/diff.js b/static/js/util/diff.js index 7e6a348f..f48de09c 100644 --- a/static/js/util/diff.js +++ b/static/js/util/diff.js @@ -60,8 +60,7 @@ diff = function(before, after) { return [].concat(diff(before.slice(0, best_bi), after.slice(0, best_ai)), [ { type: "=", - data: after.slice(best_ai, - best_ai + best_length) + data: after.slice(best_ai, best_ai + best_length) } ], diff(before.slice(best_bi + best_length, before.length), after.slice(best_ai + best_length, after.length))); } diff --git a/static/js/util/splitbar.js b/static/js/util/splitbar.js index f27dffa8..49afaba4 100644 --- a/static/js/util/splitbar.js +++ b/static/js/util/splitbar.js @@ -1,7 +1,7 @@ -this.SplitBar = class SplitBar { - constructor(id, type = "horizontal") { +this.SplitBar = (function() { + function SplitBar(id, type) { this.id = id; - this.type = type; + this.type = type != null ? type : "horizontal"; this.element = document.getElementById(this.id); this.side1 = this.element.childNodes[0]; this.splitbar = this.element.childNodes[1]; @@ -10,38 +10,54 @@ this.SplitBar = class SplitBar { this.closed1 = false; this.closed2 = false; this.splitbar_size = 10; - this.splitbar.addEventListener("touchstart", (event) => { - if ((event.touches != null) && (event.touches[0] != null)) { - return this.startDrag(event.touches[0]); - } - }); - document.addEventListener("touchmove", (event) => { - if ((event.touches != null) && (event.touches[0] != null)) { - return this.drag(event.touches[0]); - } - }); - document.addEventListener("touchend", (event) => { - return this.stopDrag(); - }); - document.addEventListener("touchcancel", (event) => { - return this.stopDrag(); - }); - this.splitbar.addEventListener("mousedown", (event) => { - return this.startDrag(event); - }); - document.addEventListener("mousemove", (event) => { - return this.drag(event); - }); - document.addEventListener("mouseup", (event) => { - return this.stopDrag(event); - }); - window.addEventListener("resize", (event) => { - return this.update(); - }); + this.splitbar.addEventListener("touchstart", (function(_this) { + return function(event) { + if ((event.touches != null) && (event.touches[0] != null)) { + return _this.startDrag(event.touches[0]); + } + }; + })(this)); + document.addEventListener("touchmove", (function(_this) { + return function(event) { + if ((event.touches != null) && (event.touches[0] != null)) { + return _this.drag(event.touches[0]); + } + }; + })(this)); + document.addEventListener("touchend", (function(_this) { + return function(event) { + return _this.stopDrag(); + }; + })(this)); + document.addEventListener("touchcancel", (function(_this) { + return function(event) { + return _this.stopDrag(); + }; + })(this)); + this.splitbar.addEventListener("mousedown", (function(_this) { + return function(event) { + return _this.startDrag(event); + }; + })(this)); + document.addEventListener("mousemove", (function(_this) { + return function(event) { + return _this.drag(event); + }; + })(this)); + document.addEventListener("mouseup", (function(_this) { + return function(event) { + return _this.stopDrag(event); + }; + })(this)); + window.addEventListener("resize", (function(_this) { + return function(event) { + return _this.update(); + }; + })(this)); this.update(); } - startDrag(event) { + SplitBar.prototype.startDrag = function(event) { var e, i, len, list; this.dragging = true; this.drag_start_x = event.clientX; @@ -52,9 +68,9 @@ this.SplitBar = class SplitBar { e = list[i]; e.classList.add("ignoreMouseEvents"); } - } + }; - drag(event) { + SplitBar.prototype.drag = function(event) { var dx, dy, ns; if (this.dragging) { switch (this.type) { @@ -77,9 +93,9 @@ this.SplitBar = class SplitBar { } } } - } + }; - stopDrag() { + SplitBar.prototype.stopDrag = function() { var e, i, len, list; this.dragging = false; list = document.getElementsByTagName("iframe"); @@ -87,11 +103,14 @@ this.SplitBar = class SplitBar { e = list[i]; e.classList.remove("ignoreMouseEvents"); } - } + }; - initPosition(default_position = 50) { + SplitBar.prototype.initPosition = function(default_position) { var load; - load = localStorage.getItem(`splitbar-${this.id}`); + if (default_position == null) { + default_position = 50; + } + load = localStorage.getItem("splitbar-" + this.id); if ((load != null) && load >= 0 && load <= 100) { if (load >= 98 || load <= 2) { load = default_position; @@ -100,21 +119,24 @@ this.SplitBar = class SplitBar { } else { return this.setPosition(default_position, false); } - } + }; - setPosition(position, save = true) { + SplitBar.prototype.setPosition = function(position, save) { this.position = position; + if (save == null) { + save = true; + } this.update(); if (save) { return this.savePosition(); } - } + }; - savePosition() { - return localStorage.setItem(`splitbar-${this.id}`, this.position); - } + SplitBar.prototype.savePosition = function() { + return localStorage.setItem("splitbar-" + this.id, this.position); + }; - update() { + SplitBar.prototype.update = function() { var h, h1, h2, h3, w, w1, w2, w3; if (this.element.clientWidth === 0 || this.element.clientHeight === 0) { return; @@ -200,6 +222,8 @@ this.SplitBar = class SplitBar { this.splitbar.style.top = h1 + "px"; return this.side2.style.height = h3 + "px"; } - } + }; + + return SplitBar; -}; +})(); From 364901d054d3493a1a4f8083d7f8d14e99500c53 Mon Sep 17 00:00:00 2001 From: KingLauri200 Date: Wed, 20 Mar 2024 13:54:51 +0100 Subject: [PATCH 2/4] added scripts and requirements --- static/js/editor/editor.coffee | 11 ++++++----- static/js/editor/editor.js | 8 ++++++-- templates/home.pug | 3 +++ 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/static/js/editor/editor.coffee b/static/js/editor/editor.coffee index a2d7ed9b..4141bb66 100644 --- a/static/js/editor/editor.coffee +++ b/static/js/editor/editor.coffee @@ -15,19 +15,20 @@ class @Editor extends Manager @file_icon = "fa fa-file" @init() - + ace.require("ace/ext/language_tools"); + @editor = ace.edit "editor-view" @editor.$blockScrolling = Infinity @editor.setTheme("ace/theme/tomorrow_night_bright") @editor.getSession().setMode(@language.ace_mode) @editor.setFontSize("14px") - @editor.getSession().setOptions + @editor.setOptions tabSize: 2 useSoftTabs: true useWorker: false # disables lua autocorrection ; preserves syntax coloring - #enableBasicAutocompletion: true - #enableSnippets: true - #enableLiveAutocompletion: true + enableBasicAutocompletion: true + enableSnippets: true + enableLiveAutocompletion: true @update_delay = 50 @update_time = 0 diff --git a/static/js/editor/editor.js b/static/js/editor/editor.js index fa558c0c..f6c68611 100644 --- a/static/js/editor/editor.js +++ b/static/js/editor/editor.js @@ -19,15 +19,19 @@ this.Editor = (function(superClass) { this.update_list = "updateSourceList"; this.file_icon = "fa fa-file"; this.init(); + ace.require("ace/ext/language_tools"); this.editor = ace.edit("editor-view"); this.editor.$blockScrolling = 2e308; this.editor.setTheme("ace/theme/tomorrow_night_bright"); this.editor.getSession().setMode(this.language.ace_mode); this.editor.setFontSize("14px"); - this.editor.getSession().setOptions({ + this.editor.setOptions({ tabSize: 2, useSoftTabs: true, - useWorker: false + useWorker: false, + enableBasicAutocompletion: true, + enableSnippets: true, + enableLiveAutocompletion: true }); this.update_delay = 50; this.update_time = 0; diff --git a/templates/home.pug b/templates/home.pug index 3d25c7da..08dbb871 100644 --- a/templates/home.pug +++ b/templates/home.pug @@ -56,6 +56,9 @@ html(lang=language) script(src="/lib/jquery/jquery.js") script(src="/lib/jquery-ui/jquery-ui.min.js") script(src="/lib/ace/ace.js") + script(src="/lib/ace/ext-searchbox.js") + script(src="/lib/ace/ext-language_tools.js") + script(src="/lib/ace/mode-microscript.js") script(src="/lib/ace/mode-microscript2.js") script(src="/lib/ace/mode-markdown.js") From e6b2d0730625e7a2e14c9c23d4426605ef94a18e Mon Sep 17 00:00:00 2001 From: KingLauri200 Date: Thu, 21 Mar 2024 17:01:37 +0100 Subject: [PATCH 3/4] added CustomCompleter for extended completions like "screen.drawText()" --- static/js/editor/editor.coffee | 16 +++++++++++++++- static/js/editor/editor.js | 23 ++++++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/static/js/editor/editor.coffee b/static/js/editor/editor.coffee index 4141bb66..7297bfc3 100644 --- a/static/js/editor/editor.coffee +++ b/static/js/editor/editor.coffee @@ -16,12 +16,26 @@ class @Editor extends Manager @init() ace.require("ace/ext/language_tools"); - + @editor = ace.edit "editor-view" @editor.$blockScrolling = Infinity @editor.setTheme("ace/theme/tomorrow_night_bright") @editor.getSession().setMode(@language.ace_mode) @editor.setFontSize("14px") + + customCompleter = + getCompletions: (editor, session, pos, prefix, callback) -> + state = session.getState(pos.row) + completions = session.$mode.getCompletions(state, session, pos, prefix) + myCompletions = [ + { value: 'screen.drawText()', score: 1, meta: 'draw text' } + { value: 'screen.drawRect()', score: 1, meta: 'draw rect' } + ] + completions = completions.concat(myCompletions) + callback(null, completions) + + ace.require("ace/ext/language_tools").addCompleter(customCompleter) + @editor.setOptions tabSize: 2 useSoftTabs: true diff --git a/static/js/editor/editor.js b/static/js/editor/editor.js index f6c68611..d986d3e2 100644 --- a/static/js/editor/editor.js +++ b/static/js/editor/editor.js @@ -6,7 +6,7 @@ this.Editor = (function(superClass) { extend(Editor, superClass); function Editor(app) { - var f; + var customCompleter, f; Editor.__super__.constructor.call(this, app); this.language = this.app.languages.microscript; this.folder = "ms"; @@ -25,6 +25,27 @@ this.Editor = (function(superClass) { this.editor.setTheme("ace/theme/tomorrow_night_bright"); this.editor.getSession().setMode(this.language.ace_mode); this.editor.setFontSize("14px"); + customCompleter = { + getCompletions: function(editor, session, pos, prefix, callback) { + var completions, myCompletions, state; + state = session.getState(pos.row); + completions = session.$mode.getCompletions(state, session, pos, prefix); + myCompletions = [ + { + value: 'screen.drawText()', + score: 1, + meta: 'draw text' + }, { + value: 'screen.drawRect()', + score: 1, + meta: 'draw rect' + } + ]; + completions = completions.concat(myCompletions); + return callback(null, completions); + } + }; + ace.require("ace/ext/language_tools").addCompleter(customCompleter); this.editor.setOptions({ tabSize: 2, useSoftTabs: true, From 63ff471bce659a561306bd8e02bde83193505052 Mon Sep 17 00:00:00 2001 From: KingLauri200 Date: Fri, 22 Mar 2024 11:56:34 +0100 Subject: [PATCH 4/4] some more stuff --- static/js/editor/editor.coffee | 48 +++++++++++++++++++++++++ static/js/editor/editor.js | 66 +++++++++++++++++++++++++++++++++- 2 files changed, 113 insertions(+), 1 deletion(-) diff --git a/static/js/editor/editor.coffee b/static/js/editor/editor.coffee index 7297bfc3..eb30b6e1 100644 --- a/static/js/editor/editor.coffee +++ b/static/js/editor/editor.coffee @@ -16,6 +16,8 @@ class @Editor extends Manager @init() ace.require("ace/ext/language_tools"); + acorn = require("acorn") + fs = require("fs") @editor = ace.edit "editor-view" @editor.$blockScrolling = Infinity @@ -23,6 +25,52 @@ class @Editor extends Manager @editor.getSession().setMode(@language.ace_mode) @editor.setFontSize("14px") + analyzeFile = (filePath) -> + # Dateiinhalt lesen + content = fs.readFileSync(filePath, "utf8") + + # JavaScript-Code mit acorn analysieren, um Variablen zu extrahieren + ast = acorn.parse(content, { ecmaVersion: 11, sourceType: "module" }) + + # Array für gefundene Variablen initialisieren + variables = [] + + # AST durchlaufen und Variablen extrahieren + traverseAST(ast, (node) -> + if node.type is "VariableDeclaration" + node.declarations.forEach (declaration) -> + variables.push(declaration.id.name) + ) + + return variables + + traverseAST = (node, callback) -> + callback(node) + for prop, value of node + if typeof value is "object" and value + if Array.isArray(value) + for item in value + if typeof item is "object" and item + traverseAST(item, callback) + else + traverseAST(value, callback) + + searchVariablesInFiles = (directory) -> + allVariables = [] + # Alle Dateien im Verzeichnis durchsuchen + files = fs.readdirSync(directory) + files.forEach (file) -> + filePath = directory + "/" + file + # Nur JavaScript-Dateien betrachten + if file.endsWith(".js") + # Variablen in der Datei analysieren und extrahieren + variables = analyzeFile(filePath) + allVariables = allVariables.concat(variables) + return allVariables + + directory = "pfad/zum/deinem/projekt" + #allVariables = searchVariablesInFiles(directory) + customCompleter = getCompletions: (editor, session, pos, prefix, callback) -> state = session.getState(pos.row) diff --git a/static/js/editor/editor.js b/static/js/editor/editor.js index d986d3e2..b3ec435a 100644 --- a/static/js/editor/editor.js +++ b/static/js/editor/editor.js @@ -6,7 +6,7 @@ this.Editor = (function(superClass) { extend(Editor, superClass); function Editor(app) { - var customCompleter, f; + var acorn, analyzeFile, customCompleter, directory, f, fs, searchVariablesInFiles, traverseAST; Editor.__super__.constructor.call(this, app); this.language = this.app.languages.microscript; this.folder = "ms"; @@ -20,11 +20,75 @@ this.Editor = (function(superClass) { this.file_icon = "fa fa-file"; this.init(); ace.require("ace/ext/language_tools"); + acorn = require("acorn"); + fs = require("fs"); this.editor = ace.edit("editor-view"); this.editor.$blockScrolling = 2e308; this.editor.setTheme("ace/theme/tomorrow_night_bright"); this.editor.getSession().setMode(this.language.ace_mode); this.editor.setFontSize("14px"); + analyzeFile = function(filePath) { + var ast, content, variables; + content = fs.readFileSync(filePath, "utf8"); + ast = acorn.parse(content, { + ecmaVersion: 11, + sourceType: "module" + }); + variables = []; + traverseAST(ast, function(node) { + if (node.type === "VariableDeclaration") { + return node.declarations.forEach(function(declaration) { + return variables.push(declaration.id.name); + }); + } + }); + return variables; + }; + traverseAST = function(node, callback) { + var item, prop, results, value; + callback(node); + results = []; + for (prop in node) { + value = node[prop]; + if (typeof value === "object" && value) { + if (Array.isArray(value)) { + results.push((function() { + var j, len, results1; + results1 = []; + for (j = 0, len = value.length; j < len; j++) { + item = value[j]; + if (typeof item === "object" && item) { + results1.push(traverseAST(item, callback)); + } else { + results1.push(void 0); + } + } + return results1; + })()); + } else { + results.push(traverseAST(value, callback)); + } + } else { + results.push(void 0); + } + } + return results; + }; + searchVariablesInFiles = function(directory) { + var allVariables, files; + allVariables = []; + files = fs.readdirSync(directory); + files.forEach(function(file) { + var filePath, variables; + filePath = directory + "/" + file; + if (file.endsWith(".js")) { + variables = analyzeFile(filePath); + return allVariables = allVariables.concat(variables); + } + }); + return allVariables; + }; + directory = "pfad/zum/deinem/projekt"; customCompleter = { getCompletions: function(editor, session, pos, prefix, callback) { var completions, myCompletions, state;