-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommunity_create.html
More file actions
436 lines (387 loc) · 18.2 KB
/
community_create.html
File metadata and controls
436 lines (387 loc) · 18.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
<!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); } }
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
background-repeat: no-repeat;
background-position: right 0.5rem center;
background-size: 1.2em;
}
</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">
<div id="debug-tool" class="hidden mb-4 p-2 bg-red-100 text-red-600 rounded text-xs">
检测到Token可能无效。
<button onclick="clearToken()" class="underline font-bold ml-2">清除缓存并重新登录</button>
</div>
<form id="create-post-form" class="space-y-6">
<div class="border-b border-slate-200 pb-2">
<input type="text" id="post-title"
class="w-full bg-transparent text-lg font-bold text-slate-900 placeholder-slate-400 outline-none"
placeholder="请输入标题 (例如: 99新 捷安特公路车)" required>
</div>
<div>
<textarea id="post-content" rows="8"
class="w-full bg-transparent text-sm text-slate-600 leading-relaxed placeholder-slate-400 outline-none resize-none"
placeholder="详细描述您的物品或需求..." required></textarea>
</div>
<div class="flex gap-4 flex-wrap" id="image-upload-container">
<div onclick="selectImages()" class="w-24 h-24 bg-[#D1D5DB] rounded-[1.5rem] flex items-center justify-center text-slate-700 cursor-pointer active:scale-95 transition-transform shrink-0">
<i data-lucide="plus" width="32" height="32"></i>
<input type="file" id="image-input" class="hidden" accept="image/*" multiple>
</div>
</div>
<div class="flex items-center justify-between pt-4">
<span class="text-base font-bold text-slate-800">帖子分类</span>
<div class="relative">
<select id="post-type" class="appearance-none bg-[#FCD34D] text-slate-900 font-bold text-sm py-2 pl-6 pr-10 rounded-full focus:outline-none focus:ring-2 focus:ring-yellow-300 transition-shadow cursor-pointer">
<option value="second_hand">二手闲置</option>
<option value="rent">房屋出租</option>
<option value="lost_found">失物认领</option>
<option value="help">邻里求助</option>
<option value="discuss">社区讨论</option>
<option value="vote">投票表决</option>
</select>
</div>
</div>
<div class="pt-8">
<button type="submit" id="submit-btn" class="w-full bg-[#15549e] text-white text-lg font-bold py-4 rounded-full shadow-lg shadow-blue-900/20 active:scale-[0.98] transition-transform flex justify-center items-center gap-2">
<span>确认发布</span>
</button>
</div>
</form>
</main>
<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>
<script>
// === 1. API 配置 ===
const API_BASE = 'https://happy.kudosd.icu/api/v1';
let uploadedImages = []; // 全局存储上传成功的图片URL
// === 2. AppStorage 封装 ===
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;
}
// 辅助功能:清除Token
window.clearToken = function() {
AppStorage.removeItem('token');
AppStorage.removeItem('user_info');
alert('缓存已清除,请前往登录页');
window.location.href = 'index.html';
}
// 统一请求封装
const request = async (endpoint, method = 'GET', data = null) => {
const token = AppStorage.getItem('token');
if (!token) {
if(confirm("您尚未登录,是否前往登录?")) {
window.location.href = 'index.html';
}
throw new Error("No token");
}
const headers = { 'Authorization': `Bearer ${token}` };
let body = data;
let processData = true;
let contentType = 'application/json';
if (data instanceof FormData) {
processData = false;
contentType = false;
body = data;
} else if (data) {
body = JSON.stringify(data);
}
return new Promise((resolve, reject) => {
$.ajax({
url: `${API_BASE}${endpoint}`,
method: method,
headers: headers,
data: body,
processData: processData,
contentType: contentType,
success: function(res) {
resolve(res);
},
error: function(xhr, status, error) {
console.error("API Error Detail:", xhr.responseText);
handleCriticalError(xhr);
reject({ status: xhr.status, message: "Request failed" });
}
});
});
};
function handleCriticalError(xhr) {
let isAuthError = false;
let errorMsg = "网络请求失败";
if (xhr.status === 401 || xhr.status === 422) {
isAuthError = true;
}
try {
const errRes = JSON.parse(xhr.responseText);
if (errRes.msg === "Subject must be a string") {
isAuthError = true;
errorMsg = "登录状态已失效 (Token格式错误)";
} else {
errorMsg = errRes.message || errRes.msg || errorMsg;
}
} catch(e) {}
if (isAuthError) {
$('#debug-tool').removeClass('hidden');
alert(errorMsg + ",请重新登录");
clearToken();
}
}
// === 3. 页面初始化 ===
$(document).ready(function() {
if (window.lucide) lucide.createIcons();
const initPage = () => {
const token = AppStorage.getItem('token');
if (token === 'demo_token') {
console.warn("检测到无效的测试Token,正在清理...");
AppStorage.removeItem('token');
}
loadUserProfile();
bindEvents();
};
if (window.plus) {
initPage();
} else {
document.addEventListener('plusready', function(){
initPage();
}, false);
const isApp = navigator.userAgent.indexOf("Html5Plus") > -1;
if (!isApp) {
initPage();
}
}
});
// 绑定全局函数
window.selectImages = function() {
if (window.plus) {
plus.gallery.pick(function(e){
for(var i in e.files){
var path = e.files[i];
handleUpload(path, true);
}
}, function(e){
console.log("取消选择: " + e.message);
},{
filter: "image",
multiple: true,
system: false
});
} else {
$('#image-input').click();
}
};
async function loadUserProfile() {
try {
const res = await request('/auth/me');
const user = res.data.user || res.data;
// 修复:处理头像
const avatarUrl = getAvatarUrl(user ? user.avatar_url : null);
$('#user-avatar').attr('src', avatarUrl);
} catch(e) {
console.log("加载用户信息失败或未登录");
}
}
// === 4. 上传与提交逻辑 ===
function handleUpload(fileOrPath, isNative = false) {
const $uploadBtn = $('#image-input').parent();
const loadingId = 'loading-' + Date.now() + Math.random().toString(36).substr(2, 5);
const loadingHtml = `
<div id="${loadingId}" class="w-24 h-24 rounded-[1.5rem] bg-slate-100 flex items-center justify-center border border-slate-200 shrink-0">
<i data-lucide="loader-2" class="animate-spin text-slate-400"></i>
</div>
`;
$(loadingHtml).insertBefore($uploadBtn);
if (window.lucide) lucide.createIcons();
const token = AppStorage.getItem('token');
if (isNative && window.plus) {
var task = plus.uploader.createUpload(API_BASE + "/upload",
{ method: "POST", blocksize: 204800, priority: 100 },
function (t, status) {
if (status == 200) {
try {
var res = JSON.parse(t.responseText);
if (res.code === 200) {
onUploadSuccess(loadingId, res.data.file_url);
} else {
onUploadFail(loadingId, res.message || "后端返回错误");
}
} catch(e) {
onUploadFail(loadingId, "JSON解析失败");
}
} else {
onUploadFail(loadingId, "网络错误: " + status);
}
}
);
task.addFile(fileOrPath, {key: "file"});
task.addData("module", "community");
task.setRequestHeader('Authorization', 'Bearer ' + token);
task.start();
} else {
const formData = new FormData();
formData.append('file', fileOrPath);
formData.append('module', 'community');
request('/upload', 'POST', formData)
.then(res => {
if (res.code === 200) {
onUploadSuccess(loadingId, res.data.file_url);
} else {
onUploadFail(loadingId, res.message);
}
})
.catch(err => {
onUploadFail(loadingId, err.message);
});
}
}
function onUploadSuccess(elementId, imageUrl) {
uploadedImages.push(imageUrl);
const $el = $('#' + elementId);
$el.replaceWith(`
<div class="w-24 h-24 rounded-[1.5rem] overflow-hidden relative shadow-sm group shrink-0">
<img src="${imageUrl}" class="w-full h-full object-cover">
<div class="absolute inset-0 bg-black/20 hidden group-hover:flex items-center justify-center">
<i data-lucide="check" class="text-white"></i>
</div>
</div>
`);
if (window.lucide) lucide.createIcons();
}
function onUploadFail(elementId, msg) {
const $el = $('#' + elementId);
$el.html('<i data-lucide="alert-circle" class="text-red-400"></i>');
$el.addClass('border-red-200 bg-red-50');
$el.click(() => alert("上传失败: " + msg));
if (window.lucide) lucide.createIcons();
}
function bindEvents() {
$('#image-input').change(function(e) {
const files = e.target.files;
if (!files || files.length === 0) return;
for (let i = 0; i < files.length; i++) {
handleUpload(files[i], false);
}
$(this).val('');
});
$('#create-post-form').submit(async function(e) {
e.preventDefault();
const title = $('#post-title').val();
const content = $('#post-content').val();
const type = $('#post-type').val();
const $btn = $('#submit-btn');
if (!title || !content) {
alert('请填写标题和内容');
return;
}
$btn.prop('disabled', true).html('<i data-lucide="loader-2" class="animate-spin mr-2"></i> 发布中...');
if (window.lucide) lucide.createIcons();
const payload = {
title: title,
content: content,
type: type,
images: uploadedImages
};
try {
const res = await request('/community/posts', 'POST', payload);
if (res.code === 200) {
alert('发布成功!');
window.location.href = 'index.html#community';
} else {
alert(res.message || '发布失败');
}
} catch (err) {
console.error("提交中止:", err);
} finally {
$btn.prop('disabled', false).html('<span>确认发布</span>');
if (window.lucide) lucide.createIcons();
}
});
}
</script>
</body>
</html>