-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommunity_post.html
More file actions
451 lines (400 loc) · 20.2 KB
/
community_post.html
File metadata and controls
451 lines (400 loc) · 20.2 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>帖子详情 - 幸福小区</title>
<script src="js/Taildwind-browser@4.js"></script>
<script src="js/lucide.js"></script>
<script src="js/jquery-3.7.1.min.js"></script>
<style>
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
.fade-in { animation: fadeIn 0.3s ease-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
/* 评论输入框动画 */
.slide-up { animation: slideUp 0.3s ease-out forwards; }
@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
</style>
</head>
<body class="bg-[#F5F7FA] font-sans text-slate-800 min-h-screen select-none pb-28">
<header class="px-6 pt-12 pb-6 flex justify-between items-center sticky top-0 bg-[#F5F7FA] z-10">
<div class="flex items-center gap-3">
<button onclick="window.location.href='index.html#community'" class="p-1 -ml-1 text-slate-400 active:text-slate-600 transition-colors">
<i data-lucide="chevron-left" width="32" height="32"></i>
</button>
<h1 class="text-4xl font-bold text-slate-900">社区</h1>
</div>
<div class="w-12 h-12 rounded-full overflow-hidden border-2 border-white shadow-md">
<img id="user-avatar" class="w-full h-full object-cover"
src="img/default_avatar.png"
onerror="this.src='img/default_avatar.png'"
alt="Profile">
</div>
</header>
<main class="px-6 fade-in space-y-4">
<div id="post-detail-container">
<div class="bg-white rounded-[2rem] p-6 shadow-sm animate-pulse min-h-[300px]">
<div class="flex items-center gap-3 mb-6">
<div class="w-12 h-12 bg-slate-100 rounded-full shrink-0"></div>
<div class="space-y-2 w-full">
<div class="w-2/3 h-4 bg-slate-100 rounded"></div>
<div class="w-1/3 h-3 bg-slate-100 rounded"></div>
</div>
</div>
<div class="space-y-3">
<div class="w-3/4 h-6 bg-slate-100 rounded"></div>
<div class="w-full h-32 bg-slate-100 rounded"></div>
</div>
</div>
</div>
<div id="comments-container" class="space-y-3 pb-20">
</div>
</main>
<button onclick="openCommentModal()" class="fixed bottom-24 right-6 w-14 h-14 bg-[#1e40af] text-white rounded-full flex items-center justify-center shadow-[0_4px_14px_rgba(30,64,175,0.4)] active:scale-90 transition-transform z-40">
<i data-lucide="message-square-plus" width="24" height="24"></i>
</button>
<div class="fixed bottom-6 left-6 right-6 z-30">
<nav class="bg-white/95 backdrop-blur-md rounded-[2rem] shadow-[0_8px_30px_rgb(0,0,0,0.08)] px-6 py-3 flex justify-between items-center border border-white/50">
<a href="index.html#home" class="flex flex-col items-center gap-1 w-12 text-gray-400 transition-all">
<i data-lucide="home" width="24" height="24" stroke-width="2"></i>
<span class="text-[10px] font-medium">首页</span>
</a>
<a href="index.html#life" class="flex flex-col items-center gap-1 w-12 text-gray-400 transition-all">
<i data-lucide="smile" width="24" height="24" stroke-width="2"></i>
<span class="text-[10px] font-medium">生活</span>
</a>
<a href="index.html#community" class="flex flex-col items-center gap-1 w-12 text-[#3B82F6] -translate-y-1 transition-all">
<i data-lucide="users" width="24" height="24" stroke-width="2.5"></i>
<span class="text-[10px] font-medium">社区</span>
<span class="absolute -bottom-2 w-1 h-1 bg-[#3B82F6] rounded-full"></span>
</a>
<a href="index.html#me" class="flex flex-col items-center gap-1 w-12 text-gray-400 transition-all">
<i data-lucide="user" width="24" height="24" stroke-width="2"></i>
<span class="text-[10px] font-medium">我的</span>
</a>
</nav>
</div>
<div id="comment-modal" class="fixed inset-0 bg-black/40 z-50 hidden flex flex-col justify-end">
<div onclick="closeCommentModal()" class="absolute inset-0"></div>
<div class="bg-white rounded-t-[2rem] p-6 slide-up relative z-10">
<div class="flex justify-between items-center mb-4">
<h3 class="font-bold text-lg" id="comment-title">发表评论</h3>
<button onclick="closeCommentModal()" class="p-2 text-slate-400 hover:text-slate-600">
<i data-lucide="x" width="24" height="24"></i>
</button>
</div>
<form id="comment-form" class="space-y-4">
<textarea id="comment-input" rows="3" class="w-full bg-slate-50 rounded-xl p-4 text-sm outline-none border border-slate-100 focus:border-blue-400 resize-none" placeholder="写下你的想法..."></textarea>
<div class="flex justify-end">
<button type="submit" class="bg-[#3B82F6] text-white px-6 py-2 rounded-full font-bold text-sm shadow-md shadow-blue-200 active:scale-95 transition-transform">
发送
</button>
</div>
</form>
</div>
</div>
<script>
// === 1. API 配置与 AppStorage ===
const USE_MOCK_DATA = false;
const API_BASE = 'https://happy.kudosd.icu/api/v1';
const DEBUG_MODE = false;
// 5+App 存储封装
const AppStorage = {
setItem: function(key, value) {
if (window.plus) {
plus.storage.setItem(key, String(value));
} else {
localStorage.setItem(key, value);
}
},
getItem: function(key) {
if (window.plus) {
return plus.storage.getItem(key);
} else {
return localStorage.getItem(key);
}
},
removeItem: function(key) {
if (window.plus) {
plus.storage.removeItem(key);
} else {
localStorage.removeItem(key);
}
},
clear: function() {
if (window.plus) {
plus.storage.clear();
} else {
localStorage.clear();
}
}
};
// === 新增:头像URL处理函数 ===
function getAvatarUrl(url) {
if (!url) return 'img/default_avatar.png';
if (url.startsWith('http') || url.startsWith('data:')) return url;
// 处理相对路径
const prefix = API_BASE.endsWith('/') ? API_BASE : (API_BASE + '/');
const cleanUrl = url.startsWith('/') ? url.substring(1) : url;
return prefix + cleanUrl;
}
// 统一请求封装
const request = async (endpoint, method = 'GET', data = null, optionalToken = null) => {
const token = optionalToken || AppStorage.getItem('token');
if (!token) {
if(confirm("您尚未登录,是否前往登录?")) {
window.location.href = 'index.html';
}
throw new Error("No token");
}
if (DEBUG_MODE) {
console.log(`>>> [Request] ${method} ${API_BASE}${endpoint}`);
if (data) console.log('>>> [Request Body]:', data);
}
return $.ajax({
url: `${API_BASE}${endpoint}`,
method: method,
contentType: 'application/json',
headers: { 'Authorization': `Bearer ${token}` },
data: data ? JSON.stringify(data) : undefined
}).then(response => {
if (DEBUG_MODE) {
try {
console.log(`<<< [Response Success] ${method} ${endpoint}`, JSON.stringify(response));
} catch(e) {
console.log(`<<< [Response Success] ${method} ${endpoint}`, response);
}
}
return response;
}).catch(err => {
if (DEBUG_MODE) {
console.error(`<<< [Response Error] ${method} ${endpoint}`, JSON.stringify(err));
}
handleCriticalError(err);
throw err;
});
};
function handleCriticalError(err) {
if (err.status === 401 || err.status === 422 || (err.responseJSON && err.responseJSON.msg === "Subject must be a string")) {
alert("登录状态已失效,请重新登录");
AppStorage.removeItem('token');
window.location.href = 'index.html';
}
}
// === 2. 页面逻辑 ===
let currentPostId = null;
let replyTargetId = null;
let currentUserInfo = null;
// 初始化
$(document).ready(function() {
if (window.lucide) lucide.createIcons();
if (window.plus) {
initPage();
} else {
document.addEventListener('plusready', function(){
initPage();
}, false);
const isApp = navigator.userAgent.indexOf("Html5Plus") > -1;
if (!isApp) {
initPage();
}
}
});
function initPage() {
const urlParams = new URLSearchParams(window.location.search);
currentPostId = urlParams.get('id');
if (!currentPostId && !USE_MOCK_DATA) {
alert("参数错误:缺少帖子ID");
history.back();
return;
}
if (!currentPostId) currentPostId = 1;
try {
const userStr = AppStorage.getItem('user_info');
if (userStr) {
currentUserInfo = JSON.parse(userStr);
}
} catch(e) { console.warn("Failed to parse user info"); }
loadUserProfile();
loadPostDetail(currentPostId);
loadComments(currentPostId);
}
async function loadUserProfile() {
try {
const res = await request('/auth/me');
if (res.data) {
const userData = res.data.user || res.data;
currentUserInfo = userData;
AppStorage.setItem('user_info', JSON.stringify(userData));
// 修复:处理头像URL
const avatarUrl = getAvatarUrl(userData.avatar_url);
$('#user-avatar').attr('src', avatarUrl);
}
} catch(e) { console.warn(e); }
}
// 加载帖子详情
async function loadPostDetail(id) {
try {
const res = await request(`/community/posts/${id}`);
const post = res.data;
const typeMap = {
'second_hand': { text: '二手', color: 'bg-[#FCD34D]' },
'rent': { text: '出租', color: 'bg-[#86EFAC]' },
'vote': { text: '投票', color: 'bg-[#F43F5E]' },
'lost_found': { text: '失物认领', color: 'bg-[#8B5CF6]' },
'complaint': { text: '投诉', color: 'bg-[#FF6B6B]' },
'discuss': { text: '讨论', color: 'bg-[#14B8A6]' },
'help': { text: '求助', color: 'bg-[#84CC16]' }
};
const typeInfo = typeMap[post.type] || { text: '帖子', color: 'bg-gray-400' };
let imagesHtml = '';
if (post.images && post.images.length > 0) {
// 图片URL如果是相对路径,可能也需要处理,这里假设图片服务是完整的URL或者无需特殊处理
// 如果需要统一处理,也可以封装类似 getAvatarUrl 的逻辑
imagesHtml = `<div class="mt-4 grid grid-cols-3 gap-2">
${post.images.map(img => `<img src="${img}" class="w-full h-24 object-cover rounded-lg bg-slate-100" onclick="plus.nativeUI.previewImage(['${img}'])">`).join('')}
</div>`;
}
let deleteBtnHtml = '';
if (currentUserInfo && currentUserInfo.id === post.owner_id) {
deleteBtnHtml = `
<div class="mt-8 pt-4 border-t border-slate-100">
<button onclick="deletePost(${post.id})" class="w-full py-3 rounded-xl bg-red-50 text-red-500 font-bold text-sm flex items-center justify-center gap-2 active:scale-[0.98] transition-transform hover:bg-red-100">
<i data-lucide="trash-2" width="18" height="18"></i>
删除帖子
</button>
</div>
`;
}
// 修复:处理作者头像
const authorAvatar = getAvatarUrl(post.author?.avatar_url || post.author?.avatar);
const html = `
<div class="bg-white rounded-[2rem] p-6 shadow-sm">
<div class="flex justify-between items-start mb-4">
<div class="flex items-center gap-3 flex-1 mr-2">
<div class="w-12 h-12 rounded-full overflow-hidden border border-slate-100 shrink-0">
<img src="${authorAvatar}" class="w-full h-full object-cover" alt="Author">
</div>
<div class="min-w-0">
<h3 class="font-bold text-slate-900 leading-tight">${post.title}</h3>
<div class="flex items-center gap-2 mt-1">
<p class="text-xs text-slate-500 font-medium">${post.author?.name || '匿名用户'}</p>
<p class="text-xs text-slate-400">${post.created_at ? post.created_at.split('T')[0] : '刚刚'}</p>
</div>
</div>
</div>
<span class="${typeInfo.color} text-white text-xs font-medium px-4 py-1.5 rounded-full shrink-0">
${typeInfo.text}
</span>
</div>
<div class="text-slate-700 text-sm leading-relaxed whitespace-pre-wrap font-medium">
${post.content}
</div>
${imagesHtml}
${deleteBtnHtml}
</div>
`;
$('#post-detail-container').html(html);
if (window.lucide) lucide.createIcons();
} catch (e) {
console.error("加载帖子失败", e);
$('#post-detail-container').html('<p class="text-center text-slate-400 mt-10">加载失败,请重试</p>');
}
}
window.deletePost = async function(postId) {
if(confirm('确定要删除这条帖子吗?此操作无法撤销。')) {
try {
const res = await request(`/community/posts/${postId}`, 'DELETE');
if(res.code === 200) {
alert('删除成功');
window.location.href = 'index.html#community';
} else {
alert(res.message || '删除失败');
}
} catch(e) { }
}
};
// 加载评论列表
async function loadComments(id) {
try {
const res = await request(`/community/posts/${id}/comments`);
const list = res.data.items || res.data.list || [];
const $container = $('#comments-container');
$container.empty();
if (list.length === 0) {
$container.html('<p class="text-center text-slate-400 text-xs mt-4">暂无评论,快来抢沙发~</p>');
return;
}
list.forEach(comment => {
let replyHtml = '';
if (comment.parent_id) {
replyHtml = `<span class="text-slate-400 text-xs mr-1">回复楼层</span>`;
}
// 修复:处理评论者头像
const commentAvatar = getAvatarUrl(comment.author?.avatar_url || comment.author?.avatar);
const html = `
<div onclick="replyTo(${comment.id}, '${comment.author?.name || '匿名'}')" class="bg-white rounded-[1.5rem] p-5 shadow-sm active:bg-gray-50 transition-colors cursor-pointer">
<div class="flex gap-3">
<div class="w-10 h-10 rounded-full overflow-hidden shrink-0 border border-slate-100">
<img src="${commentAvatar}" class="w-full h-full object-cover">
</div>
<div class="flex-1">
<div class="flex justify-between items-center mb-1">
<h4 class="text-sm font-bold text-slate-700">${comment.author?.name || '匿名用户'}</h4>
</div>
<p class="text-xs text-slate-400 mb-2">${comment.created_at ? comment.created_at.split('T')[0] : '刚刚'}</p>
<div class="text-slate-800 text-sm leading-normal">
${replyHtml}${comment.content}
</div>
</div>
</div>
</div>
`;
$container.append(html);
});
} catch (e) {
console.error("加载评论失败", e);
}
}
window.openCommentModal = function() {
$('#comment-modal').removeClass('hidden');
$('#comment-input').focus();
replyTargetId = null;
$('#comment-title').text('发表评论');
$('#comment-input').attr('placeholder', '写下你的想法...');
};
window.closeCommentModal = function() {
$('#comment-modal').addClass('hidden');
};
window.replyTo = function(commentId, userName) {
$('#comment-modal').removeClass('hidden');
replyTargetId = commentId;
$('#comment-title').text(`回复 ${userName}`);
$('#comment-input').attr('placeholder', `回复 ${userName}: `).focus();
};
$('#comment-form').submit(async function(e) {
e.preventDefault();
const content = $('#comment-input').val();
if(!content.trim()) return alert('请输入评论内容');
const payload = {
content: content,
parent_id: replyTargetId
};
try {
const res = await request(`/community/posts/${currentPostId}/comments`, 'POST', payload);
if(res.code === 200) {
alert('评论成功');
$('#comment-input').val('');
closeCommentModal();
loadComments(currentPostId);
} else {
alert(res.message || "评论失败");
}
} catch (e) {
alert("网络错误");
}
});
</script>
</body>
</html>