better marketplace

This commit is contained in:
2026-01-13 17:32:26 +01:00
parent f6488d6e52
commit 62eb943abe
6 changed files with 1206 additions and 1151 deletions

View File

@@ -1,242 +1,314 @@
const ORIGINAL_MARKETPLACE_URL = 'https://git.waifuboard.app/ItsSkaiya/WaifuBoard-Extensions/raw/branch/main/marketplace.json';
const MARKETPLACE_JSON_URL = `/api/proxy?url=${encodeURIComponent(ORIGINAL_MARKETPLACE_URL)}`;
const LS_KEY_MARKETPLACE_URL = 'wb_marketplace_url';
const DEFAULT_URL_PLACEHOLDER = 'https://git.waifuboard.app/ItsSkaiya/WaifuBoard-Extensions/raw/branch/main/marketplace.json';
const INSTALLED_EXTENSIONS_API = '/api/extensions';
const UPDATE_EXTENSIONS_API = '/api/extensions/update';
const marketplaceContent = document.getElementById('marketplace-content');
const filterSelect = document.getElementById('extension-filter');
const updateAllBtn = document.getElementById('btn-update-all');
// DOM Elements
const dom = {
content: document.getElementById('marketplace-content'),
configPanel: document.getElementById('config-panel'),
inputUrl: document.getElementById('source-url-input'),
const modal2 = document.getElementById('customModal');
const modalTitle = document.getElementById('modalTitle');
const modalMessage = document.getElementById('modalMessage');
const modalConfirmBtn = document.getElementById('modalConfirmButton');
const modalCloseBtn = document.getElementById('modalCloseButton');
// Filters & Toggles
filterType: document.getElementById('filter-type'),
filterLang: document.getElementById('filter-lang'),
btnNsfw: document.getElementById('btn-toggle-nsfw'),
let marketplaceMetadata = {};
let installedExtensions = [];
let currentTab = 'marketplace';
// Buttons
btnConfig: document.getElementById('btn-configure'),
btnSaveSource: document.getElementById('btn-save-source'),
btnResetSource: document.getElementById('btn-reset-source'),
btnUpdateAll: document.getElementById('btn-update-all'),
async function loadMarketplace() {
showSkeletons();
// Tabs
tabs: document.querySelectorAll('.tab-btn'),
// Modal
modal: document.getElementById('customModal'),
modalTitle: document.getElementById('modalTitle'),
modalMsg: document.getElementById('modalMessage'),
modalConfirm: document.getElementById('modalConfirmButton'),
modalClose: document.getElementById('modalCloseButton')
};
// State
let state = {
url: localStorage.getItem(LS_KEY_MARKETPLACE_URL) || null,
metadata: {},
installed: [],
currentTab: 'marketplace',
showNsfw: false // Default to HIDDEN
};
/* --- Initialization --- */
async function init() {
setupEventListeners();
if (!state.url) {
renderWelcomeState();
} else {
await loadData();
}
}
function setupEventListeners() {
// Config Panel
dom.btnConfig.addEventListener('click', () => {
dom.configPanel.classList.toggle('hidden');
if(!dom.configPanel.classList.contains('hidden')) dom.inputUrl.focus();
});
dom.btnSaveSource.addEventListener('click', saveSource);
dom.btnResetSource.addEventListener('click', () => {
dom.inputUrl.value = DEFAULT_URL_PLACEHOLDER;
saveSource();
});
// Filters
dom.filterType.addEventListener('change', render);
dom.filterLang.addEventListener('change', render);
// NSFW Toggle
dom.btnNsfw.addEventListener('click', toggleNsfw);
// Tabs
dom.tabs.forEach(tab => {
tab.addEventListener('click', () => {
dom.tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
state.currentTab = tab.dataset.tab;
if (state.currentTab === 'installed') dom.btnUpdateAll.classList.remove('hidden');
else dom.btnUpdateAll.classList.add('hidden');
render();
});
});
if(dom.btnUpdateAll) dom.btnUpdateAll.addEventListener('click', handleUpdateAll);
// Modal
dom.modalClose.addEventListener('click', hideModal);
}
/* --- Logic --- */
function toggleNsfw() {
state.showNsfw = !state.showNsfw;
// Update Button UI
if (state.showNsfw) {
dom.btnNsfw.classList.add('btn-danger'); // Red for ALERT/NSFW
dom.btnNsfw.classList.remove('btn-secondary');
dom.btnNsfw.innerHTML = `
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 6px;">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
<circle cx="12" cy="12" r="3"></circle>
</svg> NSFW: ON
`;
} else {
dom.btnNsfw.classList.remove('btn-danger');
dom.btnNsfw.classList.add('btn-secondary');
dom.btnNsfw.innerHTML = `
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 6px;">
<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
<line x1="1" y1="1" x2="23" y2="23"></line>
</svg> NSFW: Off
`;
}
render();
}
function saveSource() {
const url = dom.inputUrl.value.trim();
if (!url) return window.NotificationUtils.error('Please enter a valid URL');
localStorage.setItem(LS_KEY_MARKETPLACE_URL, url);
state.url = url;
dom.configPanel.classList.add('hidden');
window.NotificationUtils.success('Source updated');
loadData();
}
async function loadData() {
renderLoading();
try {
const proxyUrl = `/api/proxy?url=${encodeURIComponent(state.url)}`;
const [metaRes, installedRes] = await Promise.all([
fetch(MARKETPLACE_JSON_URL).then(res => res.json()),
fetch(INSTALLED_EXTENSIONS_API).then(res => res.json())
fetch(proxyUrl).then(r => r.ok ? r.json() : null),
fetch(INSTALLED_EXTENSIONS_API).then(r => r.json())
]);
marketplaceMetadata = metaRes.extensions;
installedExtensions = (installedRes.extensions || []).map(e => e.toLowerCase());
if (!metaRes) throw new Error('Failed to fetch marketplace JSON');
initTabs();
renderGroupedView();
state.metadata = metaRes.extensions || {};
state.installed = (installedRes.extensions || []).map(e => e.toLowerCase());
if (filterSelect) {
filterSelect.addEventListener('change', () => renderGroupedView());
}
if (updateAllBtn) {
updateAllBtn.onclick = handleUpdateAll;
}
render();
} catch (error) {
console.error('Error loading marketplace:', error);
marketplaceContent.innerHTML = `<div class="error-msg">Error al cargar el marketplace.</div>`;
console.error(error);
renderError(error.message);
}
}
function initTabs() {
const tabs = document.querySelectorAll('.tab-button');
tabs.forEach(tab => {
tab.onclick = () => {
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
currentTab = tab.dataset.tab;
/* --- Rendering --- */
function render() {
dom.content.innerHTML = '';
const typeFilter = dom.filterType.value;
const langFilter = dom.filterLang.value;
if (updateAllBtn) {
if (currentTab === 'installed') {
updateAllBtn.classList.remove('hidden');
} else {
updateAllBtn.classList.add('hidden');
}
}
let items = [];
renderGroupedView();
};
});
}
async function handleUpdateAll() {
const originalText = updateAllBtn.innerText;
try {
updateAllBtn.disabled = true;
updateAllBtn.innerText = 'Updating...';
const res = await fetch(UPDATE_EXTENSIONS_API, { method: 'POST' });
if (!res.ok) throw new Error('Update failed');
const data = await res.json();
if (data.updated && data.updated.length > 0) {
const list = data.updated.join(', ');
window.NotificationUtils.success(`Updated: ${list}`);
await loadMarketplace();
} else {
window.NotificationUtils.info('Everything is up to date.');
}
} catch (error) {
console.error('Update All Error:', error);
window.NotificationUtils.error('Failed to perform bulk update.');
} finally {
updateAllBtn.disabled = false;
updateAllBtn.innerText = originalText;
}
}
function renderGroupedView() {
marketplaceContent.innerHTML = '';
const activeFilter = filterSelect.value;
const groups = {};
let listToRender = [];
if (currentTab === 'marketplace') {
for (const [id, data] of Object.entries(marketplaceMetadata)) {
listToRender.push({
id,
...data,
isInstalled: installedExtensions.includes(id.toLowerCase())
});
}
// 1. Prepare items
if (state.currentTab === 'marketplace') {
items = Object.entries(state.metadata).map(([id, data]) => ({
id, ...data, isInstalled: state.installed.includes(id.toLowerCase())
}));
} else {
for (const [id, data] of Object.entries(marketplaceMetadata)) {
if (installedExtensions.includes(id.toLowerCase())) {
listToRender.push({ id, ...data, isInstalled: true });
}
}
const metaItems = Object.entries(state.metadata)
.filter(([id]) => state.installed.includes(id.toLowerCase()))
.map(([id, data]) => ({ id, ...data, isInstalled: true }));
installedExtensions.forEach(id => {
const existsInMeta = Object.keys(marketplaceMetadata).some(k => k.toLowerCase() === id);
if (!existsInMeta) {
listToRender.push({
id: id,
name: id.charAt(0).toUpperCase() + id.slice(1),
items = [...metaItems];
state.installed.forEach(instId => {
if (!items.find(i => i.id.toLowerCase() === instId)) {
items.push({
id: instId,
name: capitalize(instId),
type: 'Local',
author: 'Unknown',
isInstalled: true
description: 'Locally installed.',
author: '?',
lang: 'Local',
isInstalled: true,
isLocal: true
});
}
});
}
listToRender.forEach(ext => {
const type = ext.type || 'Other';
if (activeFilter !== 'All' && type !== activeFilter) return;
if (!groups[type]) groups[type] = [];
groups[type].push(ext);
// 2. Filter
items = items.filter(item => {
// NSFW Filter logic
if (!state.showNsfw && item.nsfw) return false;
// Type Filter
if (typeFilter !== 'All' && item.type !== typeFilter && item.type !== 'Local') return false;
// Lang Filter
if (langFilter !== 'All') {
const itemLang = (item.lang || 'en').toLowerCase();
// Si es image-board, ignoramos el filtro de idioma (ya que no tienen idioma)
// O podemos decidir que siempre pasen, o que solo pasen si el filtro es "All".
// Para simplificar: Si es image-board, pasa el filtro de idioma automáticamente.
if (item.type !== 'image-board' && itemLang !== 'multi' && itemLang !== langFilter.toLowerCase()) return false;
}
return true;
});
const sortedTypes = Object.keys(groups).sort();
const grouped = groupBy(items, 'type');
const types = Object.keys(grouped).sort();
if (sortedTypes.length === 0) {
marketplaceContent.innerHTML = `<p class="empty-msg">No extensions found for this criteria.</p>`;
return;
}
if (types.length === 0) return renderEmptyState();
sortedTypes.forEach(type => {
types.forEach(type => {
const section = document.createElement('div');
section.className = 'category-group';
section.className = 'mp-section';
const title = document.createElement('h2');
title.className = 'marketplace-section-title';
title.innerText = type.replace('-', ' ');
title.className = 'category-title';
title.innerText = formatType(type);
const grid = document.createElement('div');
grid.className = 'marketplace-grid';
groups[type].forEach(ext => grid.appendChild(createCard(ext)));
grid.className = 'mp-grid';
grouped[type].forEach(ext => grid.appendChild(createCard(ext)));
section.appendChild(title);
section.appendChild(grid);
marketplaceContent.appendChild(section);
dom.content.appendChild(section);
});
}
function createCard(ext) {
const card = document.createElement('div');
card.className = `extension-card ${ext.nsfw ? 'nsfw-ext' : ''} ${ext.broken ? 'broken-ext' : ''}`;
card.className = `mp-card ${ext.nsfw ? 'card-nsfw' : ''}`;
const iconUrl = `https://www.google.com/s2/favicons?domain=${ext.domain}&sz=128`;
// Icon logic
const iconSrc = ext.icon || '/public/assets/waifuboards.ico';
// Button Logic
let btnClass = 'btn-primary';
let btnText = 'Install';
let buttonHtml = '';
if (ext.isInstalled) {
buttonHtml = `<button class="extension-action-button btn-uninstall">Uninstall</button>`;
btnClass = 'btn-danger';
btnText = 'Uninstall';
} else if (ext.broken) {
buttonHtml = `<button class="extension-action-button" style="background: #4b5563; cursor: not-allowed;" disabled>Broken</button>`;
} else {
buttonHtml = `<button class="extension-action-button btn-install">Install</button>`;
btnClass = 'btn-secondary';
btnText = 'Broken';
}
// Language Pill Logic
let langHtml = '';
// Solo mostramos lenguaje si NO es un image-board
if (ext.type !== 'image-board') {
const langCode = (ext.lang || 'EN').toLowerCase();
const langClass = `lang-${langCode}`;
const langLabel = langCode === 'multi' ? 'MULTI' : langCode.toUpperCase();
langHtml = `<span class="pill ${langClass}">${langLabel}</span>`;
}
card.innerHTML = `
<img class="extension-icon" src="${iconUrl}" onerror="this.src='/public/assets/waifuboards.ico'">
<div class="card-content-wrapper">
<h3 class="extension-name">${ext.name}</h3>
<span class="extension-author">by ${ext.author || 'Unknown'}</span>
<p class="extension-description">${ext.description || 'No description available.'}</p>
<div class="extension-tags">
<span class="extension-status-badge badge-${ext.isInstalled ? 'installed' : (ext.broken ? 'local' : 'available')}">
${ext.isInstalled ? 'Installed' : (ext.broken ? 'Broken' : 'Available')}
</span>
${ext.nsfw ? '<span class="extension-status-badge badge-local">NSFW</span>' : ''}
<div class="card-header">
<img class="card-icon" src="${iconSrc}" loading="lazy" onerror="this.src='/public/assets/waifuboards.ico'">
<div class="card-info">
<h3 class="card-title" title="${ext.name}">${ext.name}</h3>
<span class="card-author">by ${ext.author || 'Unknown'}</span>
</div>
</div>
${buttonHtml}
<div class="card-meta">
${langHtml}
${ext.isInstalled ? '<span class="pill status-installed">INSTALLED</span>' : ''}
${ext.nsfw ? '<span class="pill nsfw">NSFW</span>' : ''}
</div>
<p class="card-desc">${ext.description || 'No description provided.'}</p>
<div class="card-actions">
<button class="btn-primary btn-card ${btnClass}" ${ext.broken && !ext.isInstalled ? 'disabled' : ''}>
${btnText}
</button>
</div>
`;
const btn = card.querySelector('.extension-action-button');
const btn = card.querySelector('button');
if (!ext.broken || ext.isInstalled) {
btn.onclick = () => ext.isInstalled ? promptUninstall(ext) : handleInstall(ext);
btn.onclick = () => ext.isInstalled ? confirmUninstall(ext) : installExtension(ext);
}
return card;
}
function showModal(title, message, showConfirm = false, onConfirm = null) {
modalTitle.innerText = title;
modalMessage.innerText = message;
if (showConfirm) {
modalConfirmBtn.classList.remove('hidden');
modalConfirmBtn.onclick = () => { hideModal(); if (onConfirm) onConfirm(); };
} else {
modalConfirmBtn.classList.add('hidden');
}
modalCloseBtn.onclick = hideModal;
modal2.classList.remove('hidden');
}
function hideModal() { modal2.classList.add('hidden'); }
async function handleInstall(ext) {
/* --- Actions & Helpers --- */
async function installExtension(ext) {
if (!ext.entry) return window.NotificationUtils.error('Invalid extension entry point');
try {
window.NotificationUtils.info(`Installing ${ext.name}...`);
const res = await fetch('/api/extensions/install', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: ext.entry })
});
if (res.ok) {
installedExtensions.push(ext.id.toLowerCase());
renderGroupedView();
window.NotificationUtils.success(`${ext.name} installed!`);
}
} catch (e) { window.NotificationUtils.error('Install failed.'); }
window.NotificationUtils.success(`${ext.name} Installed!`);
state.installed.push(ext.id.toLowerCase());
render();
} else throw new Error('Install failed');
} catch (e) { window.NotificationUtils.error(`Failed to install ${ext.name}`); }
}
function promptUninstall(ext) {
showModal('Confirm', `Uninstall ${ext.name}?`, true, () => handleUninstall(ext));
function confirmUninstall(ext) {
showModal('Uninstall Extension', `Remove ${ext.name}?`, true, () => uninstallExtension(ext));
}
async function handleUninstall(ext) {
async function uninstallExtension(ext) {
try {
const res = await fetch('/api/extensions/uninstall', {
method: 'POST',
@@ -244,19 +316,53 @@ async function handleUninstall(ext) {
body: JSON.stringify({ fileName: ext.id + '.js' })
});
if (res.ok) {
installedExtensions = installedExtensions.filter(id => id !== ext.id.toLowerCase());
renderGroupedView();
window.NotificationUtils.info(`${ext.name} uninstalled.`);
state.installed = state.installed.filter(id => id !== ext.id.toLowerCase());
window.NotificationUtils.success(`${ext.name} removed.`);
render();
}
} catch (e) { window.NotificationUtils.error('Uninstall failed.'); }
} catch (e) { window.NotificationUtils.error('Uninstall failed'); }
}
function showSkeletons() {
marketplaceContent.innerHTML = `
<div class="marketplace-grid">
${Array(3).fill('<div class="extension-card skeleton"></div>').join('')}
async function handleUpdateAll() {
const btn = dom.btnUpdateAll;
const oldText = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = 'Updating...';
try {
const res = await fetch(UPDATE_EXTENSIONS_API, { method: 'POST' });
const data = await res.json();
if (data.updated?.length) {
window.NotificationUtils.success(`Updated ${data.updated.length} extensions.`);
loadData();
} else window.NotificationUtils.info('All up to date.');
} catch (e) { window.NotificationUtils.error('Bulk update failed.'); }
finally { btn.disabled = false; btn.innerHTML = oldText; }
}
function renderWelcomeState() {
dom.content.innerHTML = `
<div class="empty-state">
<div style="font-size: 3rem; margin-bottom: 1rem;">🔌</div>
<h2>Configure Source</h2>
<p class="empty-text" style="max-width: 500px; margin: 0 auto 2rem;">Configure a source URL to start.</p>
<button class="btn-primary" onclick="document.getElementById('config-panel').classList.remove('hidden'); document.getElementById('source-url-input').focus();">Setup URL</button>
</div>
`;
}
document.addEventListener('DOMContentLoaded', loadMarketplace);
function renderEmptyState() {
dom.content.innerHTML = `<div class="empty-state"><div style="font-size: 3rem;">🔍</div><p class="empty-text">No extensions found.</p></div>`;
}
function renderLoading() { dom.content.innerHTML = '<div class="empty-state"><p class="empty-text">Loading...</p></div>'; }
function renderError(msg) { dom.content.innerHTML = `<div class="empty-state"><p class="empty-text" style="color:#f87171;">Error: ${msg}</p></div>`; }
function showModal(title, msg, hasConfirm, onConfirm) {
dom.modalTitle.innerText = title; dom.modalMsg.innerText = msg; dom.modal.classList.remove('hidden');
if (hasConfirm) { dom.modalConfirm.classList.remove('hidden'); dom.modalConfirm.onclick = () => { hideModal(); if (onConfirm) onConfirm(); }; }
else dom.modalConfirm.classList.add('hidden');
}
function hideModal() { dom.modal.classList.add('hidden'); }
function groupBy(arr, key) { return arr.reduce((acc, i) => ((acc[i[key] || 'Other'] = acc[i[key] || 'Other'] || []).push(i), acc), {}); }
function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); }
function formatType(t) { return t.replace(/-/g, ' ').toUpperCase(); }
document.addEventListener('DOMContentLoaded', init);