<commit_before>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw) {
      function getURL() {
        var url = API_URL + path;
        return url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime();
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL());
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      };
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        var command = username ? "/users/"+username : "/user";

        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(path, cb) {
        _request("GET", repoPath + "/contents", { path: path }, cb);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path; });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<commit_msg>fixed bug with getting current users info<commit_after>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw) {
      function getURL() {
        var url = API_URL + path;
        return url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime();
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL());
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      };
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        var command = username ? "/users/"+username : "/user";

        _request("GET", command, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(path, cb) {
        _request("GET", repoPath + "/contents", { path: path }, cb);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path; });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<|endoftext|>


<commit_before>window.l2 = window.l2 || {};

(function () {

	var handlers = {};
	var globalHandlers = [];

	var notifyPropertyChanged = function (property, value) {
		if (handlers[property])
			handlers[property].forEach(function (handler) {
				handler(value);
			});
		globalHandlers.forEach(function (handler) {
			handler(property, value);
		});
	};

	var addHandler = function (property, handler) {
		if (!handlers[property])
			handlers[property] = [];
		handlers[property].push(handler);
	};

	var addGlobalHandler = function (handler) {
		globalHandlers.push(handler);
	};

	var getValue = function (model) {

	};

	var setValue = function (model, value) {
		var obj = l2.model;
		var parts = model.split('.');
		for (var i = 0; i < parts.length - 1; i++)
			obj = obj[parts[i]];
		if (obj[parts[parts.length - 1]] === undefined)
			throw 'Invalid property';
		obj[parts[parts.length - 1]] = value;
	};

	var L2Item = function (itemType) {
		var grade = null;
		Object.defineProperty(this, 'grade', {
			get: function () { return grade; },
			set: function (value) {
				value = value.toLowerCase();
				if (['d', 'c', 'b', 'a', 's', 's80', 's84'].indexOf(value) >= 0)
					grade = value;
				else
					if (value == 'none')
						grade = null;
					else
						throw 'Invalid grade';
				notifyPropertyChanged(itemType + '.grade', grade);
			}
		});
		var enchant = 0;
		Object.defineProperty(this, 'enchant', {
			get: function () { return enchant; },
			set: function (value) {
				if (value == null || value == '')
					enchant = 0;
				else {
					var intVal = parseInt(value);
					if (!isNaN(intVal) && intVal.toString() == value.toString() && intVal >= 0)
						enchant = intVal;
					else
						throw 'Invalid enchant';
				}
				notifyPropertyChanged(itemType + '.enchant', enchant);
			}
		});
		var id = null;
		Object.defineProperty(this, 'id', {
			get: function () { return id; },
			set: function (value) {
				if (value == null || value == '')
					id = null;
				else {
					var intVal = parseInt(value);
					if (!isNaN(intVal) && intVal.toString() == value.toString())
						id = intVal;
					else
						throw 'Invalid id';
				}
				notifyPropertyChanged(itemType + '.id', id);
			}
		});
		Object.defineProperty(this, 'item', {
			get: function () {
				if (this.id)
					return l2.data.tools.getItem(this.id);
				else
					return null;
			}
		});
		var canEnchant = false;
		Object.defineProperty(this, 'canEnchant', {
			get: function () { return canEnchant; },
			set: function (value) {
				canEnchant = !!value;
				if (!canEnchant)
					this.enchant = 0;
				notifyPropertyChanged(itemType + '.canEnchant', canEnchant);
			}
		});
		var disabled = false;
		Object.defineProperty(this, 'disabled', {
			get: function () { return disabled; },
			set: function (value) {
				disabled = !!value;
				if (disabled) {
					this.id = null;
					this.enchant = 0;
				}
				notifyPropertyChanged(itemType + '.disabled', disabled);
			}
		});
	};

	var L2Weapon = function () {
		L2Item.call(this, 'weapon');

		var type = 'bigsword';
		Object.defineProperty(this, 'type', {
			get: function () { return type; },
			set: function (value) {
				type = value.toLowerCase();
				notifyPropertyChanged('weapon.type', type);
			}
		});
	};

	var L2TatooPart = function (part) {
		var stat = null;
		Object.defineProperty(this, 'stat', {
			get: function () { return stat; },
			set: function (value) {
				stat = value;
				notifyPropertyChanged(part + '.stat', stat);
			}
		});
		var val = null;
		Object.defineProperty(this, 'value', {
			get: function () { return val; },
			set: function (value) {
				val = value;
				notifyPropertyChanged(part + '.value', val);
			}
		});
		var min = null;
		Object.defineProperty(this, 'minValue', {
			get: function () { return min; },
			set: function (value) {
				min = value;
				notifyPropertyChanged(part + '.minValue', min);
			}
		});
		var max = null;
		Object.defineProperty(this, 'maxValue', {
			get: function () { return max; },
			set: function (value) {
				max = value;
				notifyPropertyChanged(part + '.maxValue', max);
			}
		});
		var enableStr = false;
		Object.defineProperty(this, 'enableStr', {
			get: function () { return enableStr; },
			set: function (value) {
				enableStr = value;
				notifyPropertyChanged(part + '.enableStr', enableStr);
			}
		});
		var enableDex = false;
		Object.defineProperty(this, 'enableDex', {
			get: function () { return enableDex; },
			set: function (value) {
				enableDex = value;
				notifyPropertyChanged(part + '.enableDex', enableDex);
			}
		});
		var enableCon = false;
		Object.defineProperty(this, 'enableCon', {
			get: function () { return enableCon; },
			set: function (value) {
				enableCon = value;
				notifyPropertyChanged(part + '.enableCon', enableCon);
			}
		});
		var enableInt = false;
		Object.defineProperty(this, 'enableInt', {
			get: function () { return enableInt; },
			set: function (value) {
				enableInt = value;
				notifyPropertyChanged(part + '.enableInt', enableInt);
			}
		});
		var enableWit = false;
		Object.defineProperty(this, 'enableWit', {
			get: function () { return enableWit; },
			set: function (value) {
				enableWit = value;
				notifyPropertyChanged(part + '.enableWit', enableWit);
			}
		});
		var enableMen = false;
		Object.defineProperty(this, 'enableMen', {
			get: function () { return enableMen; },
			set: function (value) {
				enableMen = value;
				notifyPropertyChanged(part + '.enableMen', enableMen);
			}
		});
	};

	var L2Tatoo = function (slot) {
		this.add = new L2TatooPart(slot + '.add');
		this.sub = new L2TatooPart(slot + '.sub');
		var enabled = true;
		Object.defineProperty(this, 'enabled', {
			get: function () { return enabled; },
			set: function (value) {
				enabled = value == 'false' ? false : value;
				if (!enabled)
					this.checked = false;
				notifyPropertyChanged(slot + '.enabled', enabled);
			}
		});
		var checked = false;
		Object.defineProperty(this, 'checked', {
			get: function () { return checked; },
			set: function (value) {
				checked = value == 'false' ? false : value;
				notifyPropertyChanged(slot + '.checked', checked);
			}
		});
	};

	var L2SkillList = function (type) {

	};

	window.l2.model = {
		addHandler: addHandler,
		addGlobalHandler: addGlobalHandler,
		getValue: getValue,
		setValue: setValue,
		weapon: new L2Weapon(),
		shield: new L2Item('shield'),
		helmet: new L2Item('helmet'),
		bodyUpper: new L2Item('bodyUpper'),
		bodyLower: new L2Item('bodyLower'),
		gloves: new L2Item('gloves'),
		boots: new L2Item('boots'),
		underwear: new L2Item('underwear'),
		belt: new L2Item('belt'),
		necklace: new L2Item('necklace'),
		earring1: new L2Item('earring1'),
		earring2: new L2Item('earring2'),
		ring1: new L2Item('ring1'),
		ring2: new L2Item('ring2'),
		tatto1: new L2Tatoo('tatto1'),
		tatto2: new L2Tatoo('tatto2'),
		tatto3: new L2Tatoo('tatto3'),
		selfBuffs: {}
	};

	var addModel = function (property, getter, setter) {
		Object.defineProperty(window.l2.model, property, {
			get: getter,
			set: setter
		});
	};

	var raceId = 0;
	addModel('raceId', function () { return raceId; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 0 && intVal <= 5) {
			raceId = intVal;
			notifyPropertyChanged('raceId', raceId);
		} else
			throw 'Invalid raceId';
	});

	var prof = 0;
	addModel('prof', function () { return prof; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 0 && intVal <= 3) {
			prof = intVal;
			notifyPropertyChanged('prof', prof);
		} else
			throw 'Invalid prof';
	});

	var classId = 0;
	addModel('classId', function () { return classId; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 0) {
			classId = intVal;
			notifyPropertyChanged('classId', classId);
		} else
			throw 'Invalid classId';
	});

	var level = 0;
	addModel('level', function () { return level; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 1 && intVal <= 85) {
			level = intVal;
			notifyPropertyChanged('level', level);
		} else
			throw 'Invalid level';
	});

	var hpPercent = 100;
	addModel('hpPercent', function () { return hpPercent; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && [30, 60, 100].indexOf(intVal) >= 0) {
			hpPercent = intVal;
			notifyPropertyChanged('hpPercent', hpPercent);
		} else
			throw 'Invalid hpPercent';
	});

	var position = 'front';
	addModel('position', function () { return position; }, function (value) {
		if (['front', 'behind', 'side'].indexOf(value) >= 0) {
			position = value;
			notifyPropertyChanged('position', position);
		} else
			throw 'Invalid position';
	});

	var setGrade = null;
	addModel('setGrade', function () { return setGrade; }, function (value) {
		if (['d', 'c', 'b', 'a', 's', 's80', 's84'].indexOf(value) >= 0)
			setGrade = value;
		else
			if (value == 'none')
				setGrade = null;
			else
				throw 'Invalid grade';
		notifyPropertyChanged('setGrade', setGrade);
	});

})();<commit_msg>mini save<commit_after>window.l2 = window.l2 || {};

