Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,401 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// 本地存储键名
|
||||
const STORAGE_KEY = 'imageGenerationHistory';
|
||||
// 最大历史记录条数
|
||||
const MAX_HISTORY_ITEMS = 50;
|
||||
|
||||
/**
|
||||
* 图像生成历史记录管理钩子
|
||||
* @param {number} maxItems 最大历史记录条数
|
||||
* @returns {Object} 历史记录相关状态和方法
|
||||
*/
|
||||
const useImageHistory = (maxItems = MAX_HISTORY_ITEMS) => {
|
||||
const { t: _t } = useTranslation();
|
||||
|
||||
// 状态管理
|
||||
const [history, setHistory] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// 从本地存储加载历史记录
|
||||
const loadHistory = useCallback(() => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const savedHistory = localStorage.getItem(STORAGE_KEY);
|
||||
if (savedHistory) {
|
||||
const parsedHistory = JSON.parse(savedHistory);
|
||||
// 确保是数组格式
|
||||
if (Array.isArray(parsedHistory)) {
|
||||
setHistory(parsedHistory);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load history from localStorage:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 保存历史记录到本地存储
|
||||
const saveHistory = useCallback((historyData) => {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(historyData));
|
||||
} catch (error) {
|
||||
console.error('Failed to save history to localStorage:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 初始化时加载历史记录
|
||||
useEffect(() => {
|
||||
loadHistory();
|
||||
}, [loadHistory]);
|
||||
|
||||
/**
|
||||
* 添加新的生成记录
|
||||
* @param {Object} record 生成记录
|
||||
* @param {string} record.model 使用的模型
|
||||
* @param {string} record.prompt 使用的提示词
|
||||
* @param {string} record.negativePrompt 使用的反向提示词
|
||||
* @param {string} record.size 图片尺寸
|
||||
* @param {string} record.quality 图片质量
|
||||
* @param {Array} record.images 生成的图片数组
|
||||
*/
|
||||
const addHistoryRecord = useCallback(
|
||||
(record) => {
|
||||
if (
|
||||
!record ||
|
||||
!record.prompt ||
|
||||
!record.images ||
|
||||
!Array.isArray(record.images)
|
||||
) {
|
||||
console.error('Invalid history record:', record);
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建完整的记录对象
|
||||
const newRecord = {
|
||||
id: Date.now().toString(), // 使用时间戳作为唯一ID
|
||||
timestamp: new Date().toISOString(),
|
||||
model: record.model || '',
|
||||
prompt: record.prompt,
|
||||
negativePrompt: record.negativePrompt || '',
|
||||
size: record.size || '',
|
||||
quality: record.quality || 'standard',
|
||||
style: record.style || 'natural',
|
||||
images: record.images,
|
||||
};
|
||||
|
||||
setHistory((prev) => {
|
||||
// 添加新记录到开头,并限制最大数量
|
||||
const updatedHistory = [newRecord, ...prev].slice(0, maxItems);
|
||||
// 保存到本地存储
|
||||
saveHistory(updatedHistory);
|
||||
return updatedHistory;
|
||||
});
|
||||
},
|
||||
[maxItems, saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 删除单条历史记录
|
||||
* @param {string} recordId 记录ID
|
||||
*/
|
||||
const deleteHistoryRecord = useCallback(
|
||||
(recordId) => {
|
||||
setHistory((prev) => {
|
||||
const updatedHistory = prev.filter((item) => item.id !== recordId);
|
||||
// 保存到本地存储
|
||||
saveHistory(updatedHistory);
|
||||
return updatedHistory;
|
||||
});
|
||||
},
|
||||
[saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 清空所有历史记录
|
||||
*/
|
||||
const clearAllHistory = useCallback(() => {
|
||||
setHistory([]);
|
||||
// 从本地存储中删除
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error('Failed to clear history from localStorage:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 根据ID获取历史记录
|
||||
* @param {string} recordId 记录ID
|
||||
* @returns {Object|null} 历史记录对象
|
||||
*/
|
||||
const getHistoryRecordById = useCallback(
|
||||
(recordId) => {
|
||||
return history.find((item) => item.id === recordId) || null;
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 从历史记录中加载参数
|
||||
* @param {string} recordId 记录ID
|
||||
* @returns {Object|null} 生成参数对象
|
||||
*/
|
||||
const loadParamsFromHistory = useCallback(
|
||||
(recordId) => {
|
||||
const record = getHistoryRecordById(recordId);
|
||||
if (!record) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
model: record.model,
|
||||
prompt: record.prompt,
|
||||
negativePrompt: record.negativePrompt,
|
||||
size: record.size,
|
||||
quality: record.quality,
|
||||
style: record.style,
|
||||
images: record.images,
|
||||
};
|
||||
},
|
||||
[getHistoryRecordById],
|
||||
);
|
||||
|
||||
/**
|
||||
* 搜索历史记录
|
||||
* @param {string} keyword 搜索关键词
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const searchHistory = useCallback(
|
||||
(keyword) => {
|
||||
if (!keyword || !keyword.trim()) {
|
||||
return history;
|
||||
}
|
||||
|
||||
const searchTerm = keyword.toLowerCase().trim();
|
||||
return history.filter(
|
||||
(item) =>
|
||||
item.prompt.toLowerCase().includes(searchTerm) ||
|
||||
(item.negativePrompt &&
|
||||
item.negativePrompt.toLowerCase().includes(searchTerm)) ||
|
||||
item.model.toLowerCase().includes(searchTerm),
|
||||
);
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 按时间范围过滤历史记录
|
||||
* @param {Date} startDate 开始时间
|
||||
* @param {Date} endDate 结束时间
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const filterHistoryByDate = useCallback(
|
||||
(startDate, endDate) => {
|
||||
if (!startDate && !endDate) {
|
||||
return history;
|
||||
}
|
||||
|
||||
return history.filter((item) => {
|
||||
const itemDate = new Date(item.timestamp);
|
||||
|
||||
if (startDate && itemDate < startDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (endDate && itemDate > endDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 按模型过滤历史记录
|
||||
* @param {string} modelName 模型名称
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const filterHistoryByModel = useCallback(
|
||||
(modelName) => {
|
||||
if (!modelName || !modelName.trim()) {
|
||||
return history;
|
||||
}
|
||||
|
||||
return history.filter((item) => item.model === modelName);
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 导出历史记录为JSON
|
||||
* @returns {string} JSON格式的历史记录
|
||||
*/
|
||||
const exportHistory = useCallback(() => {
|
||||
return JSON.stringify(history, null, 2);
|
||||
}, [history]);
|
||||
|
||||
/**
|
||||
* 导入历史记录
|
||||
* @param {string} jsonData JSON格式的历史记录数据
|
||||
* @returns {boolean} 是否导入成功
|
||||
*/
|
||||
const importHistory = useCallback(
|
||||
(jsonData) => {
|
||||
try {
|
||||
const importedData = JSON.parse(jsonData);
|
||||
|
||||
// 验证导入的数据格式
|
||||
if (!Array.isArray(importedData)) {
|
||||
throw new Error('Invalid history data format');
|
||||
}
|
||||
|
||||
// 验证每条记录的格式
|
||||
const validRecords = importedData.filter(
|
||||
(record) =>
|
||||
record.id &&
|
||||
record.timestamp &&
|
||||
record.prompt &&
|
||||
Array.isArray(record.images),
|
||||
);
|
||||
|
||||
if (validRecords.length === 0) {
|
||||
throw new Error('No valid history records found');
|
||||
}
|
||||
|
||||
// 合并现有历史记录,避免重复,并限制最大数量
|
||||
const combinedRecords = [...validRecords, ...history];
|
||||
|
||||
// 去重(基于ID)
|
||||
const uniqueRecords = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const record of combinedRecords) {
|
||||
if (!seenIds.has(record.id)) {
|
||||
seenIds.add(record.id);
|
||||
uniqueRecords.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
// 按时间戳排序(最新的在前)
|
||||
uniqueRecords.sort(
|
||||
(a, b) => new Date(b.timestamp) - new Date(a.timestamp),
|
||||
);
|
||||
|
||||
// 限制最大数量
|
||||
const finalRecords = uniqueRecords.slice(0, maxItems);
|
||||
|
||||
// 更新状态并保存
|
||||
setHistory(finalRecords);
|
||||
saveHistory(finalRecords);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to import history:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[history, maxItems, saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取最近使用的提示词列表
|
||||
* @param {number} limit 最大返回数量
|
||||
* @returns {Array} 提示词数组
|
||||
*/
|
||||
const getRecentPrompts = useCallback(
|
||||
(limit = 10) => {
|
||||
const prompts = [];
|
||||
const seenPrompts = new Set();
|
||||
|
||||
for (const item of history) {
|
||||
if (item.prompt && !seenPrompts.has(item.prompt)) {
|
||||
seenPrompts.add(item.prompt);
|
||||
prompts.push(item.prompt);
|
||||
|
||||
if (prompts.length >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return prompts;
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取历史记录统计信息
|
||||
* @returns {Object} 统计信息
|
||||
*/
|
||||
const getHistoryStats = useCallback(() => {
|
||||
const stats = {
|
||||
totalRecords: history.length,
|
||||
models: {},
|
||||
sizes: {},
|
||||
recentActivity:
|
||||
history.length > 0 ? new Date(history[0].timestamp) : null,
|
||||
};
|
||||
|
||||
// 统计各模型和尺寸的使用次数
|
||||
history.forEach((item) => {
|
||||
// 模型统计
|
||||
if (item.model) {
|
||||
stats.models[item.model] = (stats.models[item.model] || 0) + 1;
|
||||
}
|
||||
|
||||
// 尺寸统计
|
||||
if (item.size) {
|
||||
stats.sizes[item.size] = (stats.sizes[item.size] || 0) + 1;
|
||||
}
|
||||
});
|
||||
|
||||
return stats;
|
||||
}, [history]);
|
||||
|
||||
return {
|
||||
// 状态
|
||||
history,
|
||||
isLoading,
|
||||
|
||||
// 操作方法
|
||||
addHistoryRecord,
|
||||
deleteHistoryRecord,
|
||||
clearAllHistory,
|
||||
getHistoryRecordById,
|
||||
loadParamsFromHistory,
|
||||
searchHistory,
|
||||
filterHistoryByDate,
|
||||
filterHistoryByModel,
|
||||
exportHistory,
|
||||
importHistory,
|
||||
getRecentPrompts,
|
||||
getHistoryStats,
|
||||
loadHistory,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageHistory;
|
||||
Reference in New Issue
Block a user