Archived
1
0
This repository has been archived on 2020-12-10. You can view files and clone it, but cannot push or open issues or pull requests.
old/assets/js/blog-edit.js
2019-01-04 19:47:29 +01:00

624 lines
18 KiB
JavaScript

const toolbarOptions = [
[{'header': [2, 3, 4, 5, 6, false]}],
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['image', 'video'],
['link', 'code-block', 'blockquote'],
[{'list': 'ordered'}, {'list': 'bullet'}],
[{'script': 'sub'}, {'script': 'super'}], // superscript/subscript
[{'indent': '-1'}, {'indent': '+1'}], // outdent/indent
[{'color': []}, {'background': []}], // dropdown with defaults from theme
[{'align': []}]
['clean']
];
// const quill = new Quill('#postContent', {
// theme: 'snow',
// bounds: '#postContent .ql-editor',
// modules: {
// syntax: true,
// toolbar: toolbarOptions
// }
// });
const editor = tinymce.init({
selector: '#postContent',
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'save table contextmenu directionality emoticons template paste textcolor'
],
templates: '/admin/blog/getTemplates',
toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons'
});
let changeUrl = true;
// Prevent the backspace key from navigating back.
$(document).on("keydown", function (e) {
if (e.which === 8 && !$(e.target || e.srcElement).is("span, [contenteditable=true], input")) {
e.preventDefault();
return false;
}
});
// var autolist = new AutoList();
// var editor = new MediumEditor('#content', {
// extensions: {
// 'autolist': autolist
// }
// });
// $('#content').mediumInsert({
// editor: editor
// });
// TODO
// $(function () {
// $('#content').mediumInsert({
// editor: editor
// });
// });
$('#postTitle').bind('click', function () {
$(this).attr('contentEditable', true);
}).blur(
function () {
$(this).attr('contentEditable', false);
});
$('#postTitle').on('keyup', function () {
if (changeUrl) {
var title = prepareString($('#postTitle').text());
$('#postUrl').val(encodeURI(title));
}
});
$('#postDescription').bind('click', function () {
$(this).attr('contentEditable', true);
}).blur(
function () {
$(this).attr('contentEditable', false);
});
$('#postCategory').bind('change', function () {
switchCategory();
});
function switchCategory() {
if ($('#postCategory').val() === 'new-category') {
$('#new-category').fadeIn(250);
} else {
$('#new-category').fadeOut(250);
}
}
$('#cat-dname').bind('keyup', function () {
$('#cat-name').val(prepareString($(this).val()));
});
function prepareString(input) {
input = input.toLowerCase()
.replace(/ /g, '-') // Remove spaces
.replace(/ä/g, 'ae') // Remove umlauts
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/[^a-z1-9-]/g, '') // Remove non alphanumerical chars
.replace(/--+/g, '-'); // Prevent multiple dashes
return input;
}
var shift = false;
const edits = ["#postTitle", "#postDescription", ".ql-editor"];
$(edits.toString()).keydown(function (e) {
const key = e.key;
// Shift Control
if (key === 'Shift') {
shift = true;
}
// Ctrl + Return Control
if (key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
$(this).attr('contentEditable', false);
}
// Tab Control
if (key === 'Tab') {
e.preventDefault();
$(this).attr('contentEditable', false);
let pos = edits.findIndex(edit => edit === '#' + $(this).attr('id') || $(this).hasClass(edit.substr(1)));
if (shift) {
pos--;
if (pos < 0)
pos = edits.length - 1;
} else {
pos++;
if (pos >= edits.length)
pos = 0;
}
$(edits[pos]).attr('contenteditable', true).focus();
}
});
$('.noEnter').keydown(function (e) {
var key = e.keyCode;
// Return Control
if (key === 13 && $(this).hasClass('noEnter')) {
e.preventDefault();
$(this).attr('contentEditable', false);
}
});
$('span').keyup(function (e) {
var key = e.keyCode;
// Shift Control
if (key === 16) {
shift = false;
}
});
const existingTags = new Bloodhound({
// datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
// queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
// prefetch: {
// url: '/admin/blog/tagsList',
// filter: function (list) {
// return $.map(list, function (cityname) {
// return {name: cityname};
// });
// }
// }
prefetch: {
url: '/admin/blog/tagsList',
cache: true
}
// local: ['Hallo Welt', 'Hund', 'Test', 'Geht doch']
});
existingTags.initialize();
// $('#postTags').typeahead({
// hint: true,
// highlight: true,
// minLength: 1
// }, {
// name: 'existingTags',
// source: existingTags,
// });
let tagsList = [];
$(function () {
$.ajax({
url: '/admin/blog/tagsList',
method: 'GET',
success: function (data) {
console.log(data);
for (let tag of data) {
tagsList.push(tag.display_name);
}
}
});
// $('#postTags').tagsinput();
//
$('#postTags').tagsinput({
// itemText: 'display_name',
typeaheadjs: {
source: ['Test', 'Value'],
name: 'existingTags',
// displayKey: 'display_name',
// source: existingTags.ttAdapter()
// source: substringMatcher(['Hallo', 'test', 'Hund'])
}
});
$('#postTags').keydown(function (e) {
if (e.keyCode === 9 || e.keyCode === 13) {
e.preventDefault();
}
});
if ($('#postID').val() !== '-1') {
getPostData();
getPostTags();
// getTranslations();
if ($('#contentID').val() !== '-1') {
getContentData();
}
if ($('#translationID').val() !== '-1') {
getTranslationData();
}
}
$('#postPublishDate').datetimepicker({
format: 'DD.MM.YYYY HH:mm',
stepping: '10',
sideBySide: true,
showTodayButton: true,
icons: {
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-arrow-up",
down: "fa fa-arrow-down"
}
});
});
Number.prototype.pad = function (size) {
let s = String(this);
while (s.length < (size || 2)) s = "0" + s;
return s;
};
function convertDate(dbDate) {
const date = new Date(dbDate);
console.log(date);
const day = date.getDate().pad();
const month = (date.getMonth() + 1).pad();
const year = date.getFullYear();
const hour = date.getHours().pad();
const minutes = date.getMinutes().pad();
return `${day}.${month}.${year} ${hour}:${minutes}`;
}
function getPostData() {
const postID = $('#postID').val();
$.ajax({
url: '/admin/blog/getPost',
method: 'post',
data: {
postID
},
success: (result) => {
console.log(result);
if (result.status === 'success') {
$('#postUrl').val(result.postData.postUrl);
$('#postCategory').val(result.postData.postCategoryID);
switchCategory();
$('#postPublishDate').data('DateTimePicker').setValue(convertDate(result.postData.postPublishDate));
// $('#postPublishDate').val(convertDate(result.postData.postPublishDate));
$('#uploadedImage').val(result.postData.postImage);
$('.img-container').css('background-image', 'url(' + result.postData.postImage + ')');
if (result.postData.postState === "1") {
$('#postUrl').attr('disabled', '');
changeUrl = false;
$('#postUrl').keydown((e) => {
e.preventDefault();
});
}
}
}
})
}
function getContentData() {
const postID = $('#postID').val();
const contentID = $('#contentID').val();
const lang = $('#postLanguage').val();
$.ajax({
url: '/admin/blog/getContent',
method: 'post',
data: {
postID, contentID, lang
},
success: (result) => {
console.log(result);
if (result.status === 'success') {
quill.clipboard.dangerouslyPasteHTML(result.contentData.content);
// $('#contentID').val('-1');
}
}
})
}
function getTranslationData() {
const postID = $('#postID').val();
const translationID = $('#translationID').val();
const lang = $('#postLanguage').val();
$.ajax({
url: '/admin/blog/getTranslationData',
method: 'post',
data: {
postID, translationID, lang
},
success: (result) => {
console.log(result);
if (result.status === 'success') {
$('#postTitle').text(result.translationData.postTitle);
$('#postDescription').text(result.translationData.postDesc);
}
}
})
}
function getPostTags() {
const postID = $('#postID').val();
$.ajax({
url: '/admin/blog/getPostTags',
method: 'POST',
data: {
postID
},
success: (result) => {
console.log(result);
if (result.success) {
for (let tag of result.tags) {
$('#postTags').tagsinput('add', tag.display_name);
}
}
}
})
}
$(function () {
$('#switchLanguages > li').click(function () {
const currentPostTitle = $('#postTitle').text();
const currentPostDescription = $('#postDescription').text();
const currentPostContent = quill.getContents();
const currentContentID = $('#contentID').val();
const currentTranslationID = $('#translationID').val();
$('#switchLanguages > li.active').data('title', currentPostTitle)
.data('description', currentPostDescription)
.data('content', currentPostContent)
.data('contentid', currentContentID)
.data('translationid', currentTranslationID)
.removeClass('active');
console.log($(this));
if ($(this).data('title')) {
const postTitle = $(this).data('title');
const postDescription = $(this).data('description');
const postContent = $(this).data('content');
$('#postTitle').text(postTitle);
$('#postDescription').text(postDescription);
quill.setContents(postContent);
}
const contentID = $(this).data('contentid');
const translationID = $(this).data('translationid');
$('#contentID').val(contentID);
$('#translationID').val(translationID);
$('#postLanguage').val($(this).data('lang'));
getTranslationData();
getContentData();
$(this).addClass('active');
});
});
function sendPost(executionFinished) {
const postID = $('#postID').val(),
contentID = $('#contentID').val(),
translationID = $('#translationID').val(),
postImage = $('#uploadedImage').val(),
postTitle = $('#postTitle').text(),
postDescription = $('#postDescription').text(),
postContent = $('.ql-editor').html(),
postPublishDate = $('#postPublishDate').val(),
postUrl = $('#postUrl').val(),
postCategory = $('#postCategory').val(),
postLanguage = $('#postLanguage').val(),
postTags = $('#postTags').tagsinput('items');
$.ajax({
url: '/admin/blog/sendEdit',
method: 'post',
data: {
postID,
contentID,
translationID,
postImage,
postTitle,
postDescription,
postContent,
postPublishDate,
postUrl,
postCategory,
postLanguage,
postTags
},
success: (result) => {
console.log(result);
if (result.success) {
$('#postID').val(result.postID);
$('#contentID').val(result.contentID);
$('#switchLanguages > li.active').data('contentid', result.contentID);
$('#translationID').val(result.translationID);
$('#switchLanguages > li.active').data('translationid', result.translationID);
$('.snackbar-container').append(`<div class="alert alert-success snackbar" role="alert">${result.message}</div>`);
} else {
$('.snackbar-container').append(`<div class="alert alert-danger snackbar" role="alert">${result.message}</div>`);
}
},
error: console.log
}).done(() => {
if (executionFinished)
executionFinished()
});
}
function publishPost() {
const postID = $('#postID').val(),
contentID = $('#contentID').val(),
contentDE = $('#switchLanguages').find('> li[data-lang=de]').data('contentid'),
contentEN = $('#switchLanguages').find('> li[data-lang=en]').data('contentid'),
contentFR = $('#switchLanguages').find('> li[data-lang=fr]').data('contentid');
$.ajax({
url: '/admin/blog/publishPost',
method: 'post',
data: {
postID, contentID,
contentIDs: {'de': contentDE, 'en': contentEN, 'fr': contentFR}
},
success: (result) => {
console.log(result);
$('#blogSubmit').button('reset');
if (result.success) {
$('#postUrl').attr('disabled', '');
changeUrl = false;
$('.snackbar-container').append(`<div class="alert alert-success snackbar" role="alert">${result.message}</div>`);
} else {
$('.snackbar-container').append(`<div class="alert alert-danger snackbar" role="alert">${result.message}</div>`);
}
}
})
}
$('#blogPostSave').click(() => {
$(this).button('loading');
sendPost();
});
$('#blogSubmit').click(() => {
$(this).button('loading');
sendPost(publishPost);
});
$('#blogPreview').click(() => openPreview());
let timeoutPreview;
$('body').keyup(() => {
if (timeoutPreview)
clearTimeout(timeoutPreview);
timeoutPreview = setTimeout(() => {
if (previewWindow)
openPreview();
}, 1000);
});
let previewID;
let previewWindow;
function openPreview() {
const data = {
postTitle: $('#postTitle').text(),
postDesc: $('#postDescription').text(),
// postContent: $('.ql-editor').html(),
postContent: tinymce.get('postContent').getContent(),
};
if (previewID)
data.previewID = previewID;
$.ajax({
url: '/admin/blog/updatePreview',
data: data,
method: 'POST',
success: (data) => {
if (data.success) {
previewID = data.previewID;
console.log(data.session);
if (!previewWindow) {
previewWindow = window.open('http://192.168.178.39/admin/blog/preview?id=' + previewID, '_BLANK');
} else {
previewWindow.location.reload();
previewWindow.opener.focus();
}
}
}
});
}
// Upload Header Image
$('.upload-btn').on('change', '.upload-image', function () {
$('.upload-btn').fadeOut();
$('.img-container').append('<i class="fa fa-cog fa-spin fa-4x"></i>');
const file = this.files[0],
imageFile = file.type,
match = ["image/jpeg", "image/jpg", "image/png"];
if (match.indexOf(imageFile) === -1) {
return;
}
const reader = new FileReader();
reader.addEventListener('load', () => {
$('.img-container').css('background-image', 'url(' + reader.result + ')');
$.ajax({
url: '/admin/files/uploadImage',
type: 'POST',
data: {
image: reader.result,
name: file.name,
type: file.type,
size: file.size,
},
success: (data) => {
if (data.success) {
$('.img-container > .fa').removeClass('fa-spin').removeClass('fa-cog').addClass('fa-check').addClass('text-success')
.delay(2000).fadeOut();
$('#uploadedImage').val(data.url);
$('.snackbar-container').append(`<div class="alert alert-success snackbar" role="alert">${data.message}</div>`);
} else {
$('.img-container > .fa').removeClass('fa-spin').removeClass('fa-cog').addClass('fa-cross').addClass('text-danger')
.delay(2000).fadeOut();
$('.img-container').delay(2000).css('background-image', '');
$('.snackbar-container').append(`<div class="alert alert-danger snackbar" role="alert">${data.message}</div>`);
}
setTimeout(() => {
$('.upload-btn').fadeIn();
}, 2500);
}
});
});
reader.readAsDataURL(file);
});
function substringMatcher(strs) {
return function findMatches(q, cb) {
let matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
console.log('ich bin auc hdavbei #.');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function (i, str) {
if (substrRegex.test(str)) {
console.log(str);
matches.push(str);
}
});
cb(matches);
};
}