(function () {

	var handlers = {};
	var globalHandlers = [];

	var notifyPropertyChanged = function (property, value) {
		if (handlers[property])
			handlers[property].forEach(function (handler) {
				handler(value);
			});
		globalHandlers.forEach(function (handler) {
			handler(property, value);
		});
	};

	var addHandler = function (property, handler) {
		if (!handlers[property])
			handlers[property] = [];
		handlers[property].push(handler);
	};

	var addGlobalHandler = function (handler) {
		globalHandlers.push(handler);
	};

	var getValue = function (model) {

	};

	var setValue = function (model, value) {
		var obj = l2.model;
		var parts = model.split('.');
		for (var i = 0; i < parts.length - 1; i++)
			obj = obj[parts[i]];
		if (obj[parts[parts.length - 1]] === undefined)
			throw 'Invalid property';
		obj[parts[parts.length - 1]] = value;
	};

	var L2Item = function (itemType) {
		var grade = null;
		Object.defineProperty(this, 'grade', {
			get: function () { return grade; },
			set: function (value) {
				value = value.toLowerCase();
				if (['d', 'c', 'b', 'a', 's', 's80', 's84'].indexOf(value) >= 0)
					grade = value;
				else
					if (value == 'none')
						grade = null;
					else
						throw 'Invalid grade';
				notifyPropertyChanged(itemType + '.grade', grade);
			}
		});
		var enchant = 0;
		Object.defineProperty(this, 'enchant', {
			get: function () { return enchant; },
			set: function (value) {
				if (value == null || value == '')
					enchant = 0;
				else {
					var intVal = parseInt(value);
					if (!isNaN(intVal) && intVal.toString() == value.toString() && intVal >= 0)
						enchant = intVal;
					else
						throw 'Invalid enchant';
				}
				notifyPropertyChanged(itemType + '.enchant', enchant);
			}
		});
		var id = null;
		Object.defineProperty(this, 'id', {
			get: function () { return id; },
			set: function (value) {
				if (value == null || value == '')
					id = null;
				else {
					var intVal = parseInt(value);
					if (!isNaN(intVal) && intVal.toString() == value.toString())
						id = intVal;
					else
						throw 'Invalid id';
				}
				notifyPropertyChanged(itemType + '.id', id);
			}
		});
		Object.defineProperty(this, 'item', {
			get: function () {
				if (this.id)
					return l2.data.tools.getItem(this.id);
				else
					return null;
			}
		});
		var canEnchant = false;
		Object.defineProperty(this, 'canEnchant', {
			get: function () { return canEnchant; },
			set: function (value) {
				canEnchant = !!value;
				if (!canEnchant)
					this.enchant = 0;
				notifyPropertyChanged(itemType + '.canEnchant', canEnchant);
			}
		});
		var disabled = false;
		Object.defineProperty(this, 'disabled', {
			get: function () { return disabled; },
			set: function (value) {
				disabled = !!value;
				if (disabled) {
					this.id = null;
					this.enchant = 0;
				}
				notifyPropertyChanged(itemType + '.disabled', disabled);
			}
		});
	};

	var L2Weapon = function () {
		L2Item.call(this, 'weapon');

		var type = 'bigsword';
		Object.defineProperty(this, 'type', {
			get: function () { return type; },
			set: function (value) {
				type = value.toLowerCase();
				notifyPropertyChanged('weapon.type', type);
			}
		});
	};

	var L2TatooPart = function (part) {
		var stat = null;
		Object.defineProperty(this, 'stat', {
			get: function () { return stat; },
			set: function (value) {
				stat = value;
				notifyPropertyChanged(part + '.stat', stat);
			}
		});
		var val = null;
		Object.defineProperty(this, 'value', {
			get: function () { return val; },
			set: function (value) {
				val = value;
				notifyPropertyChanged(part + '.value', val);
			}
		});
		var min = null;
		Object.defineProperty(this, 'minValue', {
			get: function () { return min; },
			set: function (value) {
				min = value;
				notifyPropertyChanged(part + '.minValue', min);
			}
		});
		var max = null;
		Object.defineProperty(this, 'maxValue', {
			get: function () { return max; },
			set: function (value) {
				max = value;
				notifyPropertyChanged(part + '.maxValue', max);
			}
		});
		var enableStr = false;
		Object.defineProperty(this, 'enableStr', {
			get: function () { return enableStr; },
			set: function (value) {
				enableStr = value;
				notifyPropertyChanged(part + '.enableStr', enableStr);
			}
		});
		var enableDex = false;
		Object.defineProperty(this, 'enableDex', {
			get: function () { return enableDex; },
			set: function (value) {
				enableDex = value;
				notifyPropertyChanged(part + '.enableDex', enableDex);
			}
		});
		var enableCon = false;
		Object.defineProperty(this, 'enableCon', {
			get: function () { return enableCon; },
			set: function (value) {
				enableCon = value;
				notifyPropertyChanged(part + '.enableCon', enableCon);
			}
		});
		var enableInt = false;
		Object.defineProperty(this, 'enableInt', {
			get: function () { return enableInt; },
			set: function (value) {
				enableInt = value;
				notifyPropertyChanged(part + '.enableInt', enableInt);
			}
		});
		var enableWit = false;
		Object.defineProperty(this, 'enableWit', {
			get: function () { return enableWit; },
			set: function (value) {
				enableWit = value;
				notifyPropertyChanged(part + '.enableWit', enableWit);
			}
		});
		var enableMen = false;
		Object.defineProperty(this, 'enableMen', {
			get: function () { return enableMen; },
			set: function (value) {
				enableMen = value;
				notifyPropertyChanged(part + '.enableMen', enableMen);
			}
		});
	};

	var L2Tatoo = function (slot) {
		this.add = new L2TatooPart(slot + '.add');
		this.sub = new L2TatooPart(slot + '.sub');
		var enabled = true;
		Object.defineProperty(this, 'enabled', {
			get: function () { return enabled; },
			set: function (value) {
				enabled = value == 'false' ? false : value;
				if (!enabled)
					this.checked = false;
				notifyPropertyChanged(slot + '.enabled', enabled);
			}
		});
		var checked = false;
		Object.defineProperty(this, 'checked', {
			get: function () { return checked; },
			set: function (value) {
				checked = value == 'false' ? false : value;
				notifyPropertyChanged(slot + '.checked', checked);
			}
		});
	};

	var L2SkillList = function (type) {

	};

	window.l2.model = {
		addHandler: addHandler,
		addGlobalHandler: addGlobalHandler,
		getValue: getValue,
		setValue: setValue,
		weapon: new L2Weapon(),
		shield: new L2Item('shield'),
		helmet: new L2Item('helmet'),
		bodyUpper: new L2Item('bodyUpper'),
		bodyLower: new L2Item('bodyLower'),
		gloves: new L2Item('gloves'),
		boots: new L2Item('boots'),
		underwear: new L2Item('underwear'),
		belt: new L2Item('belt'),
		necklace: new L2Item('necklace'),
		earring1: new L2Item('earring1'),
		earring2: new L2Item('earring2'),
		ring1: new L2Item('ring1'),
		ring2: new L2Item('ring2'),
		tatto1: new L2Tatoo('tatto1'),
		tatto2: new L2Tatoo('tatto2'),
		tatto3: new L2Tatoo('tatto3'),
		selfBuffs: {}
	};

	var addModel = function (property, getter, setter) {
		Object.defineProperty(window.l2.model, property, {
			get: getter,
			set: setter
		});
	};

	var raceId = 0;
	addModel('raceId', function () { return raceId; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 0 && intVal <= 5) {
			raceId = intVal;
			notifyPropertyChanged('raceId', raceId);
		} else
			throw 'Invalid raceId';
	});

	var prof = 0;
	addModel('prof', function () { return prof; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 0 && intVal <= 3) {
			prof = intVal;
			notifyPropertyChanged('prof', prof);
		} else
			throw 'Invalid prof';
	});

	var classId = 0;
	addModel('classId', function () { return classId; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 0) {
			classId = intVal;
			notifyPropertyChanged('classId', classId);
		} else
			throw 'Invalid classId';
	});

	var level = 0;
	addModel('level', function () { return level; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && intVal >= 1 && intVal <= 85) {
			level = intVal;
			notifyPropertyChanged('level', level);
		} else
			throw 'Invalid level';
	});

	var hpPercent = 100;
	addModel('hpPercent', function () { return hpPercent; }, function (value) {
		var intVal = parseInt(value);
		if (!isNaN(intVal) && [30, 60, 100].indexOf(intVal) >= 0) {
			hpPercent = intVal;
			notifyPropertyChanged('hpPercent', hpPercent);
		} else
			throw 'Invalid hpPercent';
	});

	var position = 'front';
	addModel('position', function () { return position; }, function (value) {
		if (['front', 'behind', 'side'].indexOf(value) >= 0) {
			position = value;
			notifyPropertyChanged('position', position);
		} else
			throw 'Invalid position';
	});

	var setGrade = null;
	addModel('setGrade', function () { return setGrade; }, function (value) {
		if (['d', 'c', 'b', 'a', 's', 's80', 's84'].indexOf(value) >= 0)
			setGrade = value;
		else
			if (value == 'none')
				setGrade = null;
			else
				throw 'Invalid grade';
		notifyPropertyChanged('setGrade', setGrade);
	});

})();<|endoftext|>


