Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
81 lines (72 loc) · 2.21 KB
/
Copy pathscript.js
File metadata and controls
81 lines (72 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
document.addEventListener('DOMContentLoaded', function() {
fetchLinks();
document.getElementById('link-form').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(this);
const linkData = Object.fromEntries(formData);
const response = await fetch('/api/links', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: linkData.edit_password,
link: {
category: linkData.category,
title: linkData.title,
url: linkData.url,
icon: linkData.icon
}
}),
});
if (response.ok) {
alert('链接已保存');
fetchLinks();
this.reset();
} else {
const errorText = await response.text();
alert('保存失败: ' + errorText);
}
});
document.getElementById('toggle-edit').addEventListener('click', function() {
const editForm = document.getElementById('edit-form');
editForm.style.display = editForm.style.display === 'none' ? 'block' : 'none';
});
});
async function fetchLinks() {
const response = await fetch('/api/links');
const links = await response.json();
renderLinks(links);
}
function renderLinks(links) {
document.querySelectorAll('.link-grid').forEach(grid => grid.innerHTML = '');
const linksByCategory = groupBy(links, 'category');
for (const [category, categoryLinks] of Object.entries(linksByCategory)) {
const section = document.querySelector(`#${category} .link-grid`);
if (section) {
categoryLinks.forEach(link => {
const linkCard = createLinkCard(link);
section.appendChild(linkCard);
});
}
}
}
function createLinkCard(link) {
const div = document.createElement('div');
div.className = 'link-card';
div.setAttribute('href', link.url);
div.innerHTML = `
<i class="${link.icon}"></i>
<h3>${link.title}</h3>
`;
div.addEventListener('click', function() {
window.open(link.url, '_blank');
});
return div;
}
function groupBy(array, key) {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
return result;
}, {});
}