-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathscript.js
More file actions
293 lines (248 loc) · 10.1 KB
/
script.js
File metadata and controls
293 lines (248 loc) · 10.1 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
* SeaLantern Plugin Market
* 加载流程:api/plugins.json(路径列表)→ 并发 fetch 各插件 JSON
* 分类由插件自身 categories[] 字段声明,categories.json 仅做 i18n
*/
const state = {
plugins: [],
categories: {}, // { key: { "zh-CN": "...", "en-US": "..." } }
activeCategory: '',
searchQuery: '',
sortBy: 'name'
};
const $ = sel => document.querySelector(sel);
// ==================== 数据加载 ====================
async function fetchJSON(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
return res.json();
}
async function loadData() {
const grid = $('#pluginsGrid');
try {
const [catData, pluginsIndex] = await Promise.all([
fetchJSON('./api/categories.json'),
fetchJSON('./api/plugins.json')
]);
state.categories = catData;
const paths = Array.isArray(pluginsIndex?.paths) ? pluginsIndex.paths : [];
const results = await Promise.allSettled(paths.map(p => fetchJSON(`./${p}`).then(data => ({ ...data, _path: p }))));
state.plugins = results
.filter(r => r.status === 'fulfilled' && r.value?.id)
.map(r => {
const p = r.value;
// 从路径 plugins/username/plugin-id/plugin-id.json 推断 repo 和 author
const parts = p._path?.split('/'); // ["plugins","username","plugin-id","plugin-id.json"]
const username = parts?.[1];
const pluginFolder = parts?.[2];
if (username && pluginFolder) {
if (!p.repo) p.repo = `${username}/${pluginFolder}`;
if (!p.author) p.author = { name: username, url: `https://github.com/${username}` };
}
return p;
});
renderCategories();
renderPlugins();
} catch (e) {
console.error('加载数据失败:', e);
if (grid) grid.innerHTML = '<div class="empty-state"><h3>加载失败</h3><p>请检查 api/plugins.json 和 api/categories.json</p></div>';
}
}
function getUserLang() {
const lang = navigator.language || 'zh-CN';
return lang.startsWith('zh') ? 'zh-CN' : 'en-US';
}
function getCategoryLabel(key) {
const lang = getUserLang();
const cat = state.categories[key];
if (!cat) return key;
return typeof cat === 'string' ? cat : (cat[lang] || cat['zh-CN'] || key);
}
// ==================== 渲染 ====================
function renderCategories() {
// 从插件数据中收集实际存在的分类
const usedCats = new Set();
state.plugins.forEach(p => (p.categories || []).forEach(c => usedCats.add(c)));
const tabs = ['<button class="tab active" data-category="">全部</button>'];
for (const key of usedCats) {
tabs.push(`<button class="tab" data-category="${key}">${escapeHtml(getCategoryLabel(key))}</button>`);
}
const container = $('#categoryTabs');
if (container) container.innerHTML = tabs.join('');
}
function renderPlugins() {
const list = filterAndSort(state.plugins);
const grid = $('#pluginsGrid');
const count = $('#pluginCount');
if (!grid) return;
grid.innerHTML = list.length
? list.map(p => createCard(p)).join('')
: '<div class="empty-state"><h3>没有找到插件</h3></div>';
if (count) {
const total = state.plugins.length;
const shown = list.length;
count.textContent = shown === total ? `共 ${total} 个插件` : `显示 ${shown} / ${total}`;
}
}
function createCard(plugin) {
const lang = getUserLang();
const name = plugin.name?.[lang] || plugin.name?.['zh-CN'] || plugin.id;
const desc = plugin.description?.[lang] || plugin.description?.['zh-CN'] || '';
const cats = (plugin.categories || []).map(c => escapeHtml(getCategoryLabel(c))).join(', ');
const iconHtml = plugin.icon_url
? `<img src="./${plugin._path?.replace(/\/[^/]+$/, '')}/${plugin.icon_url}" alt="" onerror="onerrorSetSvg(this.parentElement)">`
: getDefaultIconSvg();
return `
<article class="plugin-card" data-id="${plugin.id}">
<div class="card-header">
<div class="card-icon">${iconHtml}</div>
<div class="card-info">
<div class="card-name">${escapeHtml(name)}</div>
<div class="card-version">${plugin.version ? 'v' + escapeHtml(plugin.version) : ''}</div>
</div>
</div>
<p class="card-desc">${escapeHtml(desc)}</p>
<div class="card-footer">
<span class="card-author">${escapeHtml(plugin.author?.name || 'Unknown')}</span>
<span class="card-category">${cats}</span>
</div>
</article>
`;
}
function getDefaultIconSvg() {
return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>`;
}
function onerrorSetSvg(element) {
element.innerHTML=getDefaultIconSvg();
}
function renderModal(plugin) {
const body = $('#modalBody');
if (!body) return;
const lang = getUserLang();
const name = plugin.name?.[lang] || plugin.name?.['zh-CN'] || plugin.id;
const desc = plugin.description?.[lang] || plugin.description?.['zh-CN'] || '';
const iconHtml = plugin.icon_url
? `<img src="./${plugin._path?.replace(/\/[^/]+$/, '')}/${plugin.icon_url}" alt="" onerror="onerrorSetSvg(this.parentElement)">`
: getDefaultIconSvg();
const permissionsHtml = (plugin.permissions || []).map(p =>
`<span class="permission ${getPermissionClass(p)}">${escapeHtml(p)}</span>`
).join('');
const cats = (plugin.categories || []).map(c => escapeHtml(getCategoryLabel(c))).join(', ');
const downloadUrl = plugin.download_url || (plugin.repo ? `https://github.com/${plugin.repo}/releases/latest` : '#');
body.innerHTML = `
<div class="detail-header">
<div class="detail-icon">${iconHtml}</div>
<div class="detail-info">
<h2>${escapeHtml(name)}</h2>
<div class="detail-meta">
${plugin.version ? 'v' + escapeHtml(plugin.version) + ' · ' : ''}${cats} ·
by <a href="${escapeHtml(plugin.author?.url || '#')}" target="_blank">${escapeHtml(plugin.author?.name || 'Unknown')}</a>
</div>
</div>
</div>
<div class="detail-section"><h3>简介</h3><p class="detail-desc">${escapeHtml(desc)}</p></div>
${plugin.repo ? `<div class="detail-section"><h3>源代码</h3><p><a href="https://github.com/${escapeHtml(plugin.repo)}" target="_blank">${escapeHtml(plugin.repo)}</a></p></div>` : ''}
${permissionsHtml ? `<div class="detail-section"><h3>所需权限</h3><div class="detail-permissions">${permissionsHtml}</div></div>` : ''}
<div class="detail-actions">
<a href="${downloadUrl}" class="btn-download" target="_blank" rel="noreferrer">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
查看最新版本
</a>
</div>
`;
}
// ==================== 筛选 ====================
function filterAndSort(plugins) {
const lang = getUserLang();
let list = [...plugins];
if (state.activeCategory) {
list = list.filter(p => (p.categories || []).includes(state.activeCategory));
}
if (state.searchQuery) {
const q = state.searchQuery.toLowerCase();
list = list.filter(p => {
const name = (p.name?.[lang] || p.name?.['zh-CN'] || p.id).toLowerCase();
const desc = (p.description?.[lang] || p.description?.['zh-CN'] || '').toLowerCase();
return name.includes(q) || desc.includes(q);
});
}
if (state.sortBy === 'name') {
list.sort((a, b) =>
(a.name?.[lang] || a.name?.['zh-CN'] || a.id)
.localeCompare(b.name?.[lang] || b.name?.['zh-CN'] || b.id, lang)
);
}
return list;
}
function getPermissionClass(perm) {
const dangerous = ['fs', 'network', 'server', 'console'];
const critical = ['execute_program', 'plugin_folder_access'];
if (critical.includes(perm)) return 'permission--critical';
if (dangerous.includes(perm)) return 'permission--dangerous';
return '';
}
function escapeHtml(text) {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// ==================== 事件 ====================
function setupEvents() {
const searchInput = $('#searchInput');
if (searchInput) {
let timer;
searchInput.addEventListener('input', e => {
clearTimeout(timer);
timer = setTimeout(() => { state.searchQuery = e.target.value.trim(); renderPlugins(); }, 250);
});
}
const sortSelect = $('#sortSelect');
if (sortSelect) {
sortSelect.addEventListener('change', e => { state.sortBy = e.target.value; renderPlugins(); });
}
const categoryTabs = $('#categoryTabs');
if (categoryTabs) {
categoryTabs.addEventListener('click', e => {
if (e.target.classList.contains('tab')) {
categoryTabs.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
e.target.classList.add('active');
state.activeCategory = e.target.dataset.category;
renderPlugins();
}
});
}
const pluginsGrid = $('#pluginsGrid');
if (pluginsGrid) {
pluginsGrid.addEventListener('click', e => {
const card = e.target.closest('.plugin-card');
if (!card) return;
const plugin = state.plugins.find(p => p.id === card.dataset.id);
if (plugin) { renderModal(plugin); openModal(); }
});
}
const modal = $('#pluginModal');
if (modal) {
modal.addEventListener('click', e => {
if (e.target.classList.contains('modal-backdrop') || e.target.dataset.close) closeModal();
});
const closeBtn = modal.querySelector('.modal-close');
if (closeBtn) closeBtn.addEventListener('click', closeModal);
}
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
const m = $('#pluginModal');
if (m && m.getAttribute('aria-hidden') === 'false') closeModal();
}
});
}
function openModal() {
const modal = $('#pluginModal');
if (modal) { modal.setAttribute('aria-hidden', 'false'); document.body.style.overflow = 'hidden'; }
}
function closeModal() {
const modal = $('#pluginModal');
if (modal) { modal.setAttribute('aria-hidden', 'true'); document.body.style.overflow = ''; }
}
setupEvents();
loadData();