<commit_before>import React, { Component } from 'react';
import moment from 'moment';

import './css/styles.css';

import sampleActivities from './sampleActivities';

class App extends Component {

  constructor(props) {
    super(props);

    this.loadSampleActivities = this.loadSampleActivities.bind(this);
  }

  state = {
    activitiesByTimestamp: {},
    activityTimestamps: [],
    currentDay: moment().startOf('day')
  };

  renderActivity(timestamp,activity) {
    return (

{moment(+timestamp).format('MMMM DD, YYYY')}

{activity.description}

    )
  }

  loadSampleActivities() {
    this.setState({
      activityTimestamps: Object.keys(sampleActivities),
      activitiesByTimestamp: sampleActivities,
    })
  }

  addActivity(text) {
    const now = moment().format('x');
    this.setState({
      activitiesByTimestamp: {
        ...this.state.activitiesByTimestamp,
        [now]: { text },
      },
      activityTimestamps: [...this.state.activityTimestamps, now]
    })
  }

  choosePreviousDay() {
    this.setState({
      currentDay: this.state.currentDay.subtract(1, 'day')
    })
  }

  chooseNextDay() {
    this.setState({
      currentDay: this.state.currentDay.add(1, 'day')
    })
  }

  getCurrentDayTimestamps() {
    const { currentDay, activityTimestamps } = this.state;
    const start = +currentDay.startOf('day');
    const end = +currentDay.endOf('day');

    return activityTimestamps
      .filter( timestamp => start <= +timestamp && timestamp <= end)
  }

  render() {
    const { activitiesByTimestamp, currentDay } = this.state;
    return (

            Today daily tracker

          current day: {currentDay.format('MMMM DD, YYYY')}

            <button onClick={this.loadSampleActivities}>Load sample activities</button>

        {
          this.getCurrentDayTimestamps()
            .sort()
            .reverse()
            .map(timestamp => this.renderActivity(timestamp, activitiesByTimestamp[timestamp]))
        }

    );
  }
}

export default App;
<commit_msg>Change addActivity to receive entire object<commit_after>import React, { Component } from 'react';
import moment from 'moment';

import './css/styles.css';

import sampleActivities from './sampleActivities';

class App extends Component {

  constructor(props) {
    super(props);

    this.loadSampleActivities = this.loadSampleActivities.bind(this);
  }

  state = {
    activitiesByTimestamp: {},
    activityTimestamps: [],
    currentDay: moment().startOf('day')
  };

  renderActivity(timestamp,activity) {
    return (

{moment(+timestamp).format('MMMM DD, YYYY')}

{activity.description}

    )
  }

