const usernames = [
"HappyTiger", "BraveElephant", "GentlePanda", "CuriousDolphin", "KindRabbit"
];
async function assignUsername() {
let deviceId = localStorage.getItem("deviceId");
if (!deviceId) {
deviceId = "device_" + Math.random().toString(36).substr(2, 9);
localStorage.setItem("deviceId", deviceId);
}
const userRef = db.collection("users").doc(deviceId);
const doc = await userRef.get();
if (doc.exists) {
localStorage.setItem("username", doc.data().username);
} else {
const newUsername = usernames[Math.floor(Math.random() * usernames.length)];
await userRef.set({ username: newUsername });
localStorage.setItem("username", newUsername);
}
}
async function submitPost() {
const title = document.getElementById("post-title").value.trim();
const content = document.getElementById("post-content").value.trim();
const imageInput = document.getElementById("post-image");
const username = localStorage.getItem("username") || "AnonymousUser";
if (!title || !content) return;
const reader = new FileReader();
reader.onload = async function(event) {
await db.collection("posts").add({
title,
content,
image: imageInput.files.length ? event.target.result : "",
likes: 0,
username,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
loadPosts();
};
if (imageInput.files.length) {
reader.readAsDataURL(imageInput.files[0]);
} else {
reader.onload();
}
}
async function loadPosts() {
const postsContainer = document.getElementById("posts");
postsContainer.innerHTML = "";
const querySnapshot = await db.collection("posts").orderBy("timestamp", "desc").get();
querySnapshot.forEach((doc) => {
const post = doc.data();
const postId = doc.id;
const currentUsername = localStorage.getItem("username") || "AnonymousUser";
const isOwner = post.username === currentUsername;
const isLiked = localStorage.getItem(`liked_${postId}`) === "true";
const postElement = document.createElement("div");
postElement.classList.add("forum-post");
postElement.innerHTML = `
${post.title}
${post.content}
Posted by: ${post.username}
${post.image ? `
` : ''}
${post.likes} Likes
${isOwner ? `Delete` : ""}
`;
postsContainer.appendChild(postElement);
});
}
async function likePost(postId) {
const postRef = db.collection("posts").doc(postId);
const doc = await postRef.get();
if (doc.exists && !localStorage.getItem(`liked_${postId}`)) {
const currentLikes = doc.data().likes || 0;
await postRef.update({ likes: currentLikes + 1 });
localStorage.setItem(`liked_${postId}`, "true");
loadPosts();
}
}
async function deletePost(postId) {
const postRef = db.collection("posts").doc(postId);
const doc = await postRef.get();
if (doc.exists && doc.data().username === localStorage.getItem("username")) {
await postRef.delete();
loadPosts();
}
}
document.addEventListener("DOMContentLoaded", async function() {
await assignUsername();
loadPosts();
});
Подробнее здесь: https://stackoverflow.com/questions/794 ... and-github
Мобильная версия