Notes/wwwroot/js/site.js
2023-01-09 15:54:20 -05:00

91 lines
2.1 KiB
JavaScript

let saveContent = function ($textarea) {
$textarea = $textarea || $('textarea');
var content = $textarea.val();
$.ajax('/api/save', {
data: content,
contentType: 'text/plain',
type: 'POST'
}).done(function (data) {
// show 'saved' indicator
$('#saved-indicator').addClass('show').delay(800).queue(function (next) {
$(this).removeClass('show');
next();
});
}).fail(function () {
alert('Could not connect to server. Check your internet connection and try again.');
});
};
var poller = null;
let pollJob = function () {
poller = setInterval(function () {
$.get('/api/get', function (content) {
$('textarea').val(content);
});
}, 30000);
}
$(function () {
// set dark mode
if (window.location.hash == '#dark') {
$('textarea').addClass('dark');
}
var timer = null;
let ignoredKeyCodes = [17, 18, 20, 27, 37, 38, 39, 40, 91];
// start polling
pollJob();
// save after half-second delay after typing
$('textarea').keyup(function (e) {
clearTimeout(timer);
clearInterval(poller);
// only set timer if key isn't ignored
if (!ignoredKeyCodes.includes(e.keyCode)) {
timer = setTimeout(function () {
saveContent();
}, 1000);
pollJob();
}
});
// 20 second interval
// setInterval(saveContent, 60000);
// support tab key in textarea
$('textarea').keydown(function (e) {
if (e.keyCode === 9) { // tab was pressed
// get caret position/selection
var start = this.selectionStart;
end = this.selectionEnd;
var $this = $(this);
// set textarea value to: text before caret + tab + text after caret
$this.val($this.val().substring(0, start)
+ '\t'
+ $this.val().substring(end));
// put caret at right position again
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
return false;
}
});
});