  loadSampleActivities() {
    this.setState({
      activityTimestamps: Object.keys(sampleActivities),
      activitiesByTimestamp: sampleActivities,
    })
  }

  addActivity(activity) {
    const now = moment().format('x');
    this.setState({
      activitiesByTimestamp: {
        ...this.state.activitiesByTimestamp,
        [now]: activity,
      },
      activityTimestamps: [...this.state.activityTimestamps, now]
    })
  }

  choosePreviousDay() {
    this.setState({
      currentDay: this.state.currentDay.subtract(1, 'day')
    })
  }

  chooseNextDay() {
    this.setState({
      currentDay: this.state.currentDay.add(1, 'day')
    })
  }

  getCurrentDayTimestamps() {
    const { currentDay, activityTimestamps } = this.state;
    const start = +currentDay.startOf('day');
    const end = +currentDay.endOf('day');

    return activityTimestamps
      .filter( timestamp => start <= +timestamp && timestamp <= end)
  }

  render() {
    const { activitiesByTimestamp, currentDay } = this.state;
    return (

            Today daily tracker

          current day: {currentDay.format('MMMM DD, YYYY')}

            <button onClick={this.loadSampleActivities}>Load sample activities</button>

        {
          this.getCurrentDayTimestamps()
            .sort()
            .reverse()
            .map(timestamp => this.renderActivity(timestamp, activitiesByTimestamp[timestamp]))
        }

    );
  }
}

export default App;
<|endoftext|>


<commit_before>var gitHub = {};

/*
 * Make sure that github is logged in before calling callback
 * if there is an error, call errorCallback with an error param
 */
gitHub.ensureLogin = function(callback, errorCallback) {
    // Determine if there is a current oauth session
    var session = hello('github').getAuthResponse();
    var currentTime = (new Date()).getTime() / 1000;
    var online = session && session.access_token && session.expires > currentTime;

    if(online) {
        // If there is an active session, perform the callback
        callback();
    }
    else {
        // Otherwise, login
        var options = {};
        options.scope = ['user', 'repo', 'gist'];
        options.force = false;

        hello('github', options).login().then(function() {
            // Then call the callback
            callback()
        },
        function(e) {
            // If there was an error, send it to the callback
            errorCallback(e);
        });
    }
}

/*
 * Get all of the user's repositories
 */
gitHub.getRepos = function(done, error) {
    /*
     * Handle a repo response from GitHub
     */
    var addAllRepos = function(target, json, done, error) {
        // Add all returned repos to the list
        json.data.forEach(function(data) {
            var repo = {};
            repo.id = data.id;
            repo.owner = data.owner.login;
            repo.name = data.name;
            repo.full_name = data.full_name;
            repo.description = data.description;
            repo.url = data.url;
            repo.branches_url = data.branches_url;
            repo.git_commits_url = data.git_commits_url;
            repo.default_branch = data.default_branch;
            repo.permissions = data.permissions;
            target.push(repo);
        });

        // If there are more pages of repos,
        if (json.paging && json.paging.next) {
            // Request the next page of repos
            hello('github').api(json.paging.next).then(
                function(response){
                    console.log("retrieving next page of repos...");
                    // and handle the repos
                    addAllRepos(target, response, done, error);
                },
                function(e) {
                    // If there is an error, report it
                    error(e);
                });
        }
        else {
            // If there are no more pages of repos, send them to the caller
            done(target);
        }
    }

    // Clear out the list of repos
    gitHub.repos = [];

    // Make sure that the user is logged in
    gitHub.ensureLogin (function () {
        // Then request the user's repos
        hello('github').api('/user/repos').then(
            function(response){
                // Once the repos are received, add them to the repo list
                addAllRepos(gitHub.repos, response, done, error);
            },
            function (e) {
                // If there was an error, report it
                error(e);
            });
    },
    function(e) {
        // If there was an error logging in, report it
        error(e);
    });
};

/*
 * Load the files from a github repo into a FileManager
 */
gitHub.loadRepo = function(fileManager, repo) {

    var branch = repo.branches_url.replace(/\{.*\}/, "/" + repo.default_branch);
    console.log(branch);
    hello('github').api(branch).then(function(response) {
        console.log(response);
    },
    function(e) {
        alert('Error loading Repo branch: ' + e.error.message);
    });
};

/*
 * Callback for auth session starts
 */
function sessionStart() {
    hello('github').api('/me').then(function(json) {
        gitHub.username = json.login;
        gitHub.repos_url = json.repos_url;
    },
    function(e) {

    });
}

/*
 * Prepare for oauth login to github
 */
hello.init({github: 'b80ec7eaa799156bba33'},
           {redirect_uri: 'https://run.mycode.run/redirect.html',
            oauth_proxy: 'https://auth-server.herokuapp.com/proxy'});

hello.on('auth.login', sessionStart);<commit_msg>adding hello.js library for connection to github<commit_after>var gitHub = {};

/*
 * Make sure that github is logged in before calling callback
 * if there is an error, call errorCallback with an error param
 */
gitHub.ensureLogin = function(callback, errorCallback) {
    // Determine if there is a current oauth session
    var session = hello('github').getAuthResponse();
    var currentTime = (new Date()).getTime() / 1000;
    var online = session && session.access_token && session.expires > currentTime;

    if(online) {
        // If there is an active session, perform the callback
        callback();
    }
    else {
        // Otherwise, login
        var options = {};
        options.scope = ['user', 'repo', 'gist'];
        options.force = false;

        hello('github', options).login().then(function() {
            // Then call the callback
            callback()
        },
        function(e) {
            // If there was an error, send it to the callback
            errorCallback(e);
        });
    }
}

/*
 * Get all of the user's repositories
 */
gitHub.getRepos = function(done, error) {
    /*
     * Handle a repo response from GitHub
     */
    var addAllRepos = function(target, json, done, error) {
        // Add all returned repos to the list
        json.data.forEach(function(data) {
            var repo = {};
            repo.id = data.id;
            repo.owner = data.owner.login;
            repo.name = data.name;
            repo.full_name = data.full_name;
            repo.description = data.description;
            repo.url = data.url;
            repo.branches_url = data.branches_url;
            repo.git_commits_url = data.git_commits_url;
            repo.default_branch = data.default_branch;
            repo.permissions = data.permissions;
            target.push(repo);
        });

        // If there are more pages of repos,
        if (json.paging && json.paging.next) {
            // Request the next page of repos
            hello('github').api(json.paging.next).then(
                function(response){
                    console.log("retrieving next page of repos...");
                    // and handle the repos
                    addAllRepos(target, response, done, error);
                },
                function(e) {
                    // If there is an error, report it
                    error(e);
                });
        }
        else {
            // If there are no more pages of repos, send them to the caller
            done(target);
        }
    }

    // Clear out the list of repos
    gitHub.repos = [];

    // Make sure that the user is logged in
    gitHub.ensureLogin (function () {
        // Then request the user's repos
        hello('github').api('/user/repos').then(
            function(response){
                // Once the repos are received, add them to the repo list
                addAllRepos(gitHub.repos, response, done, error);
            },
            function (e) {
                // If there was an error, report it
                error(e);
            });
    },
    function(e) {
        // If there was an error logging in, report it
        error(e);
    });
};

/*
 * Load the files from a github repo into a FileManager
 */
