Skip to content

Commit

Permalink
将用户中心 个人信息、上传头像和验证手机号码的 JavaScript 脚本移到 .js 文件中
Browse files Browse the repository at this point in the history
  • Loading branch information
Jijie Chen committed Dec 2, 2018
1 parent 62ec073 commit ad330cc
Show file tree
Hide file tree
Showing 11 changed files with 405 additions and 320 deletions.
2 changes: 1 addition & 1 deletion src/Discussion.Web/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public async Task<IActionResult> DoSignin([FromForm]UserViewModel viewModel, [Fr
}
else
{
_logger.LogInformation($"用户登录失败:用户名 {viewModel.UserName}:数据格式不正确。");
_logger.LogWarning($"用户登录失败:用户名 {viewModel.UserName}:数据格式不正确。");
}

if (!result.Succeeded)
Expand Down
6 changes: 3 additions & 3 deletions src/Discussion.Web/Views/Topic/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@

@section Tail{
<script>
$(document).ready(function() {
var replyUrl = '/topics/' + parseInt('@Model.Id') + '/replies';
var previewApi = '/api/common/md2html?maxHeadingLevel=3';
$(function() {
var replyUrl = '@Url.Action("Reply", "Reply", new {topicId = Model.Id})';
var previewApi = '@Url.Action("RenderMarkdown", "Common", new {maxHeadingLevel = 3})';
var app = window.DiscussionApp;
var previewSelectors = {
tabPreview: '#tab-preview',
Expand Down
197 changes: 9 additions & 188 deletions src/Discussion.Web/Views/User/Settings.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,10 @@
<img src="@AvatarService.GetUserAvatarUrl(Model)" title="点击更改头像" class="user-avatar"/>
</div>
<span class="avatar-note">点击更改头像,请使用 240x240 方形图片</span>
<canvas class="avatar-preview" width="240" height="240"></canvas>

</div>
<div>
@Html.HiddenFor(model => model.AvatarFileId)
<input type="file" class="avatar-upload" id="avatar-file-upload" accept="image/*"/>
</div>
</fieldset>
<fieldset class="form-group">
Expand Down Expand Up @@ -85,194 +84,16 @@
var sendConfirmationMailUrl = '@Url.Action("SendEmailConfirmation", "User")';
var uploadAvatarUrl = '@Url.Action("UploadFile", "Common", new {category = "avatar"})';
$(function() {
$('input[name=EmailAddress]').keyup(function() {
var changed = !this.value || this.value !== '@Model.EmailAddress';
if (changed) {
$('[rel=confirmation]').hide();
} else {
$('[rel=confirmation]').show();
}
});
// "send", "re-send", "error", "sending", "sent"
var currentStatus = null;
function updateOperations(status) {
currentStatus = status;
$('.confirmation-operation').hide();
$('.confirmation-operation[data-status=' + currentStatus + ']').show();
if (status === 'sent') {
$('span[data-status=sent-2]').hide();
$('span[data-status=sent-1]').show();
setTimeout(function() {
$('span[data-status=sent-1]').hide();
$('span[data-status=sent-2]').show();
countdown(30);
},
3500);
}
function countdown(cur) {
if (cur === 0) {
updateOperations('re-send');
} else {
$('span[data-status=sent-2].countdown').text(cur);
setTimeout(function() {
countdown(--cur);
}, 1000);
}
}
}
function send() {
$('.confirmation').addClass('sent');
updateOperations('sending');
$.ajax({
url: sendConfirmationMailUrl,
method: 'POST',
data: { __RequestVerificationToken: window.__RequestVerificationToken },
dataType: 'json',
success: function(data) {
if (!data.hasSucceeded) {
updateOperations('error');
} else {
updateOperations('sent');
}
},
error: function() {
updateOperations('error');
}
});
}
updateOperations('send');
$('a.link.confirmation-operation').click(send);
var avatarUploadSelectors = {
avatarImage: '.user-avatar',
avatarNote: '.avatar-note',
inputField: '#@(nameof(Model.AvatarFileId))'
};
var userModule = window.DiscussionApp.user;
function fileSelected() {
if (!this.files.length) {
return;
}
var blob = URL.createObjectURL(this.files[0]);
var parsedFile = parseFileName(this.files[0].name);
var img = new Image();
img.onload = function() {
var size = 240;
if (this.width < size || this.height < size) {
alert('所选的图片太小,请选择 ' + size + 'x' + size + ' 像素以上的方形图片');
} else {
var resized = resizeTo(img, size, parsedFile.canBeTransparent);
$('.user-avatar')[0].src = resized.dataURL;
uploadAvatar(resized.dataURL, parsedFile.name + resized.ext);
}
URL.revokeObjectURL(blob);
};
img.onerror = function() {
console.error('所选择的文件不是图片文件');
URL.revokeObjectURL(blob);
};
img.src = blob;
function resizeTo(img, size, canBeTransparent) {
var canvas = $('.avatar-preview')[0];
var ctx = canvas.getContext('2d');
var wRatio = img.width / size;
var hRatio = img.height / size;
var ratio = Math.min(wRatio, hRatio);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img,
0, 0,
Math.floor(size * ratio), Math.floor(size * ratio),
0, 0,
size, size);
var usePng = canBeTransparent ? hasTransparent(ctx.getImageData(0, 0, size, size)) : false;
return {
dataURL: canvas.toDataURL(usePng ? 'image/png' : 'image/jpeg', 0.8),
ext: usePng ? '.png' : '.jpg'
};
}
function hasTransparent(imageData) {
for(var x = 0; x < imageData.width; x++){
for(var y = 0; y < imageData.height; y++){
if (imageData.data[3] === 0) {
return true;
}
}
}
return false;
}
function parseFileName(fileName) {
var lastIndexOfDot = fileName.lastIndexOf('.');
var hasExt = lastIndexOfDot > 0 && lastIndexOfDot < fileName.length - 2;
var name = hasExt ? fileName.substr(0, lastIndexOfDot) : fileName;
var ext = hasExt ? fileName.substr(lastIndexOfDot) : '';
return {
name: name,
canBeTransparent: ext.toLowerCase() === '.png' || ext.toLowerCase() === '.gif'
};
}
}
function uploadAvatar(dataURL, fileName) {
var u8Image = b64ToUint8Array(dataURL);
var formData = new FormData();
formData.append('file', new Blob([ u8Image ], {type: "image/png"}), fileName);
formData.append('__RequestVerificationToken', window.__RequestVerificationToken);
$('.user-avatar').addClass('uploading').attr('title', '正在上传,请稍候...');
$.ajax({
url: uploadAvatarUrl,
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function(data) {
$('.user-avatar').removeClass('uploading').attr('title', '点击更改头像');
if (data.hasSucceeded) {
$('.user-avatar')[0].src = data.result.publicUrl;
$('#@(nameof(Model.AvatarFileId))').val(data.result.fileId);
$('.avatar-note').text('请点击 保存 确认使用新头像');
}
},
error: function() {
$('.user-avatar').removeClass('uploading').attr('title', '点击更改头像');
console.error('无法上传头像', arguments);
}
});
function b64ToUint8Array(b64Image) {
var img = atob(b64Image.split(',')[1]);
var imgBuffer = [];
var i = 0;
while (i < img.length) {
imgBuffer.push(img.charCodeAt(i));
i++;
}
return new Uint8Array(imgBuffer);
}
}
$('.user-avatar').click(function() {
if ($(this).hasClass('uploading')) {
return;
}
$('#avatar-file-upload').click();
});
$('#avatar-file-upload').change(fileSelected);
userModule.email.setupEditEmailAddress('@Model.EmailAddress', sendConfirmationMailUrl);
userModule.avatar.setupUploadAvatar(avatarUploadSelectors, uploadAvatarUrl);
});
</script>
}
124 changes: 4 additions & 120 deletions src/Discussion.Web/Views/User/VerifyPhoneNumber.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -71,128 +71,12 @@

@section Tail{
<script>
var sendCodeUrl = '@Url.Action("SendPhoneNumberVerificationCode", "User")';
var verifyNumberUrl = '@Url.Action("DoVerifyPhoneNumber", "User")';
$(function() {
// "send", "re-send", "error", "sending", "sent"
var currentStatus = null;
function updateOperations(status) {
currentStatus = status;
$('.verification-operation').hide();
$('.verification-operation[data-status=' + currentStatus + ']').show();
if (status === 'sent') {
$('.verification-submit').show();
$('span[data-status=sent-2]').hide();
$('span[data-status=sent-1]').show();
setTimeout(function() {
$('span[data-status=sent-1]').hide();
$('span[data-status=sent-2]').show();
countdown(118);
},
5000);
}
function countdown(cur) {
if (cur === 0) {
updateOperations('re-send');
} else {
$('span[data-status=sent-2].countdown').text(cur);
setTimeout(function() {
countdown(--cur);
},
1000);
}
}
}
function send() {
var phoneNumberInput = $('#VerifiedPhoneNumber_PhoneNumber');
var phoneNumber = phoneNumberInput.val();
if (!phoneNumber) {
phoneNumberInput.focus();
return;
}
if (!(/^1\d{10}$/.test(phoneNumber))) {
alert('手机号的格式不正确,请输入 11 位国内手机号');
phoneNumberInput.focus();
phoneNumberInput.select();
return;
}
$('.verification').addClass('sent');
updateOperations('sending');
$.ajax({
url: sendCodeUrl,
method: 'POST',
data: {
__RequestVerificationToken: window.__RequestVerificationToken,
phoneNumber: phoneNumber
},
dataType: 'json',
success: function(data) {
if (!data.hasSucceeded) {
updateOperations('error');
} else {
updateOperations('sent');
}
},
error: function() {
updateOperations('error');
}
});
}
function verify() {
var codeInput = $('#VerificationCode');
var code = codeInput.val();
if (!code) {
codeInput.focus();
return;
}
if (!(/^\d{6}$/.test(code))) {
alert('验证码格式不正确,请输入收到的6位验证码');
codeInput.focus();
codeInput.select();
return;
}
$.ajax({
url: verifyNumberUrl,
method: 'POST',
data: {
code: code,
__RequestVerificationToken: window.__RequestVerificationToken
},
dataType: 'json',
success: function(data) {
if (data.hasSucceeded) {
location.reload();
} else {
alert('无法验证手机号:' + data.message);
}
},
error: function() {
updateOperations('error');
}
});
}
updateOperations('send');
$('a.link.verification-operation').click(send);
$('#btn-verify').click(verify);
$('a.link.change-phone-number').click(function() {
$('.edit-phone-number').removeClass('hide');
$('.has-phone-number').removeClass('show').addClass('hide');
});
var sendCodeUrl = '@Url.Action("SendPhoneNumberVerificationCode", "User")';
var verifyNumberUrl = '@Url.Action("DoVerifyPhoneNumber", "User")';
window.DiscussionApp.utils.transformTimestampOn('.verified-at', 'data-last-verified-at');
window.DiscussionApp.user.phone.setupVerifyPhoneNumber(sendCodeUrl, verifyNumberUrl);
});
</script>
}
4 changes: 3 additions & 1 deletion src/Discussion.Web/wwwroot/scripts/_entry-js.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import '../lib/node_modules/prismjs';
import * as utils from './functions'
import * as mdeditor from './markdown-editor'
import * as topic from './topic'
import * as user from './user/index'



window.jQuery = window.$ = jQuery;
window.DiscussionApp = { utils, mdeditor, topic };
window.DiscussionApp = { utils, mdeditor, topic, user };
Loading

0 comments on commit ad330cc

Please sign in to comment.