`;
}
// Update a single link card in place
function updateLinkCard(link) {
const linkCard = document.querySelector(`.link-card[data-id="${link.id}"]`);
if (!linkCard) return;
// Replace the card content
linkCard.outerHTML = createLinkCard(link);
// Re-attach event listeners to the new card
const newCard = document.querySelector(`.link-card[data-id="${link.id}"]`);
if (newCard) {
const deleteBtn = newCard.querySelector('.delete-btn');
const archiveBtn = newCard.querySelector('.archive-btn');
const addToListBtn = newCard.querySelector('.add-to-list-btn');
if (deleteBtn) {
deleteBtn.addEventListener('click', () => handleDeleteLink(link.id));
}
if (archiveBtn) {
archiveBtn.addEventListener('click', () => handleArchiveLink(link.id));
}
if (addToListBtn) {
addToListBtn.addEventListener('click', () => handleAddToLists(link.id));
}
}
}
// Remove a single link card
function removeLinkCard(id) {
const linkCard = document.querySelector(`.link-card[data-id="${id}"]`);
if (linkCard) {
linkCard.remove();
// Check if we need to show empty state
const remainingCards = document.querySelectorAll('.link-card');
if (remainingCards.length === 0) {
const filteredCount = getFilteredLinks().length;
const totalCount = allLinks.length;
const message = showArchived
? (totalCount === 0 ? 'Add your first link to get started!' : 'No archived links found.')
: (totalCount === 0 ? 'Add your first link to get started!' : (filteredCount === 0 ? 'No active links found. Try a different search term or toggle to view archived links.' : 'Try a different search term.'));
linksContainer.innerHTML = `
No links found. ${message}
`;
}
}
}
// Check if a link should be visible based on current filters
function shouldLinkBeVisible(link) {
const isArchived = link.archived === true;
const matchesArchiveFilter = showArchived ? isArchived : !isArchived;
const query = searchInput.value.trim();
if (query) {
const queryLower = query.toLowerCase();
const titleMatch = link.title?.toLowerCase().includes(queryLower);
const descMatch = link.description?.toLowerCase().includes(queryLower);
const urlMatch = link.url?.toLowerCase().includes(queryLower);
const matchesSearch = titleMatch || descMatch || urlMatch;
return matchesArchiveFilter && matchesSearch;
}
return matchesArchiveFilter;
}
// Handle archive link
async function handleArchiveLink(id) {
try {
const link = allLinks.find(l => l.id === id);
if (!link) return;
const newArchivedStatus = !link.archived;
const response = await fetch(`${API_BASE}/${id}/archive`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ archived: newArchivedStatus })
});
if (!response.ok) throw new Error('Failed to archive link');
// Update local array
link.archived = newArchivedStatus;
// Update or remove the link card without refreshing the whole list
if (shouldLinkBeVisible(link)) {
// Link should still be visible, update it in place
updateLinkCard(link);
} else {
// Link should no longer be visible, remove it
removeLinkCard(id);
}
showMessage(newArchivedStatus ? 'Link archived successfully' : 'Link unarchived successfully', 'success');
} catch (error) {
showMessage('Failed to archive link', 'error');
console.error('Error archiving link:', error);
}
}
// Handle delete link
async function handleDeleteLink(id) {
if (!confirm('Are you sure you want to delete this link?')) {
return;
}
try {
const response = await fetch(`${API_BASE}/${id}`, {
method: 'DELETE'
});
if (!response.ok) throw new Error('Failed to delete link');
// Remove from local array
allLinks = allLinks.filter(link => link.id !== id);
displayLinks(getFilteredLinks());
showMessage('Link deleted successfully', 'success');
} catch (error) {
showMessage('Failed to delete link', 'error');
console.error('Error deleting link:', error);
}
}
// Show toast message
function showMessage(text, type = 'success') {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = text;
// Add to container
toastContainer.appendChild(toast);
// Trigger animation
requestAnimationFrame(() => {
toast.classList.add('show');
});
// Remove after delay
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => {
if (toast.parentNode) {
toast.parentNode.removeChild(toast);
}
}, 300); // Wait for fade-out animation
}, 3000);
}
// Load all lists
async function loadLists() {
try {
const response = await fetch(LISTS_API_BASE);
if (!response.ok) throw new Error('Failed to load lists');
allLists = await response.json();
// Ensure all lists have public property
allLists = allLists.map(list => ({
...list,
public: list.public || false
}));
// Only update filter chips if the filter section is visible
if (listFilterWrapper.classList.contains('show')) {
updateListFilterChips();
}
return allLists;
} catch (error) {
showMessage('Failed to load lists', 'error');
console.error('Error loading lists:', error);
return [];
}
}
// Setup lists management
function setupListsManagement() {
// Toggle filter section visibility
listsToggle.addEventListener('click', () => {
const isVisible = listFilterWrapper.classList.contains('show');
if (isVisible) {
listFilterWrapper.classList.remove('show');
listsToggle.classList.remove('active');
// Reset filters when hiding the section
selectedListFilters = [];
updateUrlForListFilter();
updateListFilterChips();
displayLinks(getFilteredLinks());
} else {
listFilterWrapper.classList.add('show');
listsToggle.classList.add('active');
// Update filter chips when showing the section
updateListFilterChips();
}
});
// Open lists modal from edit button
editListsBtn.addEventListener('click', () => {
listsModal.classList.add('show');
renderListsList();
});
// Close lists modal
closeListsModal.addEventListener('click', () => {
listsModal.classList.remove('show');
});
// Close on backdrop click
listsModal.addEventListener('click', (e) => {
if (e.target === listsModal) {
listsModal.classList.remove('show');
}
});
// Create list
createListBtn.addEventListener('click', handleCreateList);
newListName.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleCreateList();
}
});
// List selection overlay
closeListSelection.addEventListener('click', () => {
listSelectionOverlay.classList.remove('show');
currentLinkForListSelection = null;
});
// Close on backdrop click
listSelectionOverlay.addEventListener('click', (e) => {
if (e.target === listSelectionOverlay) {
listSelectionOverlay.classList.remove('show');
currentLinkForListSelection = null;
}
});
}
// Render lists in the modal
function renderListsList() {
if (allLists.length === 0) {
listsList.innerHTML = '
No lists yet. Create your first list!
';
return;
}
listsList.innerHTML = allLists.map(list => {
// Ensure public property exists and defaults to false (private)
const isPublic = list.public === true;
return `
`;
}).join('');
// Add event listeners
listsList.querySelectorAll('.toggle-public-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const listId = e.target.closest('.toggle-public-btn').dataset.id;
handleTogglePublic(listId);
});
});
listsList.querySelectorAll('.public-url-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const listId = e.target.closest('.public-url-btn').dataset.id;
const listUrl = `${window.location.origin}${window.location.pathname}#list=${listId}`;
window.open(listUrl, '_blank');
});
});
listsList.querySelectorAll('.delete-list-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const listId = e.target.closest('.delete-list-btn').dataset.id;
handleDeleteList(listId);
});
});
listsList.querySelectorAll('.list-name-input').forEach(input => {
// Auto-save on blur (when input loses focus)
input.addEventListener('blur', (e) => {
const listId = e.target.dataset.id;
handleUpdateList(listId);
});
// Also save on Enter key
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.target.blur(); // Trigger blur which will auto-save
}
});
});
}
// Handle create list
async function handleCreateList() {
const name = newListName.value.trim();
if (!name) {
showMessage('Please enter a list name', 'error');
return;
}
try {
const response = await fetch(LISTS_API_BASE, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to create list');
}
allLists.push(data);
newListName.value = '';
renderListsList();
// Only update filter chips if the filter section is visible
if (listFilterWrapper.classList.contains('show')) {
updateListFilterChips();
}
showMessage('List created successfully!', 'success');
} catch (error) {
showMessage(error.message, 'error');
console.error('Error creating list:', error);
}
}
// Handle update list
async function handleUpdateList(listId) {
const input = listsList.querySelector(`.list-name-input[data-id="${listId}"]`);
const name = input.value.trim();
if (!name) {
showMessage('List name cannot be empty', 'error');
return;
}
try {
const response = await fetch(`${LISTS_API_BASE}/${listId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to update list');
}
const listIndex = allLists.findIndex(l => l.id === listId);
if (listIndex !== -1) {
allLists[listIndex] = data;
}
renderListsList();
// Only update filter chips if the filter section is visible
if (listFilterWrapper.classList.contains('show')) {
updateListFilterChips();
}
showMessage('List updated successfully!', 'success');
} catch (error) {
showMessage(error.message, 'error');
console.error('Error updating list:', error);
}
}
// Handle toggle public status
async function handleTogglePublic(listId) {
const list = allLists.find(l => l.id === listId);
if (!list) return;
// Current state: false/undefined = private, true = public
// Toggle: if currently private (false), make it public (true)
// if currently public (true), make it private (false)
const currentIsPublic = list.public === true;
const newPublicStatus = !currentIsPublic;
try {
const response = await fetch(`${LISTS_API_BASE}/${listId}/public`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ public: newPublicStatus })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to update list public status');
}
// Update local array
const listIndex = allLists.findIndex(l => l.id === listId);
if (listIndex !== -1) {
allLists[listIndex].public = newPublicStatus;
}
renderListsList();
showMessage(newPublicStatus ? 'List is now public' : 'List is now private', 'success');
} catch (error) {
showMessage('Failed to update list public status', 'error');
console.error('Error updating list public status:', error);
}
}
// Handle delete list
async function handleDeleteList(listId) {
if (!confirm('Are you sure you want to delete this list? Links assigned to this list will be unassigned.')) {
return;
}
try {
const response = await fetch(`${LISTS_API_BASE}/${listId}`, {
method: 'DELETE'
});
if (!response.ok) throw new Error('Failed to delete list');
allLists = allLists.filter(list => list.id !== listId);
selectedListFilters = selectedListFilters.filter(id => id !== listId);
renderListsList();
// Only update filter chips if the filter section is visible
if (listFilterWrapper.classList.contains('show')) {
updateListFilterChips();
}
displayLinks(getFilteredLinks());
showMessage('List deleted successfully', 'success');
} catch (error) {
showMessage('Failed to delete list', 'error');
console.error('Error deleting list:', error);
}
}
// Handle add to lists
function handleAddToLists(linkId) {
currentLinkForListSelection = linkId;
const link = allLinks.find(l => l.id === linkId);
const linkListIds = link?.listIds || [];
// Render list checkboxes
if (allLists.length === 0) {
listSelectionBody.innerHTML = '
No lists available. Create a list first!
';
} else {
listSelectionBody.innerHTML = allLists.map(list => `
`).join('');
// Add event listeners to checkboxes for auto-save
listSelectionBody.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
checkbox.addEventListener('change', () => {
handleCheckboxChange(linkId);
});
});
}
listSelectionOverlay.classList.add('show');
}
// Handle checkbox change (auto-save)
async function handleCheckboxChange(linkId) {
if (!linkId) return;
const checkboxes = listSelectionBody.querySelectorAll('input[type="checkbox"]:checked');
const selectedListIds = Array.from(checkboxes).map(cb => cb.value);
try {
const response = await fetch(`${API_BASE}/${linkId}/lists`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ listIds: selectedListIds })
});
const data = await response.json();
if (!response.ok) {
throw new Error('Failed to update link lists');
}
// Update local array
const linkIndex = allLinks.findIndex(l => l.id === linkId);
if (linkIndex !== -1) {
allLinks[linkIndex].listIds = selectedListIds;
}
// No need to refresh the display - the link is already visible
// Only update if the link's visibility might have changed due to list filters
// But since we're just assigning lists, not changing visibility, we skip the refresh
} catch (error) {
showMessage('Failed to update link lists', 'error');
console.error('Error updating link lists:', error);
// Revert checkbox state on error
const link = allLinks.find(l => l.id === linkId);
const linkListIds = link?.listIds || [];
listSelectionBody.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
checkbox.checked = linkListIds.includes(checkbox.value);
});
}
}
// Setup list filtering
function setupListFiltering() {
clearListFilters.addEventListener('click', () => {
selectedListFilters = [];
updateUrlForListFilter();
updateListFilterChips();
displayLinks(getFilteredLinks());
});
}
// Setup URL navigation for lists
function setupUrlNavigation() {
// Listen for hash changes (browser back/forward)
window.addEventListener('hashchange', () => {
checkUrlForListFilter();
});
}
// Check URL for list filter parameter
function checkUrlForListFilter() {
const hash = window.location.hash;
if (!hash) {
return;
}
// Parse hash like #list=LIST_ID or #list=ID1,ID2,ID3
const listMatch = hash.match(/^#list=(.+)$/);
if (listMatch) {
const listIds = listMatch[1].split(',').filter(id => id.trim());
// Validate that all list IDs exist
const validListIds = listIds.filter(id => allLists.some(list => list.id === id));
if (validListIds.length > 0) {
selectedListFilters = validListIds;
// Don't show filter section when loading from URL - just apply the filter silently
// The user can manually toggle it if they want to see/modify filters
displayLinks(getFilteredLinks());
}
}
}
// Update URL based on current list filters
function updateUrlForListFilter() {
if (selectedListFilters.length > 0) {
const listIds = selectedListFilters.join(',');
window.location.hash = `list=${listIds}`;
} else {
// Remove hash if no filters
if (window.location.hash.startsWith('#list=')) {
window.history.replaceState(null, '', window.location.pathname + window.location.search);
}
}
}
// Update list filter chips
function updateListFilterChips() {
if (allLists.length === 0) {
// Don't hide the wrapper if it's already shown, just show empty state
listFilterChips.innerHTML = '
No lists available. Click Edit to create lists.
';
return;
}
// Only show the wrapper if it has the 'show' class (user has toggled it)
if (!listFilterWrapper.classList.contains('show')) {
return;
}
listFilterChips.innerHTML = allLists.map(list => {
const isSelected = selectedListFilters.includes(list.id);
return `
`;
}).join('');
// Add event listeners
listFilterChips.querySelectorAll('.list-filter-chip').forEach(chip => {
chip.addEventListener('click', () => {
const listId = chip.dataset.id;
const index = selectedListFilters.indexOf(listId);
if (index > -1) {
selectedListFilters.splice(index, 1);
} else {
selectedListFilters.push(listId);
}
updateUrlForListFilter();
updateListFilterChips();
displayLinks(getFilteredLinks());
});
});
}
// Escape HTML to prevent XSS
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}