gitHub.loadRepo = function(fileManager, repo) {

    var branch = repo.branches_url.replace(/\{.*\}/, "/" + repo.default_branch);
    hello('github').api(branch).then(function(response) {
        console.log(response);
        hello('github').api(response.commit.commit.tree.url).then(function(response) {
            console.log(response);
        },
        function (e){
            alert("Error loading latest commit: " + e.error.message)
        });
    },
    function(e) {
        alert('Error loading Repo branch: ' + e.error.message);
    });
};

/*
 * Callback for auth session starts
 */
function sessionStart() {
    hello('github').api('/me').then(function(json) {
        gitHub.username = json.login;
        gitHub.repos_url = json.repos_url;
    },
    function(e) {

    });
}

/*
 * Prepare for oauth login to github
 */
hello.init({github: 'b80ec7eaa799156bba33'},
           {redirect_uri: 'https://run.mycode.run/redirect.html',
            oauth_proxy: 'https://auth-server.herokuapp.com/proxy'});

hello.on('auth.login', sessionStart);<|endoftext|>


<commit_before>import React, {Component} from 'react';
import ReactDOM from 'react-dom';

import Map from './components/Map'
import FoundersList from './components/FoundersList'

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      foundersList : [
        {id: 'dGFraW5hcmRp', name : 'Larry Page & Sergey Brin', company : 'Google'},
        {id: 'cGVzc290dG8=', name : 'Steve Jobs & Steve Wozniak', company : 'Apple'},
        {id: 'Y29udGU=', name : 'Bill Gates', company : 'Microsoft'}
      ],
      selectedFounder : null
    }
  }

  render () {
    return (

        <Map />
        <FoundersList foundersList={this.state.foundersList}/>

    )
  }

}

ReactDOM.render(<App/>, document.querySelector('#app'));<commit_msg>connected the sse with app component<commit_after>import React, {Component} from 'react';
import ReactDOM from 'react-dom';

import Map from './components/Map'
import FoundersList from './components/FoundersList'

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      foundersList : [],
      selectedFounder : null
    }
    const eventSource = new EventSource('/founders');
    eventSource.addEventListener('message', (data) => {
      this.setState({
        foundersList : data
      });
    });
  }

  render () {
    return (

        <Map />
        <FoundersList foundersList={this.state.foundersList}/>

    )
  }

}

ReactDOM.render(<App/>, document.querySelector('#app'));<|endoftext|>


<commit_before>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor(props) {
    super(props);

    // State
    this.state = {
      names: [
        "Absalon (Absalon, Absaloni, Absalons)",
        "Adolf [a:d-] (Adolf, Adolfi, Adolfs)",
        "Adrian[a:d-] (Adrian, Adriani, Adrians)",
        "Adriel(Adriel, Adrieli, Adriels)",
        "Aðalgeir(Aðalgeir, Aðalgeiri, Aðalgeirs)",
        "Aðalstein(Aðalstein, Aðalsteini, Aðalsteins)",
        "Aggusteinus(Aggusteinus, Aggusteinusi, Aggusteinusar*)",
        "Agnar (Agnar, Agnari, Agnars)",
        "Aksal(Aksal, Aksali, Aksals)",
        "Aksel(Aksel, Akseli, Aksels)",
        "Albert(Albert, Alberti, Alberts)",
        "Albin(Albin, Albini, Albins)",
        "Aleks[a:l-] (Aleks, Aleksi, Aleks)",
        "Aleksandur[-'s-] (Aleksandur, Aleksanduri, Aleksandurs)",
        "Alfred(Alfred, Alfredi, Alfreds)",
        "Allan[-l:-] (Allan, Allani, Allans)",
        "Alvi (Alva, Alva, Alva)",
        "Amadeus [-'d-] (Amadeus, Amadeusi, Amadeusar*)"
      ],
      accepted: [],
      rejected: [],
      currentNameIndex: 0
    };

    // Bindings
    this.rejectName = this.rejectName.bind(this);
    this.acceptName = this.acceptName.bind(this);
    this.showName = this.showName.bind(this);
    this.increment = this.increment.bind(this);
    this.progress = this.progress.bind(this);
  }

  rejectName() {
    this.state.rejected.push(this.state.currentNameIndex);
    this.increment();
  }

  acceptName() {
    this.state.accepted.push(this.state.currentNameIndex);
    this.increment();
  }

  increment() {
    this.setState(function (prevState, props) {
      return {
        currentNameIndex: prevState.currentNameIndex + 1
      };
    });
  }

  progress() {
    return ((this.state.currentNameIndex + 1) * 100) / (this.state.names.length);
  }

  showName() {
    if (this.progress() <= 100) {
      return this.state.names[this.state.currentNameIndex];
    } else {
      return "Onki navn eftir";
    }
  }

  render() {
    return (

Barnanavn

{this.showName()}

        <button className="button is-danger" onClick={this.rejectName}>Ódáma</button>
        <button className="button is-success" onClick={this.acceptName}>Dáma</button>

{this.progress()}%

jjj

          {this.state.accepted.map((data) =>
{this.state.names[data]}
)}

    );
  }
}

export default App;
<commit_msg>Rewrite name logic<commit_after>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor(props) {
    super(props);

    // State
    this.state = {
      names: [
        { "name": "Absalon", "description": "(Absalon, Absaloni, Absalons)" },
        { "name": "Adolf", "description": "[a:d-] (Adolf, Adolfi, Adolfs)" },
        { "name": "Adrian", "description": "[a:d-] (Adrian, Adriani, Adrians)" },
        { "name": "Adriel", "description": "(Adriel, Adrieli, Adriels)" },
        { "name": "Aðalgeir", "description": "(Aðalgeir, Aðalgeiri, Aðalgeirs)" },
        { "name": "Aðalstein", "description": "(Aðalstein, Aðalsteini, Aðalsteins)" },
        { "name": "Aggusteinus", "description": "(Aggusteinus, Aggusteinusi, Aggusteinusar*)" },
        { "name": "Agnar", "description": "(Agnar, Agnari, Agnars)" },
        { "name": "Aksal", "description": "(Aksal, Aksali, Aksals)" },
        { "name": "Aksel", "description": "(Aksel, Akseli, Aksels)" },
        { "name": "Albert", "description": "(Albert, Alberti, Alberts)" },
        { "name": "Albin", "description": "(Albin, Albini, Albins)" },
        { "name": "Aleks", "description": "[a:l-] (Aleks, Aleksi, Aleks)" },
        { "name": "Aleksandur", "description": "[-'s-] (Aleksandur, Aleksanduri, Aleksandurs)" },
        { "name": "Alfred", "description": "(Alfred, Alfredi, Alfreds)" },
        { "name": "Allan", "description": "[-l:-] (Allan, Allani, Allans)" },
        { "name": "Alvi", "description": "(Alva, Alva, Alva)" },
        { "name": "Amadeus", "description": "[-'d-] (Amadeus, Amadeusi, Amadeusar*)" }
      ],
      accepted: [],
      rejected: [],
      currentNameIndex: 0
    };

    // Bindings
    this.rejectName = this.rejectName.bind(this);
    this.acceptName = this.acceptName.bind(this);
    this.showName = this.showName.bind(this);
    this.increment = this.increment.bind(this);
    this.progress = this.progress.bind(this);
    this.isFinished = this.isFinished.bind(this);
  }

  rejectName() {
    this.state.rejected.push(this.state.currentNameIndex);
    this.increment();
  }

  acceptName() {
    this.state.accepted.push(this.state.currentNameIndex);
    this.increment();
  }

  increment() {
    this.setState(function (prevState, props) {
      return {
        currentNameIndex: prevState.currentNameIndex + 1
      };
    });
  }

  progress() {
    return (this.state.currentNameIndex + 1) + "/" + this.state.names.length
  }

  isFinished() {
    return (this.state.currentNameIndex + 1) > this.state.names.length
  }

  showName() {
    if (!this.isFinished()) {
      return this.state.names[this.state.currentNameIndex].name
    } else {
      return "Onki navn eftir"
    }
  }

  showDescription() {
    if (!this.isFinished()) {
      return this.state.names[this.state.currentNameIndex].description
    }
  }

  render() {
    return (

Barnanavn

{ this.showName() }

{ this.showDescription() }

{ this.progress() }

        <button className="button is-danger" disabled={this.isFinished()} onClick={this.rejectName}>Ódáma</button>

        <button className="button is-success" disabled={this.isFinished()} onClick={this.acceptName}>Dáma</button>

Dáma nøvn:

          {this.state.accepted.map((data) =>
{this.state.names[data].name}
)}

    );
  }
}

