startpage/frontend/app.js

563 lines
19 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>`;
// Sortable instances — kept so we can destroy/recreate on re-render
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);
});
// Destroy old instance before creating new one
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, '&quot;')}, 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);
});
}
function openAddLinkModal() {
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>
<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();
if (!label || !url) return;
await post('/links', {
subcategory_id: state.activeSubcategoryId,
label,
url,
favicon: favicon || null,
position: state.links.length
});
closeModal();
await selectSubcategory(state.activeSubcategoryId);
});
setupFaviconFetch('f-url', 'f-favicon', 'f-favicon-preview', 'f-favicon-status', 'f-favicon-upload-btn', 'f-favicon-file');
}
function openEditLinkModal(link, e) {
e.preventDefault();
e.stopPropagation();
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>
<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();
if (!label || !url) return;
await put('/links/' + link.id, {
subcategory_id: state.activeSubcategoryId,
label,
url,
favicon: favicon || null,
position: link.position
});
closeModal();
await selectSubcategory(state.activeSubcategoryId);
});
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 = '';
}
}
// Show existing favicon immediately if editing
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 = '';
});
}