var ProfileForm = FormView.extend({ el: "#profile_form", events: { "input #profile-newpassword": 'showOldPassword', "change #profile-avatar": 'changeAvatar', }, action: "/api/user", method: "POST", initialize: function(){ this.__super__.initialize.call(this) this.template = this.$(".template").html() }, load: function(username){ this.action = "/api/user/" + username; "realname location email phone website twitter".split(" ").forEach((field) => { this.$('[name=' + field + ']').val( auth.user[field] ) }) if (! auth.user.avatar) { $("#profile-avatar-embed").hide() } else { $("#profile-avatar-embed").attr("src", sanitizeHTML(auth.user.avatar)) } $("body").removeClass('loading') }, changeAvatar: function(e){ var files = e.dataTransfer ? e.dataTransfer.files : e.target.files; if (! files.length) return var f = files[0] if ( ! f.type.match('image.*')) { e.preventDefault() return; } var reader = new FileReader(); reader.onload = (e) => { var img = new Image() img.onload = () => { this.showAvatar(img) } img.src = e.target.result } reader.readAsDataURL(f); }, showAvatar: function(img){ var canvas = document.createElement("canvas") var ctx = canvas.getContext('2d') var w, h var ratio = img.naturalWidth / img.naturalHeight if (ratio > 1) { // landscape w = 500 h = 500 / ratio } else { h = 500 w = 500 * ratio } canvas.width = w canvas.height = h ctx.drawImage(img, 0, 0, w, h) var dataURI = canvas.toDataURL('image/jpeg', 0.85) this.avatarBlob = dataUriToBlob(dataURI) this.$("#profile-avatar-embed").show().attr("src", dataURI).css("width", w/2) }, showOldPassword: function(){ this.$(".oldpassword").css('display', 'flex') }, serialize: function(){ var fd = this.__super__.serialize.call(this) var oldpw = this.$("[name=oldpassword]").val() var pw = this.$("[name=newpassword]").val() var pw2 = this.$("[name=newpassword2]").val() fd.delete('avatar') if (this.avatarBlob) { fd.append("avatar", this.avatarBlob) } return fd }, validate: function(){ var errors = [] var oldpw = this.$("[name=oldpassword]").val() var pw = this.$("[name=newpassword]").val() var pw2 = this.$("[name=newpassword2]").val() if (pw !== pw2) { errors.push("Passwords don't match.") } if (pw && ! oldpw) { errors.push("Please enter your old password.") } return errors.length ? errors : null }, success: function(data){ if (data.error) { return alert(data.error) } auth.set_user(data.user) window.location.href = "/profile" } })