refactor: 移除开发日志并优化代码格式

fix(api): 添加头像前缀参数支持
This commit is contained in:
anghunk
2026-01-20 14:25:29 +08:00
parent 78e263faa4
commit 039411b142
5 changed files with 708 additions and 740 deletions

File diff suppressed because one or more lines are too long

View File

@@ -83,10 +83,9 @@ export class CWDComments {
adminEmail: data.adminEmail || '', adminEmail: data.adminEmail || '',
adminBadge: data.adminBadge || '', adminBadge: data.adminBadge || '',
adminEnabled: !!data.adminEnabled, adminEnabled: !!data.adminEnabled,
avatarPrefix: data.avatarPrefix || '' avatarPrefix: data.avatarPrefix || '',
}; };
} catch (e) { } catch (e) {
console.warn('[CWDComments] 加载服务端评论配置失败:', e);
return {}; return {};
} }
} }
@@ -137,11 +136,7 @@ export class CWDComments {
} }
const api = createApiClient(this.config); const api = createApiClient(this.config);
this.store = createCommentStore( this.store = createCommentStore(this.config, api.fetchComments.bind(api), api.submitComment.bind(api));
this.config,
api.fetchComments.bind(api),
api.submitComment.bind(api)
);
this.unsubscribe = this.store.store.subscribe((state) => { this.unsubscribe = this.store.store.subscribe((state) => {
this._onStateChange(state); this._onStateChange(state);
@@ -191,8 +186,6 @@ export class CWDComments {
this.mountPoint = null; this.mountPoint = null;
this.store = null; this.store = null;
this._mounted = false; this._mounted = false;
console.log('[CWDComments] 组件已卸载');
} }
/** /**
@@ -213,7 +206,7 @@ export class CWDComments {
formErrors: state.formErrors, formErrors: state.formErrors,
submitting: state.submitting, submitting: state.submitting,
onSubmit: () => this._handleSubmit(), onSubmit: () => this._handleSubmit(),
onFieldChange: (field, value) => this.store.updateFormField(field, value) onFieldChange: (field, value) => this.store.updateFormField(field, value),
}); });
this.commentForm.render(); this.commentForm.render();
} }
@@ -279,7 +272,7 @@ export class CWDComments {
onClearReplyError: () => this.store.clearReplyError(), onClearReplyError: () => this.store.clearReplyError(),
onPrevPage: () => this.store.goToPage(state.pagination.page - 1), onPrevPage: () => this.store.goToPage(state.pagination.page - 1),
onNextPage: () => this.store.goToPage(state.pagination.page + 1), onNextPage: () => this.store.goToPage(state.pagination.page + 1),
onGoToPage: (page) => this.store.goToPage(page) onGoToPage: (page) => this.store.goToPage(page),
}); });
this.commentList.render(); this.commentList.render();
} }
@@ -309,7 +302,7 @@ export class CWDComments {
this.commentForm.setProps({ this.commentForm.setProps({
form: state.form, form: state.form,
formErrors: state.formErrors, formErrors: state.formErrors,
submitting: state.submitting submitting: state.submitting,
}); });
} }
@@ -349,7 +342,7 @@ export class CWDComments {
replyingTo: state.replyingTo, replyingTo: state.replyingTo,
replyContent: state.replyContent, replyContent: state.replyContent,
replyError: state.replyError, replyError: state.replyError,
submitting: state.submitting submitting: state.submitting,
}); });
} }
} }
@@ -404,11 +397,7 @@ export class CWDComments {
this.unsubscribe(); this.unsubscribe();
} }
this.store = createCommentStore( this.store = createCommentStore(this.config, api.fetchComments.bind(api), api.submitComment.bind(api));
this.config,
api.fetchComments.bind(api),
api.submitComment.bind(api)
);
this.unsubscribe = this.store.store.subscribe((state) => { this.unsubscribe = this.store.store.subscribe((state) => {
this._onStateChange(state); this._onStateChange(state);
@@ -425,5 +414,4 @@ export class CWDComments {
getConfig() { getConfig() {
return { ...this.config }; return { ...this.config };
} }
} }

View File

@@ -25,14 +25,17 @@ export function createApiClient(config) {
post_slug: config.postSlug, post_slug: config.postSlug,
page: page.toString(), page: page.toString(),
limit: limit.toString(), limit: limit.toString(),
nested: 'true' nested: 'true',
}); });
if (config.avatarPrefix) {
params.set('avatar_prefix', config.avatarPrefix);
}
const response = await fetch(`${baseUrl}/api/comments?${params}`); const response = await fetch(`${baseUrl}/api/comments?${params}`);
if (!response.ok) { if (!response.ok) {
throw new Error(`获取评论失败: ${response.status} ${response.statusText}`); throw new Error(`获取评论失败: ${response.status} ${response.statusText}`);
} }
console.log('[API] fetchComments response:', response);
return response.json(); return response.json();
} }
@@ -50,7 +53,7 @@ export function createApiClient(config) {
const response = await fetch(`${baseUrl}/api/comments`, { const response = await fetch(`${baseUrl}/api/comments`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
post_slug: config.postSlug, post_slug: config.postSlug,
@@ -60,8 +63,8 @@ export function createApiClient(config) {
email: data.email, email: data.email,
url: data.url || undefined, url: data.url || undefined,
content: data.content, content: data.content,
parent_id: data.parentId parent_id: data.parentId,
}) }),
}); });
if (!response.ok) { if (!response.ok) {
@@ -72,6 +75,6 @@ export function createApiClient(config) {
return { return {
fetchComments, fetchComments,
submitComment submitComment,
}; };
} }

View File

@@ -17,12 +17,10 @@ function loadUserInfo() {
return { return {
name: parsed.name || '', name: parsed.name || '',
email: parsed.email || '', email: parsed.email || '',
url: parsed.url || '' url: parsed.url || '',
}; };
} }
} catch (e) { } catch (e) {}
console.error('读取用户信息失败:', e);
}
return { name: '', email: '', url: '' }; return { name: '', email: '', url: '' };
} }
@@ -36,9 +34,7 @@ function saveUserInfo(name, email, url) {
try { try {
const data = { name, email, url }; const data = { name, email, url };
localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
} catch (e) { } catch (e) {}
console.error('保存用户信息失败:', e);
}
} }
/** /**
@@ -67,7 +63,7 @@ class Store {
this.state = { ...this.state, ...updates }; this.state = { ...this.state, ...updates };
// 通知所有监听器 // 通知所有监听器
this.listeners.forEach(listener => { this.listeners.forEach((listener) => {
listener(this.state, prevState); listener(this.state, prevState);
}); });
} }
@@ -82,7 +78,7 @@ class Store {
// 返回取消订阅的函数 // 返回取消订阅的函数
return () => { return () => {
this.listeners = this.listeners.filter(l => l !== listener); this.listeners = this.listeners.filter((l) => l !== listener);
}; };
} }
} }
@@ -110,7 +106,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
page: 1, page: 1,
limit: config.pageSize || 20, limit: config.pageSize || 20,
total: 0, total: 0,
totalCount: 0 totalCount: 0,
}, },
// 表单数据 // 表单数据
@@ -118,7 +114,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
name: savedInfo.name || '', name: savedInfo.name || '',
email: savedInfo.email || '', email: savedInfo.email || '',
url: savedInfo.url || '', url: savedInfo.url || '',
content: '' content: '',
}, },
formErrors: {}, formErrors: {},
submitting: false, submitting: false,
@@ -126,7 +122,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
// 回复状态 // 回复状态
replyingTo: null, replyingTo: null,
replyContent: '', replyContent: '',
replyError: null replyError: null,
}); });
// 监听用户信息变化,自动保存到 localStorage // 监听用户信息变化,自动保存到 localStorage
@@ -143,27 +139,25 @@ export function createCommentStore(config, fetchComments, submitComment) {
async function loadComments(page = 1) { async function loadComments(page = 1) {
store.setState({ store.setState({
loading: true, loading: true,
error: null error: null,
}); });
try { try {
const response = await fetchComments(page, store.getState().pagination.limit); const response = await fetchComments(page, store.getState().pagination.limit);
console.log('[Store] loadComments response:', response);
console.log('[Store] comments data:', response.data);
store.setState({ store.setState({
comments: response.data, comments: response.data,
pagination: { pagination: {
page: response.pagination.page, page: response.pagination.page,
limit: response.pagination.limit, limit: response.pagination.limit,
total: response.pagination.total, total: response.pagination.total,
totalCount: response.pagination.totalCount totalCount: response.pagination.totalCount,
}, },
loading: false loading: false,
}); });
} catch (e) { } catch (e) {
store.setState({ store.setState({
error: e instanceof Error ? e.message : '加载评论失败', error: e instanceof Error ? e.message : '加载评论失败',
loading: false loading: false,
}); });
} }
} }
@@ -180,7 +174,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
const validation = validateCommentForm(form); const validation = validateCommentForm(form);
if (!validation.valid) { if (!validation.valid) {
store.setState({ store.setState({
formErrors: validation.errors formErrors: validation.errors,
}); });
return false; return false;
} }
@@ -189,7 +183,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
store.setState({ store.setState({
formErrors: {}, formErrors: {},
submitting: true, submitting: true,
error: null error: null,
}); });
try { try {
@@ -197,13 +191,13 @@ export function createCommentStore(config, fetchComments, submitComment) {
name: form.name, name: form.name,
email: form.email, email: form.email,
url: form.url, url: form.url,
content: form.content content: form.content,
}); });
// 清空评论内容 // 清空评论内容
store.setState({ store.setState({
form: { ...form, content: '' }, form: { ...form, content: '' },
submitting: false submitting: false,
}); });
// 重新加载评论 // 重新加载评论
@@ -212,7 +206,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
} catch (e) { } catch (e) {
store.setState({ store.setState({
error: e instanceof Error ? e.message : '提交评论失败', error: e instanceof Error ? e.message : '提交评论失败',
submitting: false submitting: false,
}); });
return false; return false;
} }
@@ -236,7 +230,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
if (!validation.valid) { if (!validation.valid) {
const errorMessages = Object.values(validation.errors).join(''); const errorMessages = Object.values(validation.errors).join('');
store.setState({ store.setState({
replyError: errorMessages replyError: errorMessages,
}); });
return false; return false;
} }
@@ -244,7 +238,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
store.setState({ store.setState({
formErrors: {}, formErrors: {},
submitting: true, submitting: true,
replyError: null replyError: null,
}); });
try { try {
@@ -253,14 +247,14 @@ export function createCommentStore(config, fetchComments, submitComment) {
email: state.form.email, email: state.form.email,
url: state.form.url, url: state.form.url,
content: state.replyContent, content: state.replyContent,
parentId parentId,
}); });
// 清空回复内容并关闭回复框 // 清空回复内容并关闭回复框
store.setState({ store.setState({
replyContent: '', replyContent: '',
replyingTo: null, replyingTo: null,
submitting: false submitting: false,
}); });
// 重新加载评论 // 重新加载评论
@@ -269,7 +263,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
} catch (e) { } catch (e) {
store.setState({ store.setState({
error: e instanceof Error ? e.message : '提交回复失败', error: e instanceof Error ? e.message : '提交回复失败',
submitting: false submitting: false,
}); });
return false; return false;
} }
@@ -280,13 +274,11 @@ export function createCommentStore(config, fetchComments, submitComment) {
* @param {number} commentId - 评论 ID * @param {number} commentId - 评论 ID
*/ */
function startReply(commentId) { function startReply(commentId) {
console.log('[Store] startReply called with commentId:', commentId);
store.setState({ store.setState({
replyingTo: commentId, replyingTo: commentId,
replyContent: '', replyContent: '',
replyError: null replyError: null,
}); });
console.log('[Store] New state:', store.getState());
} }
/** /**
@@ -296,7 +288,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
store.setState({ store.setState({
replyingTo: null, replyingTo: null,
replyContent: '', replyContent: '',
replyError: null replyError: null,
}); });
} }
@@ -317,7 +309,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
*/ */
function updateReplyContent(content) { function updateReplyContent(content) {
store.setState({ store.setState({
replyContent: content replyContent: content,
}); });
} }
@@ -326,7 +318,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
*/ */
function clearReplyError() { function clearReplyError() {
store.setState({ store.setState({
replyError: null replyError: null,
}); });
} }
@@ -335,7 +327,7 @@ export function createCommentStore(config, fetchComments, submitComment) {
*/ */
function clearError() { function clearError() {
store.setState({ store.setState({
error: null error: null,
}); });
} }
@@ -370,6 +362,6 @@ export function createCommentStore(config, fetchComments, submitComment) {
updateReplyContent, updateReplyContent,
clearReplyError, clearReplyError,
clearError, clearError,
goToPage goToPage,
}; };
} }

View File

@@ -25,9 +25,7 @@ function loadConfigFromStorage() {
if (saved) { if (saved) {
return { ...DEFAULT_CONFIG, ...JSON.parse(saved) }; return { ...DEFAULT_CONFIG, ...JSON.parse(saved) };
} }
} catch (e) { } catch (e) {}
console.warn('[CWDComments] 读取本地存储失败:', e);
}
return DEFAULT_CONFIG; return DEFAULT_CONFIG;
} }
@@ -37,9 +35,7 @@ function loadConfigFromStorage() {
function saveConfigToStorage(config) { function saveConfigToStorage(config) {
try { try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(config)); localStorage.setItem(STORAGE_KEY, JSON.stringify(config));
} catch (e) { } catch (e) {}
console.warn('[CWDComments] 保存到本地存储失败:', e);
}
} }
/** /**
@@ -94,10 +90,7 @@ async function initWidget() {
pageSize: 20, pageSize: 20,
}); });
widgetInstance.mount(); widgetInstance.mount();
console.log('[CWDComments] Widget 初始化成功', config); } catch (error) {}
} catch (error) {
console.error('[CWDComments] Widget 初始化失败:', error);
}
} }
/** /**
@@ -105,7 +98,6 @@ async function initWidget() {
*/ */
function toggleTheme() { function toggleTheme() {
if (!widgetInstance) { if (!widgetInstance) {
console.warn('[CWDComments] 请先初始化 widget');
return; return;
} }
@@ -123,8 +115,6 @@ function toggleTheme() {
const config = getConfigFromInputs(); const config = getConfigFromInputs();
config.theme = newTheme; config.theme = newTheme;
saveConfigToStorage(config); saveConfigToStorage(config);
console.log('[CWDComments] 主题已切换为:', newTheme);
} }
/** /**
@@ -134,10 +124,7 @@ function clearConfig() {
try { try {
localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(STORAGE_KEY);
populateInputs(DEFAULT_CONFIG); populateInputs(DEFAULT_CONFIG);
console.log('[CWDComments] 配置已重置为默认值'); } catch (e) {}
} catch (e) {
console.error('[CWDComments] 重置配置失败:', e);
}
} }
// 将函数挂载到 window 对象,使其在 HTML 中可访问 // 将函数挂载到 window 对象,使其在 HTML 中可访问
@@ -147,8 +134,6 @@ window.clearConfig = clearConfig;
// 页面加载完成后自动初始化 // 页面加载完成后自动初始化
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
console.log('[CWDComments] 开发模式 - 页面加载完成,正在初始化...');
// 从本地存储加载配置并填充到输入框 // 从本地存储加载配置并填充到输入框
const savedConfig = loadConfigFromStorage(); const savedConfig = loadConfigFromStorage();
populateInputs(savedConfig); populateInputs(savedConfig);