export default App;
<|endoftext|>


<commit_before>const React = require('react')
const _ = require('lodash')
const tinycolor = require('tinycolor2')
const colorblend = require('colorblendjs')
const randomcolor = require('randomcolor')

const jsonp = require('jsonp')

const ColorBar = require('./components/ColorBar')

function colorToRgbArray(color) {
  var rgbColor = tinycolor(color).toRgb()
  return [rgbColor.r, rgbColor.g, rgbColor.b]
}

var rgbArrayToHex = (color) => {
  return tinycolor({
    r: color[0],
    g: color[1],
    b: color[2]
  }).toHex()
}

var fixMyColors = (colorScheme, overlayColor, overlayIntensity) => {
  return _.map(colorScheme, (color) => {
    var newColor = colorblend.overlay(colorToRgbArray(color), colorToRgbArray(overlayColor), overlayIntensity)
    return rgbArrayToHex(newColor)
  })
}

var getPalleteFromColorLovers = (callback) => {
  jsonp('https://www.colourlovers.com/api/palettes/random?format=json&jsonCallback=callback', {
    param: 'jsonCallback'
  }, callback)
}

var App = React.createClass({
  getInitialState () {
    return {
      colorScheme: ['555e7b', 'b7d968', 'b576ad', 'e04644', 'fde47f', '7ccce5'],

      overlayColor: 'FF9C00',
      overlayIntensity: 0.3,

      colorLovers: this.colorScheme
    }
  },

  componentDidMount () {
    getPalleteFromColorLovers((err, res) => {
      if (err) return console.error(err)

      this.setState({
        colorLovers: res[0].colors
      })
    })
  },

  handleChangeColor (index, color) {
    var newColorScheme = this.state.colorScheme.slice()
    newColorScheme[index] = color.hex.replace('#', '')

    this.setState({
      colorScheme: newColorScheme
    })
  },

  handleOverlayChange (index, color) {
    var newColor = color.hex.replace('#', '')

    this.setState({
      overlayColor: newColor
    })
  },

  handleOverlayIntensityChange (evt) {
    this.setState({
      overlayIntensity: parseFloat(evt.target.value)
    })
  },

  handleResizePallete (delta) {
    var colorScheme = this.state.colorScheme.slice()

    if (delta === 1) {
      colorScheme.push(randomcolor().replace('#', ''))
    } else {
      colorScheme.pop()
    }

    this.setState({
      colorScheme: colorScheme
    })
  },

  randomize () {
    this.setState({
      colorScheme: this.state.colorLovers
    })

    getPalleteFromColorLovers((err, res) => {
      if (err) return console.error(err)

      this.setState({
        colorLovers: res[0].colors
      })
    })
  },

  render () {
    var {colorScheme, overlayColor, overlayIntensity} = this.state

    return (

Cohesive Colors.

            This is a tool that may help you to create cohesive color schemes.

Original colors:

          <ColorBar colors={colorScheme} onChange={this.handleChangeColor} action='edit' />
          <button onClick={this.randomize}>
            Ger random from ColourLovers
          </button>
          {' - '}
          <button onClick={this.handleResizePallete.bind(null, -1)} disabled={colorScheme.length < 2}>
            Less colors
          </button>
          <button onClick={this.handleResizePallete.bind(null, 1)}>
            More colors
          </button>

OverlayColor

          <ColorBar colors={[overlayColor]} onChange={this.handleOverlayChange} action='edit' />

Intensity

            <input className='input-slider' type='range' min='0' max='1' step='.01' onChange={this.handleOverlayIntensityChange} value={overlayIntensity} />

Result:

          <ColorBar key={colorScheme.join('')} colors={fixMyColors(colorScheme, overlayColor, overlayIntensity)} action='copy' />

          {!!window.ClipboardEvent && (

Click on any color to copy.

          )}

            Based on this idea by _erica.
            Made by javierbyte.

    )
  }

})

module.exports = App
<commit_msg>Updated App.js - Fixed typos<commit_after>const React = require('react')
const _ = require('lodash')
const tinycolor = require('tinycolor2')
const colorblend = require('colorblendjs')
const randomcolor = require('randomcolor')

const jsonp = require('jsonp')

const ColorBar = require('./components/ColorBar')

function colorToRgbArray(color) {
  var rgbColor = tinycolor(color).toRgb()
  return [rgbColor.r, rgbColor.g, rgbColor.b]
}

var rgbArrayToHex = (color) => {
  return tinycolor({
    r: color[0],
    g: color[1],
    b: color[2]
  }).toHex()
}

var fixMyColors = (colorScheme, overlayColor, overlayIntensity) => {
  return _.map(colorScheme, (color) => {
    var newColor = colorblend.overlay(colorToRgbArray(color), colorToRgbArray(overlayColor), overlayIntensity)
    return rgbArrayToHex(newColor)
  })
}

var getPalleteFromColorLovers = (callback) => {
  jsonp('https://www.colourlovers.com/api/palettes/random?format=json&jsonCallback=callback', {
    param: 'jsonCallback'
  }, callback)
}

