My Drafts

📘 Tutorial: My Drafts Page

This tutorial walks you through how to:

  • Display login/logout/profile buttons dynamically
  • Load and view user drafts
  • Publish or edit draft stories
  • Use basic accordion behavior for toggling views

🔧 Step 1: Dynamic Auth Buttons (Login/Profile/Logout)

Function: updateAuthButtons()

This function checks if the user is logged in (by checking localStorage.token) and dynamically updates the navigation buttons.

function updateAuthButtons() {
const authButtonsContainer = document.getElementById("auth-buttons");
const token = localStorage.getItem("token");

authButtonsContainer.innerHTML = ""; // Clear buttons

if (token) {
authButtonsContainer.innerHTML = `
<a href="myaccount.html" class="btn">My Profile</a>
<a href="mydrafts.html" class="btn">My Drafts</a>
<a href="mystories.html" class="btn">My Stories</a>
<a href="#" class="btn" onclick="logout()">Logout</a>
`;
} else {
authButtonsContainer.innerHTML = `
<a href="login.html" class="btn">Login</a>
<a href="register.html" class="btn">Register</a>
`;
}
}

Logout Behavior:

function logout() {
localStorage.removeItem("token");
alert("Logged out successfully!");
updateAuthButtons();
window.location.href = "login.html";
}

📚 Step 2: Load User Drafts

Function: loadDrafts()

This fetches the user’s draft stories using the token from localStorage, then renders clickable titles in a list.

async function loadDrafts() {
const token = localStorage.getItem("token");
if (!token) return alert("You must be logged in to view your drafts.");

try {
const response = await fetch("/api/my-stories", {
headers: { Authorization: `Bearer ${token}` },
});

const { drafts } = await response.json();
const draftList = document.getElementById("draft-list");
draftList.innerHTML = "";

if (drafts.length === 0) {
storyContent.innerHTML = `<p>No drafts available. Start adding stories!</p>`;
} else {
drafts.forEach((story) => {
const item = document.createElement("li");
const link = document.createElement("a");

link.href = "#";
link.className = "story-link";
link.textContent = story.title;
link.onclick = () => loadStoryContent(story.id, true);

item.appendChild(link);
draftList.appendChild(item);
});

loadStoryContent(drafts[0].id, true); // Load the first draft by default
}
} catch (error) {
console.error("Error loading drafts:", error);
}
}

📖 Step 3: View a Single Draft’s Content

Function: loadStoryContent(storyId, isDraft)

This fetches and displays the full content of a draft or published story.

async function loadStoryContent(storyId, isDraft) {
const token = localStorage.getItem("token");
if (!token) return alert("You must be logged in.");

try {
const response = await fetch(`/api/stories/${storyId}`, {
headers: { Authorization: `Bearer ${token}` },
});

const story = await response.json();
document.getElementById("story-content").innerHTML = `
<h3>${story.title}</h3>
<p class="submitted-info"><sub>Submitted By: ${story.authorFirstName} ${story.authorLastName} on ${new Date(story.submittedOn).toLocaleString()}</sub></p>
<p>${story.content}</p>
`;

if (isDraft) {
document.getElementById("story-content").innerHTML += `
<button class="btn" onclick="publishStory(${story.id})">Publish</button>
<button class="btn" onclick="editStory(${story.id})">Edit</button>
`;
}
} catch (error) {
console.error("Error loading story content:", error);
}
}

✅ Step 4: Publish a Draft

Function: publishStory(storyId)

This sends a PUT request to mark the draft as published.

async function publishStory(storyId) {
const token = localStorage.getItem("token");
if (!token) return alert("You must be logged in to publish stories.");

try {
const response = await fetch(`/api/stories/publish/${storyId}`, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ publishedOn: new Date().toISOString() }),
});

if (response.ok) {
alert("Story published successfully!");
loadDrafts(); // Refresh list
} else {
alert("Error publishing story.");
}
} catch (error) {
console.error("Error publishing story:", error);
}
}

✍️ Step 5: Edit a Draft

Function: editStory(storyId)

Redirects the user to a separate page to edit the draft.

function editStory(storyId) {
window.location.href = `story.html?id=${storyId}`;
}

🪄 Step 6: Accordion Toggle to Show/Hide Draft List

Click a button (#view-drafts) to toggle draft list visibility.

document.getElementById("view-drafts").addEventListener("click", function () {
const draftList = document.getElementById("draft-list");
const isActive = draftList.style.display === "block";
draftList.style.display = isActive ? "none" : "block";

if (!isActive) {
loadDrafts(); // Only load when opening
}
});

🚀 Final Setup on Page Load

window.onload = () => {
updateAuthButtons();
loadDrafts(); // Automatically load drafts when page loads
};

✅ What You Need in Your HTML

Make sure you include:

<div id="auth-buttons"></div>
<button id="view-drafts">View Drafts</button>
<ul id="draft-list"></ul>
<div id="story-content"></div>