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

629 lines
19 KiB
JavaScript
Raw Permalink Normal View History

2018-10-16 16:28:42 +00:00
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'
2018-10-16 16:28:42 +00:00
});
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;
}
});
2018-10-16 16:28:42 +00:00
// 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(
2018-10-16 16:28:42 +00:00
function () {
$(this).attr('contentEditable', false);
}).on('keyup', function () {
if (changeUrl) {
var title = prepareString($('#postTitle').text());
$('#postUrl').val(encodeURI(title));
}
2018-10-16 16:28:42 +00:00
});
$('#postDescription').bind('click', function () {
$(this).attr('contentEditable', true);
}).blur(
function () {
$(this).attr('contentEditable', false);
});
$('#postCategory').bind('change', function () {
switchCategory();
});
function switchCategory() {
if ($('#postCategory').val().includes('new-category')) {
2018-10-16 16:28:42 +00:00
$('#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;
2018-10-16 16:28:42 +00:00
// Shift Control
if (key === 'Shift') {
2018-10-16 16:28:42 +00:00
shift = true;
}
// Ctrl + Return Control
if (key === 'Enter' && (e.ctrlKey || e.metaKey)) {
2018-10-16 16:28:42 +00:00
e.preventDefault();
$(this).attr('contentEditable', false);
}
// Tab Control
if (key === 'Tab') {
2018-10-16 16:28:42 +00:00
e.preventDefault();
$(this).attr('contentEditable', false);
let pos = edits.findIndex(edit => edit === '#' + $(this).attr('id') || $(this).hasClass(edit.substr(1)));
2018-10-16 16:28:42 +00:00
if (shift) {
pos--;
if (pos < 0)
pos = edits.length - 1;
2018-10-16 16:28:42 +00:00
} else {
pos++;
if (pos >= edits.length)
pos = 0;
2018-10-16 16:28:42 +00:00
}
$(edits[pos]).attr('contenteditable', true).focus();
2018-10-16 16:28:42 +00:00
}
});
$('.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,
// });
2018-10-16 16:28:42 +00:00
let tagsList = [];
$(function () {
$.ajax({
url: '/admin/blog/tagsList',
2018-10-16 16:28:42 +00:00
method: 'GET',
success: function (data) {
console.log(data);
for (let tag of data) {
tagsList.push(tag.display_name);
}
}
});
// $('#postTags').tagsinput();
//
2018-10-16 16:28:42 +00:00
$('#postTags').tagsinput({
// itemText: 'display_name',
2018-10-16 16:28:42 +00:00
typeaheadjs: {
source: ['Test', 'Value'],
name: 'existingTags',
// displayKey: 'display_name',
// source: existingTags.ttAdapter()
// source: substringMatcher(['Hallo', 'test', 'Hund'])
2018-10-16 16:28:42 +00:00
}
});
$('#postTags').keydown(function (e) {
if (e.keyCode === 9 || e.keyCode === 13) {
e.preventDefault();
}
});
if ($('#postID').val() !== '-1') {
getPostData();
getPostTags();
// getTranslations();
if ($('#versionID').val() !== '-1')
getVersionData();
2018-10-16 16:28:42 +00:00
}
$('#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}`;
}
2018-10-16 16:28:42 +00:00
function getPostData() {
const postID = $('#postID').val();
$.ajax({
url: '/admin/blog/getPost',
2018-10-16 16:28:42 +00:00
method: 'post',
data: {
postID
},
success: (result) => {
console.log(result);
if (result.status === 'success') {
const categoryIDs = result.postData.categories.map(item => item.ID);
$('#postCategory').val(categoryIDs);
2018-10-16 16:28:42 +00:00
switchCategory();
$('#uploadedImage').val(result.postData.image);
$('.img-container').css('background-image', 'url(' + result.postData.image + ')');
$('#postPublishDate').data('DateTimePicker').setValue(convertDate(result.postData.initialRelease));
2018-10-16 16:28:42 +00:00
}
}
})
}
function getVersionData() {
2018-10-16 16:28:42 +00:00
const postID = $('#postID').val();
const versionID = $('#versionID').val();
2018-10-16 16:28:42 +00:00
const lang = $('#postLanguage').val();
2018-10-16 16:28:42 +00:00
$.ajax({
url: '/admin/blog/getVersion',
2018-10-16 16:28:42 +00:00
method: 'post',
data: {
postID, versionID, lang,
2018-10-16 16:28:42 +00:00
},
success: (result) => {
console.log(result);
if (result.status === 'success') {
$('#postTitle').text(result.title);
$('#postDescription').text(result.description);
console.log(tinyMCE.get('postContent'));
if (typeof (tinymce.activeEditor.contentDocument) !== 'undefined') {
tinyMCE.on('addeditor', (e) => {
const editor = e.editor;
if (editor.id === 'postContent') {
editor.setContent(result.content);
console.log(e);
}
});
} else {
// tinyMCE.activeEditor.setContent(result.content);
$('#postContent').val(result.content);
}
$('#postUrl').val(result.url);
$('#versionID').val('-1');
2018-10-16 16:28:42 +00:00
}
},
error: console.log
});
2018-10-16 16:28:42 +00:00
}
function getPostTags() {
const postID = $('#postID').val();
$.ajax({
url: '/admin/blog/getPostTags',
2018-10-16 16:28:42 +00:00
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 currentPostContent = tinymce.get('postContent').getContent();
const currentPostUrl = $('#postUrl').val();
const currentVersionID = $('#versionID').val();
2018-10-16 16:28:42 +00:00
$('#switchLanguages > li.active')
.data('title', currentPostTitle)
2018-10-16 16:28:42 +00:00
.data('description', currentPostDescription)
.data('content', currentPostContent)
.data('url', currentPostUrl)
.data('versionid', currentVersionID)
2018-10-16 16:28:42 +00:00
.removeClass('active');
console.log($(this));
const versionID = $(this).data('versionid');
$('#versionID').val(versionID);
$('#postLanguage').val($(this).data('lang'));
2018-10-16 16:28:42 +00:00
if ($(this).data('title')) {
const postTitle = $(this).data('title');
const postDescription = $(this).data('description');
const postContent = $(this).data('content');
const postUrl = $(this).data('url');
2018-10-16 16:28:42 +00:00
$('#postTitle').text(postTitle);
$('#postDescription').text(postDescription);
// quill.setContents(postContent);
tinymce.get('postContent').setContent(postContent);
$('#postUrl').val(postUrl);
} else {
getVersionData();
2018-10-16 16:28:42 +00:00
}
$(this).addClass('active');
});
});
function sendPost(executionFinished) {
const postID = $('#postID').val(),
versionID = $('#versionID').val(),
2018-10-16 16:28:42 +00:00
postImage = $('#uploadedImage').val(),
postTitle = $('#postTitle').text(),
postDescription = $('#postDescription').text(),
postContent = tinyMCE.activeEditor.getContent(),
2018-10-16 16:28:42 +00:00
postPublishDate = $('#postPublishDate').val(),
postUrl = $('#postUrl').val(),
postCategories = $('#postCategory').val(),
newCategoryName = $('#cat-name').val(),
newCategoryDisplayName = $('#cat-dname').val(),
2018-10-16 16:28:42 +00:00
postLanguage = $('#postLanguage').val(),
postTags = $('#postTags').tagsinput('items');
$.ajax({
url: '/admin/blog/sendEdit',
2018-10-16 16:28:42 +00:00
method: 'post',
data: {
postID,
versionID,
2018-10-16 16:28:42 +00:00
postImage,
postTitle,
postDescription,
postContent,
postPublishDate,
postUrl,
postCategories,
newCategoryName,
newCategoryDisplayName,
2018-10-16 16:28:42 +00:00
postLanguage,
postTags
},
success: (result) => {
console.log(result);
const newCategory = postCategories.includes('new-category');
2018-10-16 16:28:42 +00:00
if (result.success) {
$('#postID').val(result.postID);
$('#versionID').val(result.versionID);
$('#switchLanguages > li.active').data('versionid', result.versionID);
2018-10-16 16:28:42 +00:00
$('.snackbar-container').append(`<div class="alert alert-success snackbar" role="alert">${result.message}</div>`);
if(newCategory) {
if(!!result.newCategoryID) {
let categories = postCategories;
categories.splice(categories.indexOf('new-category'), 1);
categories.push(result.newCategoryID.toString());
$('#postCategory').append(`<option value="${result.newCategoryID}">${newCategoryDisplayName}</option>`);
setTimeout(() => {
$('#postCategory').val(categories);
}, 250);
$('#cat-name').val('');
$('#cat-dname').val('');
} else {
$('.snackbar-container').append('<div class="alert alert-warning snackbar" role="alert">Die neue Kategorie konnte nicht erstellt werden.</div>');
}
}
2018-10-16 16:28:42 +00:00
} 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(),
versionID = $('#versionID').val(),
versionDE = $('#switchLanguages').find('> li[data-lang=de]').data('versionid'),
versionEN = $('#switchLanguages').find('> li[data-lang=en]').data('versionid'),
versionFR = $('#switchLanguages').find('> li[data-lang=fr]').data('versionid');
2018-10-16 16:28:42 +00:00
$.ajax({
url: '/admin/blog/publishPost',
2018-10-16 16:28:42 +00:00
method: 'post',
data: {
postID, versionID,
versionIDs: {'de': versionDE, 'en': versionEN, 'fr': versionFR}
2018-10-16 16:28:42 +00:00
},
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(() => {
2018-10-16 16:28:42 +00:00
$(this).button('loading');
sendPost();
});
$('#blogSubmit').click(() => {
2018-10-16 16:28:42 +00:00
$(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();
}
}
}
});
}
2018-10-16 16:28:42 +00:00
// 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',
2018-10-16 16:28:42 +00:00
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) {
2018-10-16 16:28:42 +00:00
return function findMatches(q, cb) {
let matches, substrRegex;
2018-10-16 16:28:42 +00:00
// 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 #.');
2018-10-16 16:28:42 +00:00
// 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);
2018-10-16 16:28:42 +00:00
matches.push(str);
}
});
cb(matches);
};
}