Coding/BinaryDad.Coding/wwwroot/js/hub.js

92 lines
2.3 KiB
JavaScript

$(function () {
var connection = new signalR.HubConnectionBuilder().withUrl('/codeHub').build();
let $liveModeLink = $('#live-mode-link');
let $liveModeStatus = $('#live-mode-status');
let $usersList = $('#users-list');
let $yourNameText = $('#your-name-text');
let $yourColorText = $('#your-color-text');
let isLive = false;
let isLiveMode = function () {
isLive = window.location.hash === '#live';
$liveModeLink
.toggleClass('btn-success text-white', isLive)
.attr('href', isLive ? '#' : '#live');
isLive ? $liveModeStatus.fadeIn() : $liveModeStatus.fadeOut();
};
let sendName = function (e) {
let color = $yourColorText.val();
$yourNameText.css('color', `${color}`);
connection.invoke('SaveName', $yourNameText.val(), color);
};
isLiveMode();
// events
$(window).on('hashchange', isLiveMode);
$('#your-name-text, #your-color-text').doneTyping(sendName);
let isTeacher = window.location.hash === '#4ELQcUq7UnFGghAZCVr4Chr9JmtncigfkGu5WSf9';
if (isTeacher) {
$liveModeLink.hide();
$liveModeStatus.hide();
}
let $editors = $('.ace_editor');
if (isTeacher) {
$editors.each(function (i, e) {
let editor = ace.edit(e);
editor.session.on('change', function () {
let user = 'ryan';
let code = editor.getValue();
connection.invoke('UpdateCode', user, i, code).catch(function (err) {
return console.error(err.toString());
});
});
});
}
connection.on('ReceiveCode', function (user, index, code) {
if (!isTeacher && isLive) {
let editor = ace.edit($editors[index]);
editor.session.setValue(code);
}
});
connection.on('UsersList', function (users) {
let usersList = Object.values(users)
.filter(u => u.name !== '')
.map(u => `<span style='color: ${u.color};'>${u.name}</span>`);
$usersList.html(`<strong>${usersList.length} users online:</strong> ${usersList.join(', ')}`);
});
connection.start().then(function () {
sendName();
}).catch(function (err) {
return console.error(err.toString());
});
});