openvk/Web/static/js/al_wall.js
2023-08-20 15:38:21 +03:00

504 lines
No EOL
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

function humanFileSize(bytes, si) {
var thresh = si ? 1000 : 1024;
if(Math.abs(bytes) < thresh) {
return bytes + ' B';
}
var units = si
? ['kB','MB','GB','TB','PB','EB','ZB','YB']
: ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];
var u = -1;
do {
bytes /= thresh;
++u;
} while(Math.abs(bytes) >= thresh && u < units.length - 1);
return bytes.toFixed(1)+' '+units[u];
}
function trim(string) {
var newStr = string.substring(0, 10);
if(newStr.length !== string.length)
newStr += "…";
return newStr;
}
function handleUpload(id) {
console.warn("блять...");
u("#post-buttons" + id + " .postFileSel").not("#" + this.id).each(input => input.value = null);
var indicator = u("#post-buttons" + id + " .post-upload");
var file = this.files[0];
if(typeof file === "undefined") {
indicator.attr("style", "display: none;");
} else {
u("span", indicator.nodes[0]).text(trim(file.name) + " (" + humanFileSize(file.size, false) + ")");
indicator.attr("style", "display: block;");
}
document.querySelector("#post-buttons" + id + " #wallAttachmentMenu").classList.add("hidden");
}
function initGraffiti(id) {
let canvas = null;
let msgbox = MessageBox(tr("draw_graffiti"), "<div id='ovkDraw'></div>", [tr("save"), tr("cancel")], [function() {
canvas.getImage({includeWatermark: false}).toBlob(blob => {
let fName = "Graffiti-" + Math.ceil(performance.now()).toString() + ".jpeg";
let image = new File([blob], fName, {type: "image/jpeg", lastModified: new Date().getTime()});
let trans = new DataTransfer();
trans.items.add(image);
let fileSelect = document.querySelector("#post-buttons" + id + " input[name='_pic_attachment']");
fileSelect.files = trans.files;
u(fileSelect).trigger("change");
u("#post-buttons" + id + " #write textarea").trigger("focusin");
}, "image/jpeg", 0.92);
canvas.teardown();
}, function() {
canvas.teardown();
}]);
let watermarkImage = new Image();
watermarkImage.src = "/assets/packages/static/openvk/img/logo_watermark.gif";
msgbox.attr("style", "width: 750px;");
canvas = LC.init(document.querySelector("#ovkDraw"), {
backgroundColor: "#fff",
imageURLPrefix: "/assets/packages/static/openvk/js/node_modules/literallycanvas/lib/img",
watermarkImage: watermarkImage,
imageSize: {
width: 640,
height: 480
}
});
}
u(".post-like-button").on("click", function(e) {
e.preventDefault();
var thisBtn = u(this).first();
var link = u(this).attr("href");
var heart = u(".heart", thisBtn);
var counter = u(".likeCnt", thisBtn);
var likes = counter.text() === "" ? 0 : counter.text();
var isLiked = heart.attr("id") === 'liked';
ky(link);
heart.attr("id", isLiked ? '' : 'liked');
counter.text(parseInt(likes) + (isLiked ? -1 : 1));
if (counter.text() === "0") {
counter.text("");
}
return false;
});
function setupWallPostInputHandlers(id) {
u("#wall-post-input" + id).on("paste", function(e) {
if(e.clipboardData.files.length === 1) {
var input = u("#post-buttons" + id + " input[name=_pic_attachment]").nodes[0];
input.files = e.clipboardData.files;
u(input).trigger("change");
}
});
u("#wall-post-input" + id).on("input", function(e) {
var boost = 5;
var textArea = e.target;
textArea.style.height = "5px";
var newHeight = textArea.scrollHeight;
textArea.style.height = newHeight + boost + "px";
return;
// revert to original size if it is larger (possibly changed by user)
// textArea.style.height = (newHeight > originalHeight ? (newHeight + boost) : originalHeight) + "px";
});
}
u("#write > form").on("keydown", function(event) {
if(event.ctrlKey && event.keyCode === 13)
this.submit();
});
var tooltipClientTemplate = Handlebars.compile(`
<table>
<tr>
<td width="54" valign="top">
<img src="{{img}}" width="54" />
</td>
<td width="1"></td>
<td width="150" valign="top">
<text>
{{app_tr}}: <b>{{name}}</b>
</text><br/>
<a href="{{url}}">${tr("learn_more")}</a>
</td>
</tr>
</table>
`);
var tooltipClientNoInfoTemplate = Handlebars.compile(`
<table>
<tr>
<td width="150" valign="top">
<text>
{{app_tr}}: <b>{{name}}</b>
</text><br/>
</td>
</tr>
</table>
`);
tippy(".client_app", {
theme: "light vk",
content: "⌛",
allowHTML: true,
interactive: true,
interactiveDebounce: 500,
onCreate: async function(that) {
that._resolvedClient = null;
},
onShow: async function(that) {
let client_tag = that.reference.dataset.appTag;
let client_name = that.reference.dataset.appName;
let client_url = that.reference.dataset.appUrl;
let client_img = that.reference.dataset.appImg;
if(client_name != "") {
let res = {
'name': client_name,
'url': client_url,
'img': client_img,
'app_tr': tr("app")
};
that.setContent(tooltipClientTemplate(res));
} else {
let res = {
'name': client_tag,
'app_tr': tr("app")
};
that.setContent(tooltipClientNoInfoTemplate(res));
}
}
});
function addNote(textareaId, nid)
{
if(nid > 0) {
document.getElementById("note").value = nid
let noteObj = document.querySelector("#nd"+nid)
let nortd = document.querySelector("#post-buttons"+textareaId+" .post-has-note");
nortd.style.display = "block"
nortd.innerHTML = `${tr("note")} ${escapeHtml(noteObj.dataset.name)}`
} else {
document.getElementById("note").value = "none"
let nortd = document.querySelector("#post-buttons"+textareaId+" .post-has-note");
nortd.style.display = "none"
nortd.innerHTML = ""
}
u("body").removeClass("dimmed");
u(".ovk-diag-cont").remove();
}
async function attachNote(id)
{
let notes = await API.Wall.getMyNotes()
let body = ``
if(notes.closed < 1) {
body = `${tr("notes_closed")}`
} else {
if(notes.items.length < 1) {
body = `${tr("no_notes")}`
} else {
body = `
${tr("select_or_create_new")}
<div id="notesList">`
if(document.getElementById("note").value != "none") {
body += `
<div class="ntSelect" onclick="addNote(${id}, 0)">
<span>${tr("do_not_attach_note")}</span>
</div>`
}
for(const note of notes.items) {
body += `
<div data-name="${note.name}" class="ntSelect" id="nd${note.id}" onclick="addNote(${id}, ${note.id})">
<span>${escapeHtml(note.name)}</span>
</div>
`
}
body += `</div>`
}
}
let frame = MessageBox(tr("select_note"), body, [tr("cancel")], [Function.noop]);
document.querySelector(".ovk-diag-body").style.padding = "10px"
}
async function showArticle(note_id) {
u("body").addClass("dimmed");
let note = await API.Notes.getNote(note_id);
u("#articleAuthorAva").attr("src", note.author.ava);
u("#articleAuthorName").text(note.author.name);
u("#articleAuthorName").attr("href", note.author.link);
u("#articleTime").text(note.created);
u("#articleLink").attr("href", note.link);
u("#articleText").html(`<h1 class="articleView_nameHeading">${note.title}</h1>` + note.html);
u("body").removeClass("dimmed");
u("body").addClass("article");
}
$(document).on("click", "#publish_post", async (e) => {
let id = Number(e.currentTarget.dataset.id)
let post;
let body = `
<textarea id="pooblish" style="max-height:500px;resize:vertical;min-height:54px;"></textarea>
<label><input type="checkbox" id="signatr" checked>${tr("add_signature")}</label>
`
MessageBox(tr("publishing_suggested_post"), body, [tr("publish"), tr("cancel")], [(async () => {
let id = Number(e.currentTarget.dataset.id)
let post;
try {
e.currentTarget.classList.add("loaded")
e.currentTarget.setAttribute("value", "")
e.currentTarget.setAttribute("id", "")
post = await API.Wall.acceptPost(id, document.getElementById("signatr").checked, document.getElementById("pooblish").value)
} catch(ex) {
switch(ex.code) {
case 11:
MessageBox(tr("error"), tr("error_declining_invalid_post"), [tr("ok")], [Function.noop]);
break;
case 19:
MessageBox(tr("error"), tr("error_declining_not_suggested_post"), [tr("ok")], [Function.noop]);
break;
case 10:
MessageBox(tr("error"), tr("error_declining_declined_post"), [tr("ok")], [Function.noop]);
break;
case 22:
MessageBox(tr("error"), "Access denied", [tr("ok")], [Function.noop]);
break;
default:
MessageBox(tr("error"), "Unknown error "+ex.code+": "+ex.message, [tr("ok")], [Function.noop]);
break;
}
e.currentTarget.setAttribute("value", tr("publish_suggested"))
e.currentTarget.classList.remove("loaded")
e.currentTarget.setAttribute("id", "publish_post")
return 0;
}
NewNotification(tr("suggestion_succefully_published"), tr("suggestion_press_to_go"), null, () => {window.location.assign("/wall" + post.id)});
if(document.getElementById("cound") != null) {
document.getElementById("cound").innerHTML = tr("suggested_posts_in_group", post.new_count)
} else {
document.getElementById("cound_r").innerHTML = tr("suggested_by_everyone", post.new_count)
}
if(document.querySelector("object a[href='"+location.pathname+"'] b") != null) {
document.querySelector("object a[href='"+location.pathname+"'] b").innerHTML = post.new_count
if(post.new_count < 1) {
u("object a[href='"+location.pathname+"']").remove()
}
}
if(e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode.tagName == "TABLE") {
e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode.outerHTML = ""
} else {
e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.outerHTML = ""
}
if(document.querySelectorAll("#postz .post").length < 1 && post.new_count > 0 && document.querySelector(".paginator") != null) {
loadMoreSuggestedPosts()
}
}), Function.noop]);
document.getElementById("pooblish").innerHTML = e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode.querySelector(".really_text").innerHTML.replace(/(<([^>]+)>)/gi, '')
document.querySelector(".ovk-diag-body").style.padding = "9px";
})
$(document).on("click", "#decline_post", async (e) => {
let id = Number(e.currentTarget.dataset.id)
let post;
try {
e.currentTarget.classList.add("loaded")
e.currentTarget.setAttribute("value", "")
e.currentTarget.setAttribute("id", "")
post = await API.Wall.declinePost(id)
} catch(ex) {
switch(ex.code) {
case 11:
MessageBox(tr("error"), tr("error_declining_invalid_post"), [tr("ok")], [Function.noop]);
break;
case 19:
MessageBox(tr("error"), tr("error_declining_not_suggested_post"), [tr("ok")], [Function.noop]);
break;
case 10:
MessageBox(tr("error"), tr("error_declining_declined_post"), [tr("ok")], [Function.noop]);
break;
case 22:
MessageBox(tr("error"), "Access denied", [tr("ok")], [Function.noop]);
break;
default:
MessageBox(tr("error"), "Unknown error "+ex.code+": "+ex.message, [tr("ok")], [Function.noop]);
break;
}
e.currentTarget.setAttribute("value", tr("decline_suggested"))
e.currentTarget.setAttribute("id", "decline_post")
e.currentTarget.classList.remove("loaded")
return 0;
}
//NewNotification(tr("suggestion_succefully_declined"), "", null);
if(e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode.tagName == "TABLE") {
e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode.outerHTML = ""
} else {
e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.outerHTML = ""
}
if(document.getElementById("cound") != null) {
document.getElementById("cound").innerHTML = tr("suggested_posts_in_group", post)
} else {
document.getElementById("cound_r").innerHTML = tr("suggested_by_everyone", post)
}
if(document.querySelector("object a[href='"+location.pathname+"'] b") != null) {
document.querySelector("object a[href='"+location.pathname+"'] b").innerHTML = post
if(post < 1) {
u("object a[href='"+location.pathname+"']").remove()
}
}
if(document.querySelectorAll("#postz .post").length < 1 && post > 0 && document.querySelector(".paginator") != null) {
loadMoreSuggestedPosts()
}
})
function loadMoreSuggestedPosts()
{
let xhr = new XMLHttpRequest
let link = location.href
if(!link.includes("/suggested")) {
link += "/suggested"
}
xhr.open("GET", link)
xhr.onloadstart = () => {
document.getElementById("postz").innerHTML = `<img src="/assets/packages/static/openvk/img/loading_mini.gif">`
}
xhr.onload = () => {
let parser = new DOMParser()
let body = parser.parseFromString(xhr.responseText, "text/html").getElementById("postz")
if(body.querySelectorAll(".post").length < 1) {
let url = new URL(location.href)
url.searchParams.set("p", url.searchParams.get("p") - 1)
if(url.searchParams.get("p") < 1) {
return 0;
}
// OVK AJAX ROUTING ??????????
history.pushState({}, "", url)
loadMoreSuggestedPosts()
}
document.getElementById("postz").innerHTML = body.innerHTML
}
xhr.onerror = () => {
document.getElementById("postz").innerHTML = tr("error_loading_suggest")
}
xhr.send()
}
// нажатие на "x предложенных записей"
$(document).on("click", ".sugglist a", (e) => {
e.preventDefault()
if(e.currentTarget.getAttribute("data-toogled") == null || e.currentTarget.getAttribute("data-toogled") == "false") {
e.currentTarget.setAttribute("data-toogled", "true")
document.getElementById("underHeader").style.display = "none"
document.querySelector(".insertThere").style.display = "block"
history.pushState({}, "", e.currentTarget.href)
// если ещё ничего не подгружалось
if(document.querySelector(".insertThere").innerHTML == "") {
let xhr = new XMLHttpRequest
xhr.open("GET", e.currentTarget.href)
xhr.onloadstart = () => {
// лоадер
document.querySelector(".insertThere").insertAdjacentHTML("afterbegin", `<img src="/assets/packages/static/openvk/img/loading_mini.gif">`)
}
xhr.onload = () => {
let parser = new DOMParser
let result = parser.parseFromString(xhr.responseText, 'text/html').querySelector(".infContainer")
// парсинг результата и вставка постов
document.querySelector(".insertThere").innerHTML = result.innerHTML
}
xhr.send()
}
} else {
// переключение на нормальную стену
e.currentTarget.setAttribute("data-toogled", "false")
document.getElementById("underHeader").style.display = "block"
document.querySelector(".insertThere").style.display = "none"
history.pushState({}, "", e.currentTarget.href.replace("/suggested", ""))
}
})
// нажатие на пагинатор у постов пъедложки
$(document).on("click", "#postz .paginator a", (e) => {
e.preventDefault()
let xhr = new XMLHttpRequest
xhr.open("GET", e.currentTarget.href)
xhr.onloadstart = () => {
window.scrollTo({top: 0,behavior: "smooth"})
// после того как долистали наверх, добавляем лоадер
setTimeout(() => {document.querySelector("#postz").innerHTML = `<img src="/assets/packages/static/openvk/img/loading_mini.gif">`}, 500)
}
xhr.onload = () => {
// опять парс
let result = (new DOMParser).parseFromString(xhr.responseText, "text/html").querySelector(".infContainer")
// опять вставка
document.getElementById("postz").innerHTML = result.innerHTML
history.pushState({}, "", e.currentTarget.href)
}
xhr.send()
})