This commit is contained in:
Hell13Cat
2026-05-27 01:28:03 +03:00
parent ed7bc4fba5
commit 2a103d246b
9 changed files with 383 additions and 605 deletions
+143 -98
View File
@@ -6,44 +6,29 @@
<title>LocalBooru</title>
<style>
:root {
--bg-main: #1e1e1e;
--bg-header: #252525;
--bg-card: #2a2a2a;
--bg-panel: #222;
--bg-input: #333;
--text-main: #eee;
--text-muted: #aaa;
--border-color: #444;
--bg-main: #1e1e1e; --bg-header: #252525; --bg-card: #2a2a2a;
--bg-panel: #222; --bg-input: #333; --text-main: #eee;
--text-muted: #aaa; --border-color: #444;
--color-g: #4caf50; --color-s: #ff9800; --color-q: #ffeb3b; --color-e: #f44336;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background-color: var(--bg-main); color: var(--text-main); font-family: sans-serif; font-size: 14px; }
/* Header */
header { display: flex; align-items: center; background-color: var(--bg-header); padding: 10px 20px; border-bottom: 1px solid var(--border-color); gap: 15px; flex-wrap: wrap; }
.logo { font-weight: bold; font-size: 18px; color: white; text-decoration: none; }
.analytics { color: #88bece; text-decoration: none; font-size: 12px; }
/* Search & Autocomplete */
.search-wrapper { flex-grow: 1; max-width: 400px; position: relative; }
.search-wrapper input { width: 100%; background-color: var(--bg-input); border: 1px solid var(--border-color); color: white; padding: 6px 10px; border-radius: 3px; outline: none; }
.search-wrapper input:focus { border-color: var(--text-muted); }
.autocomplete-list {
position: absolute; top: 100%; left: 0; right: 0; background-color: var(--bg-card);
border: 1px solid var(--border-color); border-radius: 3px; margin-top: 4px;
list-style: none; z-index: 1000; max-height: 250px; overflow-y: auto;
box-shadow: 0 4px 10px rgba(0,0,0,0.5); display: none;
}
.autocomplete-item {
padding: 8px 10px; cursor: pointer; display: flex; justify-content: space-between; border-bottom: 1px solid #333;
}
.autocomplete-list { position: absolute; top: 100%; left: 0; right: 0; background-color: var(--bg-card); border: 1px solid var(--border-color); border-radius: 3px; margin-top: 4px; list-style: none; z-index: 1000; max-height: 250px; overflow-y: auto; box-shadow: 0 4px 10px rgba(0,0,0,0.5); display: none; }
.autocomplete-item { padding: 8px 10px; cursor: pointer; display: flex; justify-content: space-between; border-bottom: 1px solid #333; }
.autocomplete-item:last-child { border-bottom: none; }
.autocomplete-item:hover { background-color: var(--bg-input); }
.autocomplete-count { color: var(--text-muted); font-size: 12px; }
/* Filters */
.rating-filters { display: flex; gap: 5px; }
.rating-btn { background: transparent; color: white; border: 1px solid; width: 24px; height: 24px; border-radius: 3px; cursor: pointer; font-size: 12px; font-weight: bold; }
.rating-btn.active { opacity: 1; }
@@ -53,16 +38,22 @@
#btn-s { border-color: var(--color-s); color: var(--color-s); }
#btn-g { border-color: var(--color-g); color: var(--color-g); }
/* Main Content */
main { padding: 20px; max-width: 1600px; margin: 0 auto; }
.results-header { font-size: 18px; font-weight: bold; margin-bottom: 20px; }
.pagination-container { display: flex; justify-content: center; gap: 10px; margin: 20px 0; }
/* Pagination */
.pagination-container { display: flex; justify-content: center; align-items: center; gap: 10px; margin: 20px 0; }
.pagination-btn { background-color: var(--bg-header); border: 1px solid var(--border-color); color: var(--text-muted); padding: 5px 12px; cursor: pointer; border-radius: 3px; }
.pagination-btn:hover:not(:disabled) { background-color: var(--bg-input); color: white; }
.pagination-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 10px; }
.card { background-color: var(--bg-card); display: flex; flex-direction: column; border-radius: 3px; overflow: hidden; }
.card-image-container { width: 100%; aspect-ratio: 1/1; background-color: #333; }
.card { background-color: var(--bg-card); display: flex; flex-direction: column; border-radius: 3px; overflow: hidden; text-decoration: none; color: inherit; transition: transform 0.1s;}
.card:hover { transform: translateY(-2px); }
.card-image-container { width: 100%; aspect-ratio: 1/1; background-color: #333; position: relative; }
.card-image-container img { width: 100%; height: 100%; object-fit: cover; display: block; }
.card-meta { padding: 6px; text-align: center; font-size: 10px; color: var(--text-muted); }
.loader { text-align: center; padding: 50px; color: var(--text-muted); grid-column: 1/-1; }
@media (max-width: 600px) { .search-wrapper { order: 3; max-width: 100%; width: 100%; margin-top: 10px; } }
@@ -71,8 +62,8 @@
<body>
<header>
<a href="index.html" class="logo">LocalBooru</a>
<a class="analytics" href="analytics.html">📊 Analytics</a>
<a href="/" class="logo">LocalBooru</a>
<a class="analytics" href="/analytics">📊 Analytics</a>
<div class="search-wrapper">
<input type="text" id="searchInput" placeholder="Search tags...">
<ul id="autocompleteList" class="autocomplete-list"></ul>
@@ -93,13 +84,19 @@
</main>
<script>
const state = { page: 0, query: "", ratings: { e: true, q: true, s: true, g: true }, totalPages: 1, totalResults: 0 };
const state = {
page: 0,
query: "",
ratings: { e: true, q: true, s: true, g: true },
totalPages: 1,
totalResults: 0
};
// Инициализация
function init() {
setupAutocomplete('searchInput', 'autocompleteList');
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
document.getElementById('autocompleteList').style.display = 'none';
@@ -114,14 +111,21 @@
const r = e.target.getAttribute('data-rating');
state.ratings[r] = !state.ratings[r];
e.target.classList.toggle('active', state.ratings[r]);
state.page = 0; fetchData();
state.page = 0;
fetchData();
});
});
const urlQuery = new URLSearchParams(window.location.search).get('query');
if (urlQuery) {
state.query = urlQuery;
searchInput.value = urlQuery;
}
fetchData();
}
// Логика автозаполнения
// --- АВТОДОПОЛНЕНИЕ ---
function setupAutocomplete(inputId, listId) {
const input = document.getElementById(inputId);
const list = document.getElementById(listId);
@@ -132,100 +136,141 @@
const words = input.value.split(' ');
const currentWord = words[words.length - 1];
if (currentWord.length < 2) {
list.style.display = 'none';
return;
if (currentWord.length < 2) {
list.style.display = 'none';
return;
}
debounceTimer = setTimeout(async () => {
const req = { type: "autocomplete", q: currentWord };
console.log("-> Отправка API Автозаполнения:", JSON.stringify(req));
// Заглушка API. Для реального бэка: fetch('/api', { body: JSON.stringify(req)... })
const data = await mockAutocompleteAPI(req);
if (data.length === 0) {
list.style.display = 'none';
return;
}
list.innerHTML = data.map(item => `
<li class="autocomplete-item" data-tag="${item.tag}">
<span>${item.tag}</span><span class="autocomplete-count">${item.count}</span>
</li>
`).join('');
list.style.display = 'block';
list.querySelectorAll('.autocomplete-item').forEach(li => {
li.addEventListener('click', () => {
words[words.length - 1] = li.getAttribute('data-tag');
input.value = words.join(' ') + ' ';
list.style.display = 'none';
input.focus();
try {
const response = await fetch('/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(req)
});
});
}, 200); // 200ms задержка перед запросом
if (!response.ok) throw new Error('Ошибка API');
const data = await response.json();
if (!data || data.length === 0) {
list.style.display = 'none';
return;
}
list.innerHTML = data.map(item => `
<li class="autocomplete-item" data-tag="${item.tag}">
<span>${item.tag}</span><span class="autocomplete-count">${item.count}</span>
</li>
`).join('');
list.style.display = 'block';
list.querySelectorAll('.autocomplete-item').forEach(li => {
li.addEventListener('click', () => {
words[words.length - 1] = li.getAttribute('data-tag');
input.value = words.join(' ') + ' ';
list.style.display = 'none';
input.focus();
});
});
} catch (error) {
console.error(error);
}
}, 200);
});
// Скрываем список при клике вне него
document.addEventListener('click', (e) => {
if (e.target !== input && e.target !== list) list.style.display = 'none';
});
}
// --- ПОИСК И ВЫВОД РЕЗУЛЬТАТОВ ---
async function fetchData() {
const grid = document.getElementById('imageGrid');
grid.innerHTML = `<div class="loader">Загрузка...</div>`;
const activeRatings = Object.keys(state.ratings).filter(k => state.ratings[k]).join('+');
const req = { page: state.page, query: state.query.trim(), rating: activeRatings };
// Заглушка API Поиска
const data = await mockSearchAPI(req);
state.totalResults = data.total_results; state.totalPages = data.total_pages;
document.getElementById('resultsCount').textContent = `Results (${state.totalResults})`;
grid.innerHTML = data.items.map(i => `
<div class="card">
<div class="card-image-container" style="background-color: hsl(${Math.random() * 360}, 20%, 30%);"></div>
<div class="card-meta">Date: ${i.date}<br>Score: ${i.score} | Rating: <span style="color:var(--color-${i.rating[0].toLowerCase()})">${i.rating}</span></div>
</div>
`).join('');
renderPagination();
const activeRatings = Object.keys(state.ratings).filter(k => state.ratings[k]).join('+');
const req = {
type: "search",
page: state.page,
query: state.query.trim(),
rating: activeRatings
};
try {
const response = await fetch('/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(req)
});
if (!response.ok) throw new Error('Ошибка сервера');
const data = await response.json();
// Синхронизация состояния: вычисляем количество страниц (Math.ceil(всего / элементов_на_странице))
state.totalResults = data.results_info.total;
state.page = data.results_info.page;
const itemsPerPage = data.results_info.count_page || 1; // защита от деления на 0
state.totalPages = Math.ceil(state.totalResults / itemsPerPage);
document.getElementById('resultsCount').textContent = `Results (${state.totalResults})`;
if (data.results.length === 0) {
grid.innerHTML = `<div class="loader">Ничего не найдено</div>`;
} else {
grid.innerHTML = data.results.map(i => `
<a href="/post/${i.md5}" class="card">
<div class="card-image-container">
<img src="/thumb/${i.md5}.jpg" alt="thumbnail" loading="lazy">
</div>
<div class="card-meta">
Date: ${i.display_date[1]}<br>
Score: ${i.score} | Rating: <span style="color:var(--color-${i.rating[0].toLowerCase()})">${i.rating}</span>
</div>
</a>
`).join('');
}
renderPagination();
} catch (err) {
console.error(err);
grid.innerHTML = `<div class="loader">Ошибка связи с API</div>`;
}
}
// --- ПАГИНАЦИЯ ---
function renderPagination() {
const totalPages = Math.max(0, state.totalPages);
const currentPage = state.page;
const hasPrev = currentPage > 0;
const hasNext = currentPage < totalPages - 1;
const displayPage = totalPages === 0 ? 1 : currentPage + 1;
const displayTotal = totalPages === 0 ? 1 : totalPages;
const html = `
<button class="pagination-btn" onclick="changePage(0)" ${state.page === 0 ? 'disabled' : ''}>&laquo; First</button>
<button class="pagination-btn" onclick="changePage(${state.page - 1})" ${state.page === 0 ? 'disabled' : ''}>&lsaquo; Prev</button>
<span style="font-size:12px; font-weight:bold;">Page ${state.page + 1} of ${state.totalPages}</span>
<button class="pagination-btn" onclick="changePage(${state.page + 1})" ${state.page >= state.totalPages - 1 ? 'disabled' : ''}>Next &rsaquo;</button>
<button class="pagination-btn" onclick="changePage(${state.totalPages - 1})" ${state.page >= state.totalPages - 1 ? 'disabled' : ''}>Last &raquo;</button>
<button class="pagination-btn" onclick="changePage(0)" ${!hasPrev ? 'disabled' : ''}>&laquo; First</button>
<button class="pagination-btn" onclick="changePage(${currentPage - 1})" ${!hasPrev ? 'disabled' : ''}>&lsaquo; Prev</button>
<span style="font-size:12px; font-weight:bold;">Page ${displayPage} of ${displayTotal}</span>
<button class="pagination-btn" onclick="changePage(${currentPage + 1})" ${!hasNext ? 'disabled' : ''}>Next &rsaquo;</button>
<button class="pagination-btn" onclick="changePage(${totalPages - 1})" ${!hasNext ? 'disabled' : ''}>Last &raquo;</button>
`;
document.getElementById('paginationTop').innerHTML = html;
document.getElementById('paginationBottom').innerHTML = html;
}
window.changePage = (p) => { state.page = p; fetchData(); window.scrollTo(0,0); };
// --- ВРЕМЕННЫЕ API ЗАГЛУШКИ ---
function mockAutocompleteAPI(req) {
return new Promise(res => {
const db = [{tag: "long_hair", count: 8184}, {tag: "long_sleeves", count: 2828}, {tag: "looking_at_viewer", count: 8062}, {tag: "1girl", count: 11061}, {tag: "highres", count: 12700}, {tag: "absurdres", count: 6742}];
res(db.filter(t => t.tag.includes(req.q.toLowerCase())));
});
}
function mockSearchAPI(req) {
return new Promise(res => { setTimeout(() => {
const items = [];
if(req.rating.length > 0) {
const rArr = req.rating.split('+');
const rMap = {'g':'general','s':'sensitive','q':'questionable','e':'explicit'};
for(let i=0; i<48; i++) items.push({ date: '2026-05-20', score: 10, rating: rMap[rArr[Math.floor(Math.random()*rArr.length)]] });
}
res({ total_results: 14003, total_pages: 281, items });
}, 300);});
}
// Смена страницы
window.changePage = (newPage) => {
if (newPage < 0 || (state.totalPages > 0 && newPage >= state.totalPages)) return;
state.page = newPage;
fetchData();
window.scrollTo(0, 0);
};
init();
</script>