661 lines
22 KiB
JavaScript
661 lines
22 KiB
JavaScript
const API = '/api';
|
|
let state = {
|
|
categories: [],
|
|
activeCategoryId: null,
|
|
subcategories: [],
|
|
activeSubcategoryId: null,
|
|
links: []
|
|
};
|
|
|
|
const globeSVG = `<svg class="globe-icon" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
<circle cx="10" cy="10" r="9" stroke="#e8722a" stroke-width="1"/>
|
|
<ellipse cx="10" cy="10" rx="4.5" ry="9" stroke="#e8722a" stroke-width="1"/>
|
|
<line x1="1" y1="7" x2="19" y2="7" stroke="#e8722a" stroke-width="1"/>
|
|
<line x1="1" y1="13" x2="19" y2="13" stroke="#e8722a" stroke-width="1"/>
|
|
<line x1="10" y1="1" x2="10" y2="19" stroke="#e8722a" stroke-width="1"/>
|
|
</svg>`;
|
|
|
|
let categorySortable = null;
|
|
let subcategorySortable = null;
|
|
let linkSortable = null;
|
|
|
|
async function api(method, path, body) {
|
|
const opts = {
|
|
method,
|
|
headers: body ? { 'Content-Type': 'application/json' } : {}
|
|
};
|
|
if (body) opts.body = JSON.stringify(body);
|
|
const res = await fetch(API + path, opts);
|
|
if (!res.ok) throw new Error(await res.text());
|
|
return res.json();
|
|
}
|
|
const get = (path) => api('GET', path);
|
|
const post = (path, body) => api('POST', path, body);
|
|
const put = (path, body) => api('PUT', path, body);
|
|
const del = (path) => api('DELETE', path);
|
|
|
|
async function reorder(type, ids) {
|
|
await put('/reorder', { type, ids });
|
|
}
|
|
|
|
async function loadCategories() {
|
|
state.categories = await get('/categories');
|
|
renderCategoryNav();
|
|
if (state.categories.length > 0) {
|
|
await selectCategory(
|
|
state.activeCategoryId && state.categories.find(c => c.id === state.activeCategoryId)
|
|
? state.activeCategoryId
|
|
: state.categories[0].id
|
|
);
|
|
}
|
|
}
|
|
|
|
function renderCategoryNav() {
|
|
const nav = document.getElementById('category-nav');
|
|
nav.innerHTML = '';
|
|
state.categories.forEach(cat => {
|
|
const btn = document.createElement('button');
|
|
btn.className = 'cat-tab' + (cat.id === state.activeCategoryId ? ' active' : '');
|
|
btn.dataset.id = cat.id;
|
|
btn.innerHTML = `<i class="ti ${cat.icon || 'ti-folder'}"></i>${cat.name}`;
|
|
btn.onclick = () => selectCategory(cat.id);
|
|
btn.oncontextmenu = (e) => { e.preventDefault(); openEditCategoryModal(cat); };
|
|
nav.appendChild(btn);
|
|
});
|
|
if (categorySortable) categorySortable.destroy();
|
|
categorySortable = Sortable.create(nav, {
|
|
animation: 150,
|
|
ghostClass: 'sortable-ghost',
|
|
chosenClass: 'sortable-chosen',
|
|
onEnd: async (evt) => {
|
|
const ids = [...nav.querySelectorAll('button[data-id]')]
|
|
.map(el => parseInt(el.dataset.id));
|
|
state.categories = ids.map((id, i) => {
|
|
const cat = state.categories.find(c => c.id === id);
|
|
return { ...cat, position: i };
|
|
});
|
|
await reorder('categories', ids);
|
|
}
|
|
});
|
|
}
|
|
|
|
async function selectCategory(id) {
|
|
state.activeCategoryId = id;
|
|
state.subcategories = await get('/subcategories/' + id);
|
|
state.activeSubcategoryId = null;
|
|
renderCategoryNav();
|
|
renderSubcategoryBar();
|
|
if (state.subcategories.length > 0) {
|
|
await selectSubcategory(state.subcategories[0].id);
|
|
} else {
|
|
state.links = [];
|
|
renderLinkGrid();
|
|
}
|
|
}
|
|
|
|
function renderSubcategoryBar() {
|
|
const bar = document.getElementById('subcategory-bar');
|
|
bar.innerHTML = '';
|
|
state.subcategories.forEach(sub => {
|
|
const btn = document.createElement('button');
|
|
btn.className = 'sub-tab' + (sub.id === state.activeSubcategoryId ? ' active' : '');
|
|
btn.dataset.id = sub.id;
|
|
btn.textContent = sub.name;
|
|
btn.onclick = () => selectSubcategory(sub.id);
|
|
btn.oncontextmenu = (e) => { e.preventDefault(); openEditSubcategoryModal(sub); };
|
|
bar.appendChild(btn);
|
|
});
|
|
const addBtn = document.createElement('button');
|
|
addBtn.className = 'btn-add-sub';
|
|
addBtn.id = 'add-sub-btn';
|
|
addBtn.innerHTML = '<i class="ti ti-plus"></i> Add subcategory';
|
|
addBtn.onclick = () => openAddSubcategoryModal();
|
|
bar.appendChild(addBtn);
|
|
if (subcategorySortable) subcategorySortable.destroy();
|
|
subcategorySortable = Sortable.create(bar, {
|
|
animation: 150,
|
|
ghostClass: 'sortable-ghost',
|
|
chosenClass: 'sortable-chosen',
|
|
filter: '#add-sub-btn',
|
|
onEnd: async (evt) => {
|
|
const ids = [...bar.querySelectorAll('button[data-id]')]
|
|
.map(el => parseInt(el.dataset.id));
|
|
state.subcategories = ids.map((id, i) => {
|
|
const sub = state.subcategories.find(s => s.id === id);
|
|
return { ...sub, position: i };
|
|
});
|
|
await reorder('subcategories', ids);
|
|
}
|
|
});
|
|
}
|
|
|
|
async function selectSubcategory(id) {
|
|
state.activeSubcategoryId = id;
|
|
state.links = await get('/links/' + id);
|
|
renderSubcategoryBar();
|
|
renderLinkGrid();
|
|
}
|
|
|
|
function renderLinkGrid() {
|
|
const grid = document.getElementById('link-grid');
|
|
grid.innerHTML = '';
|
|
state.links.forEach(link => {
|
|
const a = document.createElement('a');
|
|
a.className = 'link-card';
|
|
a.href = link.url;
|
|
a.target = '_blank';
|
|
a.rel = 'noopener noreferrer';
|
|
a.dataset.id = link.id;
|
|
const favicon = document.createElement('div');
|
|
favicon.className = 'link-favicon';
|
|
if (link.favicon) {
|
|
const img = document.createElement('img');
|
|
img.src = '/favicons/' + link.favicon;
|
|
img.width = 20;
|
|
img.height = 20;
|
|
img.onerror = () => { favicon.innerHTML = globeSVG; };
|
|
favicon.appendChild(img);
|
|
} else {
|
|
favicon.innerHTML = globeSVG;
|
|
}
|
|
const label = document.createElement('span');
|
|
label.className = 'link-label';
|
|
label.textContent = link.label;
|
|
const actions = document.createElement('div');
|
|
actions.className = 'link-actions';
|
|
actions.innerHTML = `
|
|
<button class="link-action-btn" title="Edit" onclick="openEditLinkModal(${JSON.stringify(link).replace(/"/g, '"')}, event)">
|
|
<i class="ti ti-pencil"></i>
|
|
</button>
|
|
<button class="link-action-btn" title="Delete" onclick="deleteLink(${link.id}, event)">
|
|
<i class="ti ti-trash"></i>
|
|
</button>
|
|
`;
|
|
a.appendChild(favicon);
|
|
a.appendChild(label);
|
|
a.appendChild(actions);
|
|
grid.appendChild(a);
|
|
});
|
|
const addCard = document.createElement('button');
|
|
addCard.className = 'add-link-card';
|
|
addCard.id = 'add-link-card';
|
|
addCard.innerHTML = '<i class="ti ti-plus"></i> Add link';
|
|
addCard.onclick = () => openAddLinkModal();
|
|
grid.appendChild(addCard);
|
|
if (linkSortable) linkSortable.destroy();
|
|
linkSortable = Sortable.create(grid, {
|
|
animation: 150,
|
|
ghostClass: 'sortable-ghost',
|
|
chosenClass: 'sortable-chosen',
|
|
filter: '#add-link-card',
|
|
draggable: 'a.link-card',
|
|
onEnd: async (evt) => {
|
|
const ids = [...grid.querySelectorAll('a.link-card[data-id]')]
|
|
.map(el => parseInt(el.dataset.id));
|
|
state.links = ids.map((id, i) => {
|
|
const link = state.links.find(l => l.id === id);
|
|
return { ...link, position: i };
|
|
});
|
|
await reorder('links', ids);
|
|
}
|
|
});
|
|
}
|
|
|
|
function openModal(title, bodyHTML, onConfirm) {
|
|
document.getElementById('modal-title').textContent = title;
|
|
document.getElementById('modal-body').innerHTML = bodyHTML + `
|
|
<div class="modal-actions">
|
|
<button class="btn-secondary" id="modal-cancel">Cancel</button>
|
|
<button class="btn-primary" id="modal-confirm">Save</button>
|
|
</div>
|
|
`;
|
|
document.getElementById('modal-overlay').classList.remove('hidden');
|
|
document.getElementById('modal-cancel').onclick = closeModal;
|
|
document.getElementById('modal-close').onclick = closeModal;
|
|
document.getElementById('modal-confirm').onclick = onConfirm;
|
|
}
|
|
|
|
function closeModal() {
|
|
document.getElementById('modal-overlay').classList.add('hidden');
|
|
}
|
|
|
|
function openAddCategoryModal() {
|
|
openModal('Add category', `
|
|
<div class="field">
|
|
<label>Name</label>
|
|
<input type="text" id="f-name" placeholder="Homelab" />
|
|
</div>
|
|
<div class="field">
|
|
<label>Icon (Tabler icon name)</label>
|
|
<input type="text" id="f-icon" placeholder="ti-server" />
|
|
</div>
|
|
`, async () => {
|
|
const name = document.getElementById('f-name').value.trim();
|
|
const icon = document.getElementById('f-icon').value.trim();
|
|
if (!name) return;
|
|
await post('/categories', { name, icon, position: state.categories.length });
|
|
closeModal();
|
|
await loadCategories();
|
|
});
|
|
}
|
|
|
|
function openEditCategoryModal(cat) {
|
|
openModal('Edit category', `
|
|
<div class="field">
|
|
<label>Name</label>
|
|
<input type="text" id="f-name" value="${cat.name}" />
|
|
</div>
|
|
<div class="field">
|
|
<label>Icon (Tabler icon name)</label>
|
|
<input type="text" id="f-icon" value="${cat.icon || ''}" />
|
|
</div>
|
|
<div class="modal-actions" style="justify-content:flex-start; margin-top:0">
|
|
<button class="btn-secondary" style="color:#e8722a;border-color:#e8722a"
|
|
onclick="deleteCategory(${cat.id})">Delete category</button>
|
|
</div>
|
|
`, async () => {
|
|
const name = document.getElementById('f-name').value.trim();
|
|
const icon = document.getElementById('f-icon').value.trim();
|
|
if (!name) return;
|
|
await put('/categories/' + cat.id, { name, icon, position: cat.position });
|
|
closeModal();
|
|
await loadCategories();
|
|
});
|
|
}
|
|
|
|
function openAddSubcategoryModal() {
|
|
openModal('Add subcategory', `
|
|
<div class="field">
|
|
<label>Name</label>
|
|
<input type="text" id="f-name" placeholder="Self-hosted" />
|
|
</div>
|
|
`, async () => {
|
|
const name = document.getElementById('f-name').value.trim();
|
|
if (!name) return;
|
|
await post('/subcategories', {
|
|
category_id: state.activeCategoryId,
|
|
name,
|
|
position: state.subcategories.length
|
|
});
|
|
closeModal();
|
|
await selectCategory(state.activeCategoryId);
|
|
});
|
|
}
|
|
|
|
function openEditSubcategoryModal(sub) {
|
|
openModal('Edit subcategory', `
|
|
<div class="field">
|
|
<label>Name</label>
|
|
<input type="text" id="f-name" value="${sub.name}" />
|
|
</div>
|
|
<div class="modal-actions" style="justify-content:flex-start; margin-top:0">
|
|
<button class="btn-secondary" style="color:#e8722a;border-color:#e8722a"
|
|
onclick="deleteSubcategory(${sub.id})">Delete subcategory</button>
|
|
</div>
|
|
`, async () => {
|
|
const name = document.getElementById('f-name').value.trim();
|
|
if (!name) return;
|
|
await put('/subcategories/' + sub.id, {
|
|
category_id: state.activeCategoryId,
|
|
name,
|
|
position: sub.position
|
|
});
|
|
closeModal();
|
|
await selectCategory(state.activeCategoryId);
|
|
});
|
|
}
|
|
|
|
// Build the category+subcategory select HTML for link modals.
|
|
// selectedCatId / selectedSubId pre-select the dropdowns (used in edit mode).
|
|
function buildLocationFields(selectedCatId, selectedSubId) {
|
|
const catOptions = state.categories.map(c =>
|
|
`<option value="${c.id}" ${c.id === selectedCatId ? 'selected' : ''}>${c.name}</option>`
|
|
).join('');
|
|
return `
|
|
<div class="field">
|
|
<label>Category</label>
|
|
<select id="f-cat">${catOptions}</select>
|
|
</div>
|
|
<div class="field">
|
|
<label>Subcategory</label>
|
|
<select id="f-sub"><option value="">Loading…</option></select>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
// Populate the subcategory dropdown for the given category id.
|
|
// If targetSubId is provided, pre-select it.
|
|
async function populateSubSelect(catId, targetSubId) {
|
|
const subEl = document.getElementById('f-sub');
|
|
if (!subEl) return;
|
|
subEl.innerHTML = '<option value="">Loading…</option>';
|
|
const subs = await get('/subcategories/' + catId);
|
|
if (subs.length === 0) {
|
|
subEl.innerHTML = '<option value="">(no subcategories)</option>';
|
|
return;
|
|
}
|
|
subEl.innerHTML = subs.map(s =>
|
|
`<option value="${s.id}" ${s.id === targetSubId ? 'selected' : ''}>${s.name}</option>`
|
|
).join('');
|
|
}
|
|
|
|
function openAddLinkModal() {
|
|
const defaultCatId = state.activeCategoryId || (state.categories[0] && state.categories[0].id);
|
|
const defaultSubId = state.activeSubcategoryId;
|
|
|
|
openModal('Add link', `
|
|
<div class="field">
|
|
<label>Label</label>
|
|
<input type="text" id="f-label" placeholder="Forgejo" />
|
|
</div>
|
|
<div class="field">
|
|
<label>URL</label>
|
|
<input type="text" id="f-url" placeholder="https://..." />
|
|
</div>
|
|
${buildLocationFields(defaultCatId, defaultSubId)}
|
|
<div class="field favicon-field">
|
|
<label>Favicon</label>
|
|
<div class="favicon-preview-row">
|
|
<div id="f-favicon-preview" class="favicon-preview-box"></div>
|
|
<span id="f-favicon-status" class="favicon-status"></span>
|
|
<button type="button" class="btn-ghost favicon-upload-btn" id="f-favicon-upload-btn" style="display:none">
|
|
<i class="ti ti-upload"></i> Upload manually
|
|
</button>
|
|
<input type="file" id="f-favicon-file" accept="image/*" style="display:none" />
|
|
<input type="hidden" id="f-favicon" value="" />
|
|
</div>
|
|
</div>
|
|
`, async () => {
|
|
const label = document.getElementById('f-label').value.trim();
|
|
const url = document.getElementById('f-url').value.trim();
|
|
const favicon = document.getElementById('f-favicon').value.trim();
|
|
const subId = parseInt(document.getElementById('f-sub').value);
|
|
if (!label || !url || !subId) return;
|
|
// Find position: end of the target subcategory's links
|
|
const targetLinks = await get('/links/' + subId);
|
|
await post('/links', {
|
|
subcategory_id: subId,
|
|
label,
|
|
url,
|
|
favicon: favicon || null,
|
|
position: targetLinks.length
|
|
});
|
|
closeModal();
|
|
// If we added to the currently-viewed subcategory, refresh it; otherwise navigate there
|
|
if (subId === state.activeSubcategoryId) {
|
|
await selectSubcategory(state.activeSubcategoryId);
|
|
} else {
|
|
// Find the category for this subcategory and navigate
|
|
const allCats = state.categories;
|
|
for (const cat of allCats) {
|
|
const subs = await get('/subcategories/' + cat.id);
|
|
if (subs.find(s => s.id === subId)) {
|
|
await selectCategory(cat.id);
|
|
await selectSubcategory(subId);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
// Populate subcategory dropdown for the initial category
|
|
populateSubSelect(defaultCatId, defaultSubId);
|
|
|
|
// When category changes, reload subcategory dropdown
|
|
setTimeout(() => {
|
|
const catEl = document.getElementById('f-cat');
|
|
if (catEl) {
|
|
catEl.addEventListener('change', () => {
|
|
populateSubSelect(parseInt(catEl.value), null);
|
|
});
|
|
}
|
|
}, 0);
|
|
|
|
setupFaviconFetch('f-url', 'f-favicon', 'f-favicon-preview', 'f-favicon-status', 'f-favicon-upload-btn', 'f-favicon-file');
|
|
}
|
|
|
|
async function openEditLinkModal(link, e) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
|
|
// Determine which category owns this link's subcategory so we can pre-select it
|
|
let ownerCatId = state.activeCategoryId;
|
|
// Search all categories for the one that contains link.subcategory_id
|
|
for (const cat of state.categories) {
|
|
const subs = await get('/subcategories/' + cat.id);
|
|
if (subs.find(s => s.id === link.subcategory_id)) {
|
|
ownerCatId = cat.id;
|
|
break;
|
|
}
|
|
}
|
|
|
|
openModal('Edit link', `
|
|
<div class="field">
|
|
<label>Label</label>
|
|
<input type="text" id="f-label" value="${link.label}" />
|
|
</div>
|
|
<div class="field">
|
|
<label>URL</label>
|
|
<input type="text" id="f-url" value="${link.url}" />
|
|
</div>
|
|
${buildLocationFields(ownerCatId, link.subcategory_id)}
|
|
<div class="field favicon-field">
|
|
<label>Favicon</label>
|
|
<div class="favicon-preview-row">
|
|
<div id="f-favicon-preview" class="favicon-preview-box"></div>
|
|
<span id="f-favicon-status" class="favicon-status"></span>
|
|
<button type="button" class="btn-ghost favicon-upload-btn" id="f-favicon-upload-btn" style="display:none">
|
|
<i class="ti ti-upload"></i> Upload manually
|
|
</button>
|
|
<input type="file" id="f-favicon-file" accept="image/*" style="display:none" />
|
|
<input type="hidden" id="f-favicon" value="${link.favicon || ''}" />
|
|
</div>
|
|
</div>
|
|
<div class="modal-actions" style="justify-content:flex-start; margin-top:0">
|
|
<button class="btn-secondary" style="color:#e8722a;border-color:#e8722a"
|
|
onclick="deleteLink(${link.id}, event)">Delete link</button>
|
|
</div>
|
|
`, async () => {
|
|
const label = document.getElementById('f-label').value.trim();
|
|
const url = document.getElementById('f-url').value.trim();
|
|
const favicon = document.getElementById('f-favicon').value.trim();
|
|
const newSubId = parseInt(document.getElementById('f-sub').value);
|
|
if (!label || !url || !newSubId) return;
|
|
|
|
const isMoving = newSubId !== link.subcategory_id;
|
|
let position = link.position;
|
|
if (isMoving) {
|
|
// Place at end of the destination subcategory
|
|
const targetLinks = await get('/links/' + newSubId);
|
|
position = targetLinks.length;
|
|
}
|
|
|
|
await put('/links/' + link.id, {
|
|
subcategory_id: newSubId,
|
|
label,
|
|
url,
|
|
favicon: favicon || null,
|
|
position
|
|
});
|
|
closeModal();
|
|
|
|
if (!isMoving) {
|
|
// Same subcategory — just refresh current view
|
|
await selectSubcategory(state.activeSubcategoryId);
|
|
} else {
|
|
// Link moved away — refresh current subcategory (link is gone from here)
|
|
// Then optionally navigate to the destination
|
|
await selectSubcategory(state.activeSubcategoryId);
|
|
}
|
|
});
|
|
|
|
// Populate subcategory dropdown for the owner category
|
|
populateSubSelect(ownerCatId, link.subcategory_id);
|
|
|
|
// When category changes, reload subcategory dropdown
|
|
setTimeout(() => {
|
|
const catEl = document.getElementById('f-cat');
|
|
if (catEl) {
|
|
catEl.addEventListener('change', () => {
|
|
populateSubSelect(parseInt(catEl.value), null);
|
|
});
|
|
}
|
|
}, 0);
|
|
|
|
setupFaviconFetch('f-url', 'f-favicon', 'f-favicon-preview', 'f-favicon-status', 'f-favicon-upload-btn', 'f-favicon-file', link.favicon);
|
|
}
|
|
|
|
async function deleteCategory(id) {
|
|
closeModal();
|
|
await del('/categories/' + id);
|
|
state.activeCategoryId = null;
|
|
await loadCategories();
|
|
}
|
|
|
|
async function deleteSubcategory(id) {
|
|
closeModal();
|
|
await del('/subcategories/' + id);
|
|
await selectCategory(state.activeCategoryId);
|
|
}
|
|
|
|
async function deleteLink(id, e) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
await del('/links/' + id);
|
|
await selectSubcategory(state.activeSubcategoryId);
|
|
}
|
|
|
|
document.getElementById('search-form').addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
const q = document.getElementById('search-input').value.trim();
|
|
if (q) window.open('https://kagi.com/search?q=' + encodeURIComponent(q), '_blank');
|
|
});
|
|
|
|
document.getElementById('add-category-btn').onclick = openAddCategoryModal;
|
|
|
|
document.getElementById('modal-overlay').addEventListener('click', (e) => {
|
|
if (e.target === document.getElementById('modal-overlay')) closeModal();
|
|
});
|
|
|
|
loadCategories();
|
|
|
|
// Export
|
|
function exportBookmarks(format) {
|
|
document.getElementById('export-dropdown').classList.remove('open');
|
|
const a = document.createElement('a');
|
|
a.href = API + '/export/' + format;
|
|
a.download = format === 'json' ? 'startpage-bookmarks.json' : 'startpage-bookmarks.html';
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
}
|
|
|
|
// Export dropdown toggle
|
|
document.getElementById('export-btn').addEventListener('click', (e) => {
|
|
e.stopPropagation();
|
|
document.getElementById('export-dropdown').classList.toggle('open');
|
|
});
|
|
|
|
document.addEventListener('click', () => {
|
|
document.getElementById('export-dropdown').classList.remove('open');
|
|
});
|
|
|
|
// Import
|
|
function triggerImport() {
|
|
document.getElementById('export-dropdown').classList.remove('open');
|
|
document.getElementById('import-file-input').click();
|
|
}
|
|
|
|
document.getElementById('import-file-input').addEventListener('change', async (e) => {
|
|
const file = e.target.files[0];
|
|
if (!file) return;
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
try {
|
|
const res = await fetch(API + '/import/html', { method: 'POST', body: formData });
|
|
if (!res.ok) throw new Error(await res.text());
|
|
const result = await res.json();
|
|
const i = result.imported;
|
|
alert('Imported: ' + i.categories + ' categories, ' + i.subcategories + ' subcategories, ' + i.links + ' links.');
|
|
await loadCategories();
|
|
} catch (err) {
|
|
alert('Import failed: ' + err.message);
|
|
}
|
|
e.target.value = '';
|
|
});
|
|
|
|
// Favicon auto-fetch + manual upload helper
|
|
function setupFaviconFetch(urlId, faviconId, previewId, statusId, uploadBtnId, fileInputId, existingFavicon) {
|
|
const urlEl = document.getElementById(urlId);
|
|
const faviconEl = document.getElementById(faviconId);
|
|
const previewEl = document.getElementById(previewId);
|
|
const statusEl = document.getElementById(statusId);
|
|
const uploadBtn = document.getElementById(uploadBtnId);
|
|
const fileInput = document.getElementById(fileInputId);
|
|
|
|
function showPreview(filename) {
|
|
if (filename) {
|
|
previewEl.innerHTML = '<img src="/favicons/' + filename + '" width="20" height="20" onerror="this.parentNode.innerHTML=\'<span style=opacity:.4>?</span>\'" />';
|
|
} else {
|
|
previewEl.innerHTML = '';
|
|
}
|
|
}
|
|
|
|
if (existingFavicon) {
|
|
showPreview(existingFavicon);
|
|
statusEl.textContent = existingFavicon;
|
|
uploadBtn.style.display = 'inline-flex';
|
|
}
|
|
|
|
async function doFetch(url) {
|
|
if (!url || !url.startsWith('http')) return;
|
|
statusEl.textContent = 'Fetching…';
|
|
uploadBtn.style.display = 'none';
|
|
try {
|
|
const res = await fetch(API + '/favicons/fetch', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ url })
|
|
});
|
|
const data = await res.json();
|
|
if (data.favicon) {
|
|
faviconEl.value = data.favicon;
|
|
showPreview(data.favicon);
|
|
statusEl.textContent = data.favicon;
|
|
uploadBtn.style.display = 'inline-flex';
|
|
} else {
|
|
faviconEl.value = '';
|
|
previewEl.innerHTML = '';
|
|
statusEl.textContent = 'Not found';
|
|
uploadBtn.style.display = 'inline-flex';
|
|
}
|
|
} catch (err) {
|
|
statusEl.textContent = 'Failed';
|
|
uploadBtn.style.display = 'inline-flex';
|
|
}
|
|
}
|
|
|
|
urlEl.addEventListener('blur', () => doFetch(urlEl.value.trim()));
|
|
|
|
uploadBtn.addEventListener('click', () => fileInput.click());
|
|
|
|
fileInput.addEventListener('change', async (e) => {
|
|
const file = e.target.files[0];
|
|
if (!file) return;
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
statusEl.textContent = 'Uploading…';
|
|
try {
|
|
const res = await fetch(API + '/favicons/upload', { method: 'POST', body: formData });
|
|
const data = await res.json();
|
|
if (data.favicon) {
|
|
faviconEl.value = data.favicon;
|
|
showPreview(data.favicon);
|
|
statusEl.textContent = data.favicon;
|
|
}
|
|
} catch (err) {
|
|
statusEl.textContent = 'Upload failed';
|
|
}
|
|
e.target.value = '';
|
|
});
|
|
}
|