let NoticeEditor = (function () {
let module = {};
let __ButtonAddNotice = document.querySelector(".notice-add");
if (__ButtonAddNotice) {
__ButtonAddNotice.onclick = addNoticeModal;
}
let __SelectedManipulator = undefined;
/**
* Собрать все данные и отправить на БД
*
* @param {HTMLInputElement} caption
* @param {HTMLInputElement} link
* @param {HTMLDivElement} content
* @param {HTMLDivElement} images
* @param {HTMLInputElement} file
*/
function create(caption, link, content, images, file) {
if (!caption || !link || !content || !images) {
Messenger.Show("Некоторые элементы не были найдены, невозможно создать новость!");
return;
}
if (caption.value.length == 0) {
Messenger.Show("Необходимо заполнить заголовок!");
return;
}
if (link.value.length == 0) {
link.value = Main.GenerateHash256();
}
let preview = {
Valid: true,
String: "",
};
let contentHtml = "";
for (const c of content.blocks) {
switch (c.type) {
case "paragraph":
contentHtml += "
" + c.data.text + "
";
preview.String += c.data.text;
break;
case "header":
contentHtml += "" + c.data.text + "/h" + c.data.level + ">";
preview.String += c.data.text;
break;
case "list":
if (c.data.style === "ordered") {
contentHtml += "";
for (const li of c.data.items) {
contentHtml += "- " + li + "
";
preview.String += li;
}
contentHtml += "
";
} else {
contentHtml += "";
for (const li of c.data.items) {
contentHtml += "- " + li + "
";
preview.String += li;
}
contentHtml += "
";
}
break;
case "delimiter":
contentHtml += "
";
break;
case "table":
contentHtml += "";
for (const row of c.data.content) {
contentHtml += "";
for (const col of row) {
contentHtml += "" + col + " | ";
preview.String += col;
}
contentHtml += "
";
}
contentHtml += "
";
break;
}
}
if (preview.String.length > 260) {
preview.String = preview.String.slice(0, 260);
}
var date = new Date();
let m = ("00" + (date.getMonth() + 1)).slice(-2);
let d = ("00" + date.getDate()).slice(-2);
var imageFullpath = "image/notice/" + date.getUTCFullYear().toString() + "-" + m + "-" + d + "/";
var thumbFullpath = "thumb/notice/" + date.getUTCFullYear().toString() + "-" + m + "-" + m + "/";
let selectedImage = {
Valid: false,
String: "",
};
let selectedInput = images.querySelector("input:checked");
if (selectedInput) {
let img = selectedInput.closest(".image").querySelector("img");
if (img) {
selectedImage.String = thumbFullpath + img.alt.toLowerCase();
selectedImage.Valid = true;
}
}
let data = new FormData();
if (file.files.length > 0) {
contentHtml += '';
for (const f of file.files) {
let filename = f.name.toLowerCase();
contentHtml +=
'
';
data.append("Files", f, filename);
}
contentHtml += "
";
}
data.set("Caption", caption.value);
data.set("Link", link.value);
data.set("Content", contentHtml);
data.set("Source", JSON.stringify(content));
data.set("PreviewValid", preview.Valid);
data.set("PreviewString", preview.String);
data.set("ImageValid", selectedImage.Valid);
data.set("ImageString", selectedImage.String);
data.set("ImagePath", imageFullpath);
data.set("ThumbPath", thumbFullpath);
let closeModal = this.closest(".modal").querySelector(".close");
XHR.POST(
function (result) {
if (result && "Error" in result) {
if (result.Error === null) {
Messenger.Show("Объявление успешно добавлено");
closeModal.click();
} else {
Messenger.Show("Возникла ошибка добавления объявления. " + result.Error);
}
}
},
"/material-insert/" + MATERIAL_CATEGORY.NOTICE,
data,
null,
true,
true
);
}
/**
* Создать модальное окно для добавления новости
*/
function addNoticeModal() {
let body = document.createElement("div"),
inputCaption = document.createElement("input"),
inputLink = document.createElement("input"),
contentBlock = document.createElement("div"),
previewBlock = document.createElement("div"),
preview = document.createElement("div"),
label = document.createElement("label"),
file = document.createElement("input"),
fileButton = document.createElement("div"),
buttonSend = document.createElement("button");
label.append(file, fileButton);
label.className = "select-file";
fileButton.className = "button";
fileButton.textContent = "Выбрать изображениие";
file.type = "file";
file.multiple = false;
file.accept = "image/*";
file.onchange = changeImages;
inputCaption.type = "text";
inputCaption.placeholder = "Заголовок/название (обязательно)";
inputLink.type = "text";
inputLink.disabled = true;
inputLink.placeholder = "Ссылка (не обязательно)";
buttonSend.textContent = "Создать";
// buttonSend.onclick = create.bind(buttonSend, inputCaption, inputLink, contentBlock, preview, file);
preview.className = "preview-images";
contentBlock.id = "editorjs";
contentBlock.className = "news-content-editor";
// contentBlock.append(createManipulator());
body.append(inputCaption, inputLink, contentBlock, previewBlock, label, preview, buttonSend);
const editor = new EditorJS({
holderOd: "editorjs",
tools: {
header: {
class: Header,
inlineToolbar: true,
config: {
placeholder: "Заголовок",
},
shortcut: "CMD+SHIFT+H",
},
list: {
class: List,
inlineToolbar: true,
shortcut: "CMD+SHIFT+L",
},
marker: {
class: Marker,
shortcut: "CMD+SHIFT+M",
},
delimiter: Delimiter,
inlineCode: {
class: InlineCode,
shortcut: "CMD+SHIFT+C",
},
linkTool: LinkTool,
table: {
class: Table,
inlineToolbar: true,
shortcut: "CMD+ALT+T",
},
onReady: function () {
// saveButton.click();
},
onChange: function () {
console.log("something changed");
},
},
data: null,
});
buttonSend.addEventListener("click", function () {
editor.save().then((savedData) => {
console.log(savedData);
create.call(buttonSend, inputCaption, inputLink, savedData, preview, file);
});
});
Modal.Create("Создать объявление", body);
}
/**
* Функция выбора файлов изображения для новости
*/
function changeImages() {
let preview = document.querySelector(".preview-images");
if (!preview) {
console.warn("Элемент [.preview-images] не найжен");
return;
}
while (preview.children.length > 0) {
preview.children[0].remove();
}
for (const file of this.files) {
/**
* 1. Контейнер под изображение
*/
let div = document.createElement("div");
div.className = "image";
/**
* 2. Создать элемент для изображения
*/
let img = document.createElement("img");
img.src = window.URL.createObjectURL(file);
img.alt = file.name;
img.height = 100;
/**
* 3. Создать label
*/
let label = document.createElement("label");
/**
* 4. Создать input + span
*/
let input = document.createElement("input");
input.type = "radio";
input.dataset.image = file.name;
input.name = "preview-images";
let span = document.createElement("span");
div.append(img, label);
label.append(input, span);
preview.append(div);
}
let firstImage = preview.querySelector("input");
firstImage.click();
}
return module;
})();