Files
p2ns/plugin-sites/peer.directory/www/index.html
T
2025-12-17 20:05:50 -05:00

378 lines
13 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#000000">
<title>Peer Directory</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/css/tailwind.css">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="container">
<!-- Header -->
<div class="header">
<div class="flex-1"></div>
<h1>P2NS Directory</h1>
<div class="header-actions">
<a
href="https://p2ns.admin"
target="_blank"
class="btn btn-primary"
>
Go To Admin
</a>
</div>
</div>
<!-- Search and Controls -->
<div class="mb-6 space-y-4 flex-shrink-0">
<input
id="searchInput"
type="text"
placeholder="Search domains or hashes..."
class="input"
autofocus>
<div class="flex gap-4 items-center justify-between">
<div class="flex items-center gap-2">
<label for="sortBy" class="text-sm" style="color: var(--text-secondary);">Sort by:</label>
<select
id="sortBy"
class="select"
style="width: auto; min-width: 250px;"
>
<option value="type" selected>Type (Remote → Local → Internal)</option>
<option value="name">Name (A-Z)</option>
<option value="name-desc">Name (Z-A)</option>
<option value="hash">Hash (A-Z)</option>
<option value="hash-desc">Hash (Z-A)</option>
<option value="type-desc">Type (Internal → Local → Remote)</option>
</select>
</div>
</div>
</div>
<!-- Domain Table -->
<div class="table-container">
<table>
<thead>
<tr>
<th>Domain</th>
<th>Hash</th>
<th>Type</th>
</tr>
</thead>
<tbody id="domainList"></tbody>
</table>
<div id="scrollSentinel" style="height: 20px; width: 100%; flex-shrink: 0;"></div>
</div>
<!-- Loading indicator and info -->
<div class="mb-4 text-center text-sm text-tertiary flex-shrink-0" style="min-height: 1.5rem;">
<span id="paginationInfo">Loading...</span>
</div>
</div>
<script>
let currentPage = 1;
let currentLimit = 20;
let currentSort = 'type';
let allDomains = [];
let totalDomains = 0;
let isSearching = false;
let isLoading = false;
let hasMore = true;
let scrollObserver = null;
function getTypeBadge(type) {
const badges = {
internal: {
icon: '⚙️',
text: 'Internal',
class: 'badge badge-internal'
},
local: {
icon: '🏠',
text: 'Local',
class: 'badge badge-local'
},
remote: {
icon: '🌐',
text: 'Remote',
class: 'badge badge-remote'
}
};
const badge = badges[type] || badges.remote;
return `<span class="${badge.class}">
<span>${badge.icon}</span>
<span>${badge.text}</span>
</span>`;
}
function renderDomain(domainObj) {
const tr = document.createElement('tr');
// Domain cell with link
const domainCell = document.createElement('td');
const domainLink = document.createElement('a');
domainLink.href = 'https://' + domainObj.domain;
domainLink.textContent = domainObj.domain;
domainLink.target = '_blank';
domainCell.appendChild(domainLink);
// Hash cell
const hashCell = document.createElement('td');
hashCell.style.cssText = 'word-break: break-all; color: var(--text-tertiary);';
hashCell.textContent = domainObj.hash || 'none';
// Type cell with badge
const typeCell = document.createElement('td');
typeCell.innerHTML = getTypeBadge(domainObj.type);
tr.appendChild(domainCell);
tr.appendChild(hashCell);
tr.appendChild(typeCell);
return tr;
}
async function fetchAllDomains(sort = 'type') {
try {
// Fetch all domains with a large limit
const params = new URLSearchParams({ page: '1', limit: '10000', sort });
const response = await fetch('/domains?' + params.toString());
const data = await response.json();
if (data.domains) {
allDomains = data.domains;
totalDomains = data.total;
} else if (Array.isArray(data)) {
// Fallback for old API format
allDomains = data.map(d => typeof d === 'string' ? { domain: d, type: 'remote', hash: 'none', isLocal: false } : d);
totalDomains = allDomains.length;
}
return allDomains;
} catch (err) {
console.error('Failed to fetch all domains:', err);
return [];
}
}
async function fetchDomains(page = 1, limit = 20, sort = 'type', searchQuery = '', append = false, retryCount = 0) {
if (isLoading) return;
try {
isLoading = true;
let domains = [];
let total = 0;
if (searchQuery) {
// When searching, fetch all domains and filter client-side
if (allDomains.length === 0 || currentSort !== sort) {
await fetchAllDomains(sort);
currentSort = sort;
}
const query = searchQuery.toLowerCase();
const filtered = allDomains.filter(d =>
d.domain.toLowerCase().includes(query) ||
(d.hash && d.hash.toLowerCase().includes(query))
);
const startIndex = (page - 1) * limit;
const endIndex = startIndex + limit;
domains = filtered.slice(startIndex, endIndex);
total = filtered.length;
hasMore = endIndex < filtered.length;
renderDomains(domains, append);
updatePaginationInfo(page, total, limit);
} else {
// Normal paginated API call
const params = new URLSearchParams({ page: page.toString(), limit: limit.toString(), sort });
const response = await fetch('/domains?' + params.toString());
const data = await response.json();
if (data.domains) {
domains = data.domains;
total = data.total;
const totalPages = data.totalPages;
hasMore = page < totalPages;
renderDomains(domains, append);
updatePaginationInfo(page, total, limit);
totalDomains = data.total;
} else {
// Fallback
if (allDomains.length === 0) {
allDomains = Array.isArray(data) ? data.map(d => typeof d === 'string' ? { domain: d, type: 'remote', hash: 'none', isLocal: false } : d) : [];
totalDomains = allDomains.length;
}
const startIndex = (page - 1) * limit;
const endIndex = startIndex + limit;
domains = allDomains.slice(startIndex, endIndex);
total = allDomains.length;
hasMore = endIndex < allDomains.length;
renderDomains(domains, append);
updatePaginationInfo(page, total, limit);
}
}
// Setup infinite scroll if there's more to load
// Use setTimeout to ensure DOM is updated
setTimeout(() => {
if (hasMore) {
setupInfiniteScroll();
} else {
cleanupInfiniteScroll();
}
}, 100);
// If no domains found and not searching, retry after a delay
if (domains.length === 0 && !searchQuery && !append) {
const domainList = document.getElementById('domainList');
domainList.innerHTML = '<tr><td colspan="3" class="p-8 text-center" style="color: var(--text-tertiary);">No domains found. Retrying...</td>';
// Wait 2 seconds before retrying
await new Promise(resolve => setTimeout(resolve, 2000));
// Retry the request
isLoading = false;
return fetchDomains(page, limit, sort, searchQuery, append, retryCount + 1);
}
} catch (err) {
console.error('Failed to fetch domains:', err);
const domainList = document.getElementById('domainList');
if (!append) {
domainList.innerHTML = '<tr><td colspan="3" class="p-4 text-center" style="color: var(--error);">Failed to load domains. Retrying...</td>';
}
// Wait 2 seconds before retrying on error
await new Promise(resolve => setTimeout(resolve, 2000));
// Retry the request
isLoading = false;
return fetchDomains(page, limit, sort, searchQuery, append, retryCount + 1);
} finally {
isLoading = false;
}
}
function renderDomains(domains, append = false) {
const domainList = document.getElementById('domainList');
const tableContainer = document.querySelector('.table-container');
if (!append) {
domainList.innerHTML = '';
}
if (domains.length === 0 && !append) {
const tr = document.createElement('tr');
tr.innerHTML = '<td colspan="3" class="p-8 text-center" style="color: var(--text-tertiary);">No domains found.</td>';
domainList.appendChild(tr);
// Remove few-rows class when empty
if (tableContainer) {
tableContainer.classList.remove('few-rows');
}
return;
}
domains.forEach(domainObj => {
const tr = renderDomain(domainObj);
domainList.appendChild(tr);
});
// Add 'few-rows' class if there are 5 or fewer total rows for better appearance
if (tableContainer) {
const totalRows = domainList.querySelectorAll('tr').length;
if (totalRows <= 5) {
tableContainer.classList.add('few-rows');
} else {
tableContainer.classList.remove('few-rows');
}
}
}
function updatePaginationInfo(page, total, limit) {
const paginationInfo = document.getElementById('paginationInfo');
const domainList = document.getElementById('domainList');
const loadedCount = domainList.querySelectorAll('tr').length;
paginationInfo.textContent = `Showing ${loadedCount} of ${total} domains${hasMore ? ' (scroll for more)' : ''}`;
}
function setupInfiniteScroll() {
cleanupInfiniteScroll();
const sentinel = document.getElementById('scrollSentinel');
const tableContainer = document.querySelector('.table-container');
if (!sentinel || !tableContainer) {
// Retry after a short delay if elements aren't ready
setTimeout(setupInfiniteScroll, 100);
return;
}
scrollObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && hasMore && !isLoading) {
console.log('Loading more domains...');
loadMoreDomains();
}
});
}, {
root: tableContainer,
rootMargin: '100px',
threshold: 0.1
});
scrollObserver.observe(sentinel);
console.log('Infinite scroll observer set up');
}
function cleanupInfiniteScroll() {
if (scrollObserver) {
scrollObserver.disconnect();
scrollObserver = null;
}
}
async function loadMoreDomains() {
if (isLoading || !hasMore) return;
currentPage++;
const searchQuery = document.getElementById('searchInput').value;
await fetchDomains(currentPage, currentLimit, currentSort, searchQuery, true);
}
// Event listeners
document.getElementById('searchInput').addEventListener('input', async (e) => {
const searchQuery = e.target.value;
currentPage = 1;
hasMore = true;
isSearching = searchQuery.length > 0;
cleanupInfiniteScroll();
if (isSearching) {
// Clear cache when search changes to force refetch
allDomains = [];
}
await fetchDomains(currentPage, currentLimit, currentSort, searchQuery, false);
});
document.getElementById('sortBy').addEventListener('change', async (e) => {
currentSort = e.target.value;
currentPage = 1;
hasMore = true;
cleanupInfiniteScroll();
// Clear cache when sort changes
allDomains = [];
const searchQuery = document.getElementById('searchInput').value;
await fetchDomains(currentPage, currentLimit, currentSort, searchQuery, false);
});
// Initial fetch
fetchDomains(currentPage, currentLimit, currentSort, '', false);
</script>
</body>
</html>