639 lines
26 KiB
JavaScript
639 lines
26 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
// --- INDEXED DB HELPERS (For >5MB Storage) ---
|
|
const DB_NAME = 'SocialAppDB';
|
|
const DB_VERSION = 1;
|
|
|
|
function openDB() {
|
|
return new Promise((resolve, reject) => {
|
|
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
|
request.onerror = () => reject(request.error);
|
|
request.onsuccess = () => resolve(request.result);
|
|
request.onupgradeneeded = (e) => {
|
|
const db = e.target.result;
|
|
if (!db.objectStoreNames.contains('images')) {
|
|
db.createObjectStore('images', { keyPath: 'id' });
|
|
}
|
|
};
|
|
});
|
|
}
|
|
|
|
async function saveImageToDB(id, dataUrl) {
|
|
try {
|
|
const db = await openDB();
|
|
return new Promise((resolve, reject) => {
|
|
const tx = db.transaction('images', 'readwrite');
|
|
const store = tx.objectStore('images');
|
|
store.put({ id, data: dataUrl });
|
|
tx.oncomplete = () => resolve();
|
|
tx.onerror = () => reject(tx.error);
|
|
});
|
|
} catch (e) {
|
|
console.error('IndexedDB Save Error:', e);
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
async function getImageFromDB(id) {
|
|
try {
|
|
const db = await openDB();
|
|
return new Promise((resolve, reject) => {
|
|
const tx = db.transaction('images', 'readonly');
|
|
const store = tx.objectStore('images');
|
|
const request = store.get(id);
|
|
request.onsuccess = () => resolve(request.result ? request.result.data : null);
|
|
request.onerror = () => reject(request.error);
|
|
});
|
|
} catch (e) {
|
|
console.error('IndexedDB Read Error:', e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function deleteImageFromDB(id) {
|
|
try {
|
|
const db = await openDB();
|
|
return new Promise((resolve, reject) => {
|
|
const tx = db.transaction('images', 'readwrite');
|
|
const store = tx.objectStore('images');
|
|
store.delete(id);
|
|
tx.oncomplete = () => resolve();
|
|
tx.onerror = () => reject(tx.error);
|
|
});
|
|
} catch (e) {
|
|
console.error('IndexedDB Delete Error:', e);
|
|
}
|
|
}
|
|
|
|
// --- QUERY SELECTORS ---
|
|
const loginForm = document.querySelector('.login-form');
|
|
const loginContainer = document.querySelector('.login-container');
|
|
const feedView = document.getElementById('feed-view');
|
|
const emailInput = document.getElementById('email');
|
|
const passwordInput = document.getElementById('password');
|
|
const confirmPasswordInput = document.getElementById('confirm-password');
|
|
const confirmPasswordGroup = document.getElementById('confirm-password-group');
|
|
const submitBtn = document.querySelector('.btn-primary');
|
|
const btnText = submitBtn ? submitBtn.querySelector('span') : null;
|
|
const toggleLink = document.querySelector('.signup-link a');
|
|
const title = document.querySelector('.brand-section h1');
|
|
const subtitle = document.querySelector('.brand-section p');
|
|
|
|
// Post Creation Elements
|
|
const createPostView = document.getElementById('create-post-view');
|
|
const cancelPostBtn = document.getElementById('cancel-post-btn');
|
|
const sharePostBtn = document.getElementById('share-post-btn');
|
|
const uploadTrigger = document.getElementById('upload-trigger');
|
|
const imageInput = document.getElementById('post-image-input');
|
|
const imagePreview = document.getElementById('image-preview');
|
|
const captionInput = document.getElementById('post-caption-input');
|
|
const navPostBtn = document.querySelector('.nav-btn:nth-child(2)');
|
|
const navHomeBtn = document.querySelector('.nav-btn:first-child');
|
|
|
|
let isLoginMode = true;
|
|
|
|
// --- AUTH LOGIC ---
|
|
if (toggleLink) {
|
|
toggleLink.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
isLoginMode = !isLoginMode;
|
|
updateUI();
|
|
});
|
|
}
|
|
|
|
function updateUI() {
|
|
if (!title || !subtitle || !btnText || !confirmPasswordGroup) return;
|
|
|
|
if (isLoginMode) {
|
|
title.innerText = 'Welcome Back';
|
|
subtitle.innerText = 'Enter your details below';
|
|
btnText.innerText = 'Sign In';
|
|
const helper = document.querySelector('.signup-link');
|
|
if (helper) helper.innerHTML = 'Don\'t have an account? <a href="#">Create One</a>';
|
|
confirmPasswordGroup.classList.add('hidden');
|
|
confirmPasswordInput.required = false;
|
|
} else {
|
|
title.innerText = 'Create Account';
|
|
subtitle.innerText = 'Start your journey with us';
|
|
btnText.innerText = 'Sign Up';
|
|
const helper = document.querySelector('.signup-link');
|
|
if (helper) helper.innerHTML = 'Already have an account? <a href="#">Sign In</a>';
|
|
confirmPasswordGroup.classList.remove('hidden');
|
|
confirmPasswordInput.required = true;
|
|
}
|
|
|
|
const newLink = document.querySelector('.signup-link a');
|
|
if (newLink) {
|
|
newLink.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
isLoginMode = !isLoginMode;
|
|
updateUI();
|
|
});
|
|
}
|
|
|
|
if (loginForm) loginForm.reset();
|
|
resetButton();
|
|
}
|
|
|
|
function resetButton() {
|
|
if (!submitBtn || !btnText) return;
|
|
submitBtn.style.background = '';
|
|
submitBtn.style.transform = '';
|
|
btnText.innerText = isLoginMode ? 'Sign In' : 'Sign Up';
|
|
}
|
|
|
|
function showFeedback(isSuccess, message) {
|
|
if (!btnText || !submitBtn) return;
|
|
btnText.innerText = message;
|
|
if (isSuccess) {
|
|
submitBtn.style.background = 'linear-gradient(135deg, #10B981 0%, #059669 100%)';
|
|
} else {
|
|
submitBtn.style.background = 'linear-gradient(135deg, #EF4444 0%, #B91C1C 100%)';
|
|
submitBtn.animate([
|
|
{ transform: 'translateX(0)' },
|
|
{ transform: 'translateX(-5px)' },
|
|
{ transform: 'translateX(5px)' },
|
|
{ transform: 'translateX(0)' }
|
|
], { duration: 300 });
|
|
}
|
|
|
|
setTimeout(() => {
|
|
if (!message.includes('Success')) {
|
|
resetButton();
|
|
}
|
|
}, 2000);
|
|
}
|
|
|
|
function navigateToFeed() {
|
|
if (loginContainer && feedView) {
|
|
loginContainer.style.opacity = '0';
|
|
setTimeout(() => {
|
|
loginContainer.classList.add('hidden');
|
|
loginContainer.style.display = 'none';
|
|
|
|
feedView.classList.remove('hidden');
|
|
void feedView.offsetWidth; // Reflow
|
|
feedView.classList.add('fade-in');
|
|
|
|
initFeed(); // Load data (Async)
|
|
|
|
setTimeout(() => {
|
|
feedView.classList.remove('fade-in');
|
|
}, 600);
|
|
}, 600);
|
|
}
|
|
}
|
|
|
|
if (loginForm) {
|
|
loginForm.addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
const email = emailInput.value.trim();
|
|
const password = passwordInput.value.trim();
|
|
const confirmPassword = confirmPasswordInput.value.trim();
|
|
const timestamp = new Date().toISOString();
|
|
const existingUsers = JSON.parse(localStorage.getItem('socialAppUsers') || '[]');
|
|
|
|
if (isLoginMode) {
|
|
const user = existingUsers.find(u => u.email === email && u.password === password);
|
|
if (user) {
|
|
showFeedback(true, 'Success!');
|
|
setTimeout(navigateToFeed, 1000);
|
|
} else {
|
|
showFeedback(false, 'Incorrect details');
|
|
}
|
|
} else {
|
|
if (existingUsers.some(u => u.email === email)) {
|
|
showFeedback(false, 'User exists');
|
|
return;
|
|
}
|
|
if (password !== confirmPassword) {
|
|
showFeedback(false, 'Passwords do not match');
|
|
return;
|
|
}
|
|
const newUser = { email, password, joinedAt: timestamp };
|
|
existingUsers.push(newUser);
|
|
localStorage.setItem('socialAppUsers', JSON.stringify(existingUsers));
|
|
showFeedback(true, 'Account Created!');
|
|
setTimeout(() => {
|
|
isLoginMode = true;
|
|
updateUI();
|
|
setTimeout(navigateToFeed, 1000);
|
|
}, 1500);
|
|
}
|
|
});
|
|
}
|
|
|
|
// --- DATA HELPERS ---
|
|
function getPostState() {
|
|
return JSON.parse(localStorage.getItem('socialAppPostState') || '{}');
|
|
}
|
|
function savePostState(state) {
|
|
localStorage.setItem('socialAppPostState', JSON.stringify(state));
|
|
}
|
|
function isPostDeleted(id) {
|
|
const deletedPosts = JSON.parse(localStorage.getItem('socialAppDeletedPosts') || '[]');
|
|
return deletedPosts.includes(id);
|
|
}
|
|
|
|
// --- ASYNC LOAD FEED ---
|
|
async function initFeed() {
|
|
// 1. Render User Posts (Fetch images from DB)
|
|
const savedUserPosts = JSON.parse(localStorage.getItem('socialAppUserPosts') || '[]');
|
|
|
|
// Use a loop to handle async properly
|
|
const postsToRender = [...savedUserPosts].reverse();
|
|
|
|
for (const post of postsToRender) {
|
|
if (!isPostDeleted(post.id) && !document.querySelector(`[data-post-id="${post.id}"]`)) {
|
|
// Try to get image from DB, fallback to post.imageSrc (legacy support)
|
|
let imgSrc = post.imageSrc;
|
|
if (!imgSrc || imgSrc.length < 100) { // If it's a placeholder (null)
|
|
const dbImg = await getImageFromDB(post.id);
|
|
if (dbImg) imgSrc = dbImg;
|
|
}
|
|
|
|
if (imgSrc) {
|
|
const postWithImg = { ...post, imageSrc: imgSrc };
|
|
renderPost(postWithImg, true);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Restore Interaction State (Likes/Comments)
|
|
// Give a small delay to ensure rendering catches up or run immediately
|
|
const state = getPostState();
|
|
document.querySelectorAll('.post-card').forEach(card => {
|
|
const id = card.getAttribute('data-post-id');
|
|
if (id && isPostDeleted(id)) {
|
|
card.remove();
|
|
return;
|
|
}
|
|
if (id && state[id]) {
|
|
const data = state[id];
|
|
const likeIcon = card.querySelector('.heart-icon');
|
|
const likesText = card.querySelector('.likes');
|
|
if (likeIcon && likesText) {
|
|
if (data.liked) {
|
|
likeIcon.classList.add('liked');
|
|
likeIcon.style.fill = '#EF4444';
|
|
likeIcon.style.stroke = '#EF4444';
|
|
}
|
|
likesText.innerText = data.likesCount + ' likes';
|
|
}
|
|
const commentsContainer = card.querySelector('.added-comments');
|
|
if (commentsContainer) {
|
|
commentsContainer.innerHTML = '';
|
|
if (data.comments) {
|
|
data.comments.forEach(text => {
|
|
const el = document.createElement('div');
|
|
el.classList.add('comment-item');
|
|
el.innerHTML = `<span class="comment-user">you</span> ${text}`;
|
|
commentsContainer.appendChild(el);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
// --- RENDER POST ---
|
|
function renderPost(post, prepend = false) {
|
|
// Avoid duplicates
|
|
if (document.querySelector(`[data-post-id="${post.id}"]`)) return;
|
|
|
|
const feedContainer = document.querySelector('.feed-container');
|
|
const article = document.createElement('article');
|
|
article.className = 'post-card';
|
|
article.setAttribute('data-post-id', post.id);
|
|
|
|
const isUserPost = post.id && post.id.startsWith('post_');
|
|
const optionsHTML = isUserPost ? `
|
|
<button class="icon-btn-sm options-trigger">
|
|
<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" stroke-width="2"><circle cx="12" cy="12" r="1"></circle><circle cx="19" cy="12" r="1"></circle><circle cx="5" cy="12" r="1"></circle></svg>
|
|
</button>
|
|
<div class="options-menu">
|
|
<button class="menu-btn delete">
|
|
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" stroke-width="2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
|
|
Delete Post
|
|
</button>
|
|
</div>
|
|
` : `<button class="icon-btn-sm">...</button>`;
|
|
|
|
article.innerHTML = `
|
|
<div class="post-header">
|
|
<div class="post-user">
|
|
<img src="https://i.pravatar.cc/150?img=12" alt="User" class="avatar-sm">
|
|
<span class="username">${post.username}</span>
|
|
</div>
|
|
${optionsHTML}
|
|
</div>
|
|
<div class="post-image">
|
|
<img src="${post.imageSrc}" alt="Post">
|
|
</div>
|
|
<div class="post-actions">
|
|
<div class="action-left">
|
|
<button class="icon-btn"><svg viewBox="0 0 24 24" width="24" height="24" stroke="white" fill="none" class="heart-icon"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg></button>
|
|
<button class="icon-btn"><svg viewBox="0 0 24 24" width="24" height="24" stroke="white" fill="none"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path></svg></button>
|
|
</div>
|
|
<button class="icon-btn"><svg viewBox="0 0 24 24" width="24" height="24" stroke="white" fill="none"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path></svg></button>
|
|
</div>
|
|
<div class="post-content">
|
|
<span class="likes">0 likes</span>
|
|
<p><span class="username">${post.username}</span> ${post.caption}</p>
|
|
</div>
|
|
<div class="comment-section">
|
|
<div class="added-comments"></div>
|
|
<div class="comment-input-wrapper">
|
|
<input type="text" class="comment-input" placeholder="Add a comment...">
|
|
<button class="post-btn">Post</button>
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
if (prepend) {
|
|
// Check again for safety inside async flows
|
|
if (!feedContainer.querySelector(`[data-post-id="${post.id}"]`)) {
|
|
feedContainer.insertBefore(article, feedContainer.firstChild);
|
|
}
|
|
}
|
|
else feedContainer.appendChild(article);
|
|
}
|
|
|
|
// --- FEED LISTENERS ---
|
|
if (feedView) {
|
|
initFeed(); // Initial Load logic
|
|
|
|
feedView.addEventListener('click', (e) => {
|
|
const target = e.target;
|
|
|
|
// 1. OPTIONS MENU
|
|
const trigger = target.closest('.options-trigger');
|
|
if (trigger) {
|
|
const header = trigger.closest('.post-header');
|
|
const menu = header.querySelector('.options-menu');
|
|
if (menu) {
|
|
document.querySelectorAll('.options-menu.active').forEach(m => {
|
|
if (m !== menu) m.classList.remove('active');
|
|
});
|
|
menu.classList.toggle('active');
|
|
e.stopPropagation();
|
|
}
|
|
return;
|
|
}
|
|
|
|
// 2. DELETE ACTION
|
|
const deleteBtn = target.closest('.delete');
|
|
if (deleteBtn) {
|
|
const card = deleteBtn.closest('.post-card');
|
|
const id = card.getAttribute('data-post-id');
|
|
|
|
if (id && id.startsWith('post_')) { // Double check ownership
|
|
if (confirm('Delete this post?')) {
|
|
card.style.transition = 'opacity 0.3s, transform 0.3s';
|
|
card.style.opacity = '0';
|
|
card.style.transform = 'scale(0.9)';
|
|
setTimeout(() => card.remove(), 300);
|
|
|
|
let userPosts = JSON.parse(localStorage.getItem('socialAppUserPosts') || '[]');
|
|
userPosts = userPosts.filter(p => p.id !== id);
|
|
localStorage.setItem('socialAppUserPosts', JSON.stringify(userPosts));
|
|
|
|
// Delete from DB too
|
|
deleteImageFromDB(id);
|
|
|
|
// Also ban ID to be safe
|
|
const deletedPosts = JSON.parse(localStorage.getItem('socialAppDeletedPosts') || '[]');
|
|
if (!deletedPosts.includes(id)) {
|
|
deletedPosts.push(id);
|
|
localStorage.setItem('socialAppDeletedPosts', JSON.stringify(deletedPosts));
|
|
}
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
|
|
// 3. LIKE ACTION
|
|
const likeBtn = target.closest('.heart-icon')?.closest('.icon-btn');
|
|
if (likeBtn) {
|
|
const icon = likeBtn.querySelector('.heart-icon');
|
|
const postCard = likeBtn.closest('.post-card');
|
|
const likesText = postCard.querySelector('.likes');
|
|
const postId = postCard.getAttribute('data-post-id');
|
|
|
|
icon.classList.toggle('liked');
|
|
let count = parseInt(likesText.innerText);
|
|
let isLiked = false;
|
|
|
|
if (icon.classList.contains('liked')) {
|
|
icon.style.fill = '#EF4444';
|
|
icon.style.stroke = '#EF4444';
|
|
count++;
|
|
isLiked = true;
|
|
} else {
|
|
icon.style.fill = 'none';
|
|
icon.style.stroke = 'white';
|
|
count--;
|
|
isLiked = false;
|
|
}
|
|
likesText.innerText = count + ' likes';
|
|
|
|
if (postId) {
|
|
const state = getPostState();
|
|
if (!state[postId]) state[postId] = { comments: [] };
|
|
state[postId].liked = isLiked;
|
|
state[postId].likesCount = count;
|
|
if (!state[postId].comments) state[postId].comments = [];
|
|
savePostState(state);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// 4. COMMENT TOGGLE (Updated logic)
|
|
// Identify comment button by checking if it's the 2nd one or has specific path
|
|
const commentBtn = target.closest('.icon-btn');
|
|
if (commentBtn) {
|
|
const svgs = commentBtn.innerHTML;
|
|
if (svgs.includes('M21 11.5')) { // Comment icon path substring
|
|
const postCard = commentBtn.closest('.post-card');
|
|
const commentSection = postCard.querySelector('.comment-section');
|
|
commentSection.classList.toggle('active');
|
|
if (commentSection.classList.contains('active')) {
|
|
const input = commentSection.querySelector('input');
|
|
if (input) input.focus();
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
// 5. POST COMMENT
|
|
if (target.classList.contains('post-btn')) {
|
|
const wrapper = target.closest('.comment-input-wrapper');
|
|
const input = wrapper.querySelector('.comment-input');
|
|
const text = input.value.trim();
|
|
const postCard = wrapper.closest('.post-card');
|
|
const postId = postCard.getAttribute('data-post-id');
|
|
|
|
if (text) {
|
|
addComment(wrapper.closest('.comment-section'), text);
|
|
if (postId) {
|
|
const state = getPostState();
|
|
if (!state[postId]) state[postId] = { liked: false, likesCount: parseInt(postCard.querySelector('.likes').innerText) || 0, comments: [] };
|
|
if (!state[postId].comments) state[postId].comments = [];
|
|
state[postId].comments.push(text);
|
|
savePostState(state);
|
|
}
|
|
input.value = '';
|
|
}
|
|
}
|
|
});
|
|
|
|
// Enter key for comments
|
|
feedView.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter' && e.target.classList.contains('comment-input')) {
|
|
const text = e.target.value.trim();
|
|
const wrapper = e.target.closest('.comment-input-wrapper');
|
|
const postCard = wrapper.closest('.post-card');
|
|
const postId = postCard.getAttribute('data-post-id');
|
|
|
|
if (text) {
|
|
addComment(e.target.closest('.comment-section'), text);
|
|
if (postId) {
|
|
const state = getPostState();
|
|
if (!state[postId]) state[postId] = { liked: false, likesCount: parseInt(postCard.querySelector('.likes').innerText) || 0, comments: [] };
|
|
if (!state[postId].comments) state[postId].comments = [];
|
|
state[postId].comments.push(text);
|
|
savePostState(state);
|
|
}
|
|
e.target.value = '';
|
|
}
|
|
}
|
|
});
|
|
|
|
// Close menus
|
|
document.addEventListener('click', (e) => {
|
|
if (!e.target.closest('.options-menu') && !e.target.closest('.options-trigger')) {
|
|
document.querySelectorAll('.options-menu.active').forEach(m => m.classList.remove('active'));
|
|
}
|
|
});
|
|
}
|
|
|
|
function addComment(section, text) {
|
|
const container = section.querySelector('.added-comments');
|
|
const commentEl = document.createElement('div');
|
|
commentEl.classList.add('comment-item');
|
|
commentEl.innerHTML = `<span class="comment-user">you</span> ${text}`;
|
|
container.appendChild(commentEl);
|
|
}
|
|
|
|
// --- CREATE POST LOGIC ---
|
|
// Navigation
|
|
if (navPostBtn) {
|
|
navPostBtn.addEventListener('click', () => {
|
|
if (feedView && createPostView) {
|
|
feedView.classList.add('hidden');
|
|
createPostView.classList.remove('hidden');
|
|
createPostView.classList.add('fade-in');
|
|
}
|
|
});
|
|
}
|
|
|
|
// Cancel
|
|
if (cancelPostBtn) {
|
|
cancelPostBtn.addEventListener('click', () => {
|
|
resetPostForm();
|
|
createPostView.classList.add('hidden');
|
|
feedView.classList.remove('hidden');
|
|
});
|
|
}
|
|
// Home Nav
|
|
if (navHomeBtn) {
|
|
navHomeBtn.addEventListener('click', () => {
|
|
if (createPostView && !createPostView.classList.contains('hidden')) {
|
|
resetPostForm();
|
|
createPostView.classList.add('hidden');
|
|
feedView.classList.remove('hidden');
|
|
}
|
|
});
|
|
}
|
|
|
|
// Upload
|
|
if (uploadTrigger && imageInput) {
|
|
uploadTrigger.addEventListener('click', () => imageInput.click());
|
|
imageInput.addEventListener('change', (e) => {
|
|
const file = e.target.files[0];
|
|
if (file) {
|
|
const reader = new FileReader();
|
|
reader.onload = (e) => {
|
|
imagePreview.src = e.target.result;
|
|
imagePreview.classList.remove('hidden');
|
|
document.querySelector('.upload-placeholder').classList.add('hidden');
|
|
};
|
|
reader.readAsDataURL(file);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Share (Logic Updated for IndexedDB)
|
|
if (sharePostBtn) {
|
|
sharePostBtn.addEventListener('click', async () => {
|
|
if (!imagePreview.src || imagePreview.classList.contains('hidden')) {
|
|
alert('Please select an image first.');
|
|
return;
|
|
}
|
|
|
|
const caption = captionInput.value.trim();
|
|
const imageSrc = imagePreview.src;
|
|
const id = 'post_' + Date.now();
|
|
|
|
// 1. Render Optimistically (Immediate Feedback)
|
|
const displayPost = {
|
|
id,
|
|
imageSrc,
|
|
caption,
|
|
timestamp: new Date().toISOString(),
|
|
username: 'you',
|
|
likes: 0
|
|
};
|
|
renderPost(displayPost, true);
|
|
|
|
// 2. Save Metadata to LocalStorage (Small footprint)
|
|
// IMPORTANT: We do NOT save the imageSrc string here to save space
|
|
const storagePost = {
|
|
id,
|
|
imageSrc: null, // Placeholder, will look up in DB
|
|
caption,
|
|
timestamp: displayPost.timestamp,
|
|
username: displayPost.username,
|
|
likes: 0
|
|
};
|
|
|
|
const userPosts = JSON.parse(localStorage.getItem('socialAppUserPosts') || '[]');
|
|
userPosts.unshift(storagePost);
|
|
localStorage.setItem('socialAppUserPosts', JSON.stringify(userPosts));
|
|
|
|
// 3. Save Image Data to IndexedDB (Large Capacity)
|
|
// Async operation
|
|
try {
|
|
await saveImageToDB(id, imageSrc);
|
|
} catch (e) {
|
|
console.error('Failed to save to DB:', e);
|
|
alert('Uploaded, but image data count not be saved permanently due to storage error.');
|
|
}
|
|
|
|
resetPostForm();
|
|
createPostView.classList.add('hidden');
|
|
feedView.classList.remove('hidden');
|
|
});
|
|
}
|
|
|
|
function resetPostForm() {
|
|
if (imageInput) imageInput.value = '';
|
|
if (captionInput) captionInput.value = '';
|
|
if (imagePreview) {
|
|
imagePreview.src = '';
|
|
imagePreview.classList.add('hidden');
|
|
}
|
|
const ph = document.querySelector('.upload-placeholder');
|
|
if (ph) ph.classList.remove('hidden');
|
|
}
|
|
});
|