var App = React.createClass({
  getInitialState () {
    return {
      colorScheme: ['555e7b', 'b7d968', 'b576ad', 'e04644', 'fde47f', '7ccce5'],

      overlayColor: 'FF9C00',
      overlayIntensity: 0.3,

      colorLovers: this.colorScheme
    }
  },

  componentDidMount () {
    getPalleteFromColorLovers((err, res) => {
      if (err) return console.error(err)

      this.setState({
        colorLovers: res[0].colors
      })
    })
  },

  handleChangeColor (index, color) {
    var newColorScheme = this.state.colorScheme.slice()
    newColorScheme[index] = color.hex.replace('#', '')

    this.setState({
      colorScheme: newColorScheme
    })
  },

  handleOverlayChange (index, color) {
    var newColor = color.hex.replace('#', '')

    this.setState({
      overlayColor: newColor
    })
  },

  handleOverlayIntensityChange (evt) {
    this.setState({
      overlayIntensity: parseFloat(evt.target.value)
    })
  },

  handleResizePallete (delta) {
    var colorScheme = this.state.colorScheme.slice()

    if (delta === 1) {
      colorScheme.push(randomcolor().replace('#', ''))
    } else {
      colorScheme.pop()
    }

    this.setState({
      colorScheme: colorScheme
    })
  },

  randomize () {
    this.setState({
      colorScheme: this.state.colorLovers
    })

    getPalleteFromColorLovers((err, res) => {
      if (err) return console.error(err)

      this.setState({
        colorLovers: res[0].colors
      })
    })
  },

  render () {
    var {colorScheme, overlayColor, overlayIntensity} = this.state

    return (

Cohesive Colors.

            This is a tool that may help you to create cohesive color schemes.

Original colors:

          <ColorBar colors={colorScheme} onChange={this.handleChangeColor} action='edit' />
          <button onClick={this.randomize}>
            Get random from ColourLovers
          </button>
          {' - '}
          <button onClick={this.handleResizePallete.bind(null, -1)} disabled={colorScheme.length < 2}>
            Fewer colors
          </button>
          <button onClick={this.handleResizePallete.bind(null, 1)}>
            More colors
          </button>

OverlayColor

          <ColorBar colors={[overlayColor]} onChange={this.handleOverlayChange} action='edit' />

Intensity

            <input className='input-slider' type='range' min='0' max='1' step='.01' onChange={this.handleOverlayIntensityChange} value={overlayIntensity} />

Result:

          <ColorBar key={colorScheme.join('')} colors={fixMyColors(colorScheme, overlayColor, overlayIntensity)} action='copy' />

          {!!window.ClipboardEvent && (

Click on any color to copy.

          )}

            Based on this idea by _erica.
            Made by javierbyte.

    )
  }

})

module.exports = App
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');
var http = require('http');
var express = require('express');
var hbs = require('handlebars');

var app = express();

app.use(express.logger());
app.use(express.static(__dirname + '/../static'));

app.get
(
	'/favicon.ico', function (req, res)
	{
		res.status(404);
		res.end();
	}
);

app.get
(
	'/:template', function (req, res)
	{
		req.params.models = '';
		handler(req, res);
	}
);

app.get('/:template/:models', handler);

function handler (req, res)
{
	req.params.models = req.params.models.split('+');

	if (req.params.models.length === 1 && req.params.models[0] === '')
	{
		req.params.models = [];
	}

	fs.readFile(req.params.template + '.hbs', 'utf8', template_loaded);

	function template_loaded (err, template)
	{
		if (err)
		{
			res.status(500);
			res.send(err);

			return;
		}

		var final_model = {};
		var models_loaded = 0;

		(
			function load_model (err, model)
			{
				if (err)
				{
					res.status(500);
					res.send(err);

					return;
				}

				if (model !== undefined)
				{
					++models_loaded;

					model = JSON.parse(model);

					for (var key in model)
					{
						final_model[key] = model[key];
					}
				}

				if (models_loaded !== req.params.models.length)
				{
					fs.readFile(req.params.models[models_loaded] + '.json', 'utf8', load_model);
	                        }
				else
				{
					final_model_ready();
				}
			}
		)();

		function final_model_ready ()
		{
			res.send(hbs.compile(template)(final_model));
		}
	}
}

http.createServer(app).listen(4000);

<commit_msg>fix: Static file serving.<commit_after>#!/usr/bin/env node
var fs = require('fs');
var http = require('http');
var express = require('express');
var hbs = require('handlebars');

var app = express();

app.use(express.logger());
app.use(express.static(process.cwd()));

app.get
(
	'/:template', function (req, res)
	{
		req.params.models = '';
		handler(req, res);
	}
);

app.get('/:template/:models', handler);

function handler (req, res)
{
	req.params.models = req.params.models.split('+');

	if (req.params.models.length === 1 && req.params.models[0] === '')
	{
		req.params.models = [];
	}

	fs.readFile(req.params.template + '.hbs', 'utf8', template_loaded);

	function template_loaded (err, template)
	{
		if (err)
		{
			res.status(500);
			res.send(err);

			return;
		}

		var final_model = {};
		var models_loaded = 0;

		(
			function load_model (err, model)
			{
				if (err)
				{
					res.status(500);
					res.send(err);

					return;
				}

				if (model !== undefined)
				{
					++models_loaded;

					model = JSON.parse(model);

					for (var key in model)
					{
						final_model[key] = model[key];
					}
				}

				if (models_loaded !== req.params.models.length)
				{
					fs.readFile(req.params.models[models_loaded] + '.json', 'utf8', load_model);
	                        }
				else
				{
					final_model_ready();
				}
			}
		)();

		function final_model_ready ()
		{
			res.send(hbs.compile(template)(final_model));
		}
	}
}

http.createServer(app).listen(4000);

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'redux-bundler-react'
import { getNavHelper } from 'internal-nav-helper'
import ReactJoyride from 'react-joyride'
import { withTranslation } from 'react-i18next'
import { filesToStreams } from './lib/files'
// React DnD
import { DropTarget } from 'react-dnd'
import { NativeTypes } from 'react-dnd-html5-backend'
// Lib
import { appTour } from './lib/tours'
// Components
import NavBar from './navigation/NavBar'
import ComponentLoader from './loader/ComponentLoader'
import Notify from './components/notify/Notify'
import Connected from './components/connected/Connected'
import TourHelper from './components/tour/TourHelper'
import FilesExploreForm from './files/explore-form/FilesExploreForm'

export class App extends Component {
  static propTypes = {
    doInitIpfs: PropTypes.func.isRequired,
    doUpdateUrl: PropTypes.func.isRequired,
    doUpdateHash: PropTypes.func.isRequired,
    doFilesWrite: PropTypes.func.isRequired,
    route: PropTypes.oneOfType([
      PropTypes.func,
      PropTypes.element
    ]).isRequired,
    routeInfo: PropTypes.object.isRequired,
    navbarIsOpen: PropTypes.bool.isRequired,
    // Injected by DropTarget
    isOver: PropTypes.bool.isRequired
  }

  componentDidMount () {
    this.props.doInitIpfs()
  }

  addFiles = async (filesPromise) => {
    const { doFilesWrite, doUpdateHash, routeInfo } = this.props
    const isFilesPage = routeInfo.pattern === '/files*'
    const addAtPath = isFilesPage ? routeInfo.params.path : '/'
    const files = await filesPromise

    doFilesWrite(await filesToStreams(files), addAtPath)
    // Change to the files pages if the user is not there
    if (!isFilesPage) {
      doUpdateHash('/files')
    }
  }

  handleJoyrideCb = (data) => {
    if (data.action === 'close') {
      this.props.doDisableTooltip()
    }
  }

  render () {
    const { t, route: Page, ipfsReady, doFilesNavigateTo, doExploreUserProvidedPath, routeInfo: { url }, navbarIsOpen, connectDropTarget, canDrop, isOver, showTooltip } = this.props

    return connectDropTarget(

        {/* Tinted overlay that appears when dragging and dropping an item */}
        { canDrop && isOver &&
 }

          <div className={`flex-none-l bg-navy ${navbarIsOpen ? 'w5-l' : 'w4-l'}`}>
            <NavBar />

                <FilesExploreForm onBrowse={doFilesNavigateTo} onInspect={doExploreUserProvidedPath} />

                <TourHelper />
                <Connected className='joyride-app-status' />

              { (ipfsReady || url === '/welcome' || url.startsWith('/settings'))
                ? <Page />
                : <ComponentLoader pastDelay />
              }

        <ReactJoyride
          run={showTooltip}
          steps={appTour.getSteps({ t })}
          styles={appTour.styles}
          callback={this.handleJoyrideCb}
          scrollToFirstStep
          disableOverlay />

        <Notify />

    )
  }
}

const dropTarget = {
  drop: (props, monitor, App) => {
    if (monitor.didDrop()) {
      return
    }

    const { filesPromise } = monitor.getItem()
    App.addFiles(filesPromise)
  },
  canDrop: (props) => props.filesPathInfo ? props.filesPathInfo.isMfs : true
}

const dropCollect = (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop()
})

export const AppWithDropTarget = DropTarget(NativeTypes.FILE, dropTarget, dropCollect)(App)

export default connect(
  'selectRoute',
  'selectNavbarIsOpen',
  'selectRouteInfo',
  'selectIpfsReady',
  'selectShowTooltip',
  'doFilesNavigateTo',
  'doExploreUserProvidedPath',
  'doUpdateUrl',
  'doUpdateHash',
  'doInitIpfs',
  'doFilesWrite',
  'doDisableTooltip',
  'selectFilesPathInfo',
  withTranslation('app')(AppWithDropTarget)
)
<commit_msg>fix: draggable area on desktop (#1138)<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'redux-bundler-react'
import { getNavHelper } from 'internal-nav-helper'
import ReactJoyride from 'react-joyride'
import { withTranslation } from 'react-i18next'
import { filesToStreams } from './lib/files'
// React DnD
import { DropTarget } from 'react-dnd'
import { NativeTypes } from 'react-dnd-html5-backend'
// Lib
import { appTour } from './lib/tours'
// Components
import NavBar from './navigation/NavBar'
import ComponentLoader from './loader/ComponentLoader'
import Notify from './components/notify/Notify'
import Connected from './components/connected/Connected'
import TourHelper from './components/tour/TourHelper'
import FilesExploreForm from './files/explore-form/FilesExploreForm'

export class App extends Component {
  static propTypes = {
    doInitIpfs: PropTypes.func.isRequired,
    doUpdateUrl: PropTypes.func.isRequired,
    doUpdateHash: PropTypes.func.isRequired,
    doFilesWrite: PropTypes.func.isRequired,
    route: PropTypes.oneOfType([
      PropTypes.func,
      PropTypes.element
    ]).isRequired,
    routeInfo: PropTypes.object.isRequired,
    navbarIsOpen: PropTypes.bool.isRequired,
    // Injected by DropTarget
    isOver: PropTypes.bool.isRequired
  }

  componentDidMount () {
    this.props.doInitIpfs()
  }

  addFiles = async (filesPromise) => {
    const { doFilesWrite, doUpdateHash, routeInfo } = this.props
    const isFilesPage = routeInfo.pattern === '/files*'
    const addAtPath = isFilesPage ? routeInfo.params.path : '/'
    const files = await filesPromise

    doFilesWrite(await filesToStreams(files), addAtPath)
    // Change to the files pages if the user is not there
    if (!isFilesPage) {
      doUpdateHash('/files')
    }
  }

  handleJoyrideCb = (data) => {
    if (data.action === 'close') {
      this.props.doDisableTooltip()
    }
  }

  render () {
    const { t, route: Page, ipfsReady, doFilesNavigateTo, doExploreUserProvidedPath, routeInfo: { url }, navbarIsOpen, connectDropTarget, canDrop, isOver, showTooltip } = this.props

    return connectDropTarget(

        {/* Tinted overlay that appears when dragging and dropping an item */}
        { canDrop && isOver &&
 }

          <div className={`flex-none-l bg-navy ${navbarIsOpen ? 'w5-l' : 'w4-l'}`}>
            <NavBar />

                <FilesExploreForm onBrowse={doFilesNavigateTo} onInspect={doExploreUserProvidedPath} />

                <TourHelper />
                <Connected className='joyride-app-status' />

              { (ipfsReady || url === '/welcome' || url.startsWith('/settings'))
                ? <Page />
                : <ComponentLoader pastDelay />
              }

        <ReactJoyride
          run={showTooltip}
          steps={appTour.getSteps({ t })}
          styles={appTour.styles}
          callback={this.handleJoyrideCb}
          scrollToFirstStep
          disableOverlay />

        <Notify />

    )
  }
}

const dropTarget = {
  drop: (props, monitor, App) => {
    if (monitor.didDrop()) {
      return
    }

    const { filesPromise } = monitor.getItem()
    App.addFiles(filesPromise)
  },
  canDrop: (props) => props.filesPathInfo ? props.filesPathInfo.isMfs : true
}

const dropCollect = (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop()
})

export const AppWithDropTarget = DropTarget(NativeTypes.FILE, dropTarget, dropCollect)(App)

export default connect(
  'selectRoute',
  'selectNavbarIsOpen',
  'selectRouteInfo',
  'selectIpfsReady',
  'selectShowTooltip',
  'doFilesNavigateTo',
  'doExploreUserProvidedPath',
  'doUpdateUrl',
  'doUpdateHash',
  'doInitIpfs',
  'doFilesWrite',
  'doDisableTooltip',
  'selectFilesPathInfo',
  withTranslation('app')(AppWithDropTarget)
)
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

const tocasProps = [
  // main
  'ts',
  // colors
  'primary', 'info', 'warning', 'positive', 'negative', 'inverted',
  // sizes
  'mini', 'tiny', 'small', 'medium', 'large', 'big', 'huge', 'massive',
];

class Box extends Component {
  render() {
    let {
      wrapper,
      className,
      children,
      ...rest
    } = this.props;
    let cx = classNames(
      className,
      ...tocasProps.map(tocasProp => {
        delete rest[tocasProp];

        return {
          [tocasProp]: this.props[tocasProp],
        };
      })
    );

    return React.createElement(
      wrapper,
      {
        className: cx,
        ...rest,
      },
      children
    );
  }
}

Box.defaultProps = {
  wrapper: 'div',
};

Box.propTypes = {
  wrapper: PropTypes.node.isRequired,
  ...Object.assign({},
    ...tocasProps.map(tocasProp => ({ [tocasProp]: PropTypes.bool }))
  ),
};

export default Box;
<commit_msg>Add directions and alignment to Box<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

const tocasProps = [
  // main
  'ts',
  // colors
  'primary', 'info', 'warning', 'positive', 'negative', 'inverted',
  // sizes
  'mini', 'tiny', 'small', 'medium', 'large', 'big', 'huge', 'massive',
  // directions
  'left', 'right',
  // alignment
  'floated', 'aligned',
];

class Box extends Component {
  render() {
    let {
      wrapper,
      className,
      children,
      ...rest
    } = this.props;
    let cx = classNames(
      className,
      ...tocasProps.map(tocasProp => {
        delete rest[tocasProp];

        return {
          [tocasProp]: this.props[tocasProp],
        };
      })
    );

    return React.createElement(
      wrapper,
      {
        className: cx,
        ...rest,
      },
      children
    );
  }
}

Box.defaultProps = {
  wrapper: 'div',
};

Box.propTypes = {
  wrapper: PropTypes.node.isRequired,
  ...Object.assign({},
    ...tocasProps.map(tocasProp => ({ [tocasProp]: PropTypes.bool }))
  ),
};

export default Box;
<|endoftext|>