51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
/**
|
||
* 思考页搜索历史:对齐 PC blog_search_history,最多 10 条。
|
||
* 小程序用 uni.setStorageSync,与 localStorage key 保持一致便于跨端对齐。
|
||
*/
|
||
export const SEARCH_HISTORY_KEY = 'blog_search_history'
|
||
const MAX_HISTORY = 10
|
||
|
||
export function useSearchHistory() {
|
||
/** 读取历史列表 */
|
||
const readHistory = (): string[] => {
|
||
try {
|
||
const raw = uni.getStorageSync(SEARCH_HISTORY_KEY)
|
||
if (!raw) return []
|
||
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
|
||
return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === 'string') : []
|
||
}
|
||
catch {
|
||
return []
|
||
}
|
||
}
|
||
|
||
const writeHistory = (items: string[]) => {
|
||
uni.setStorageSync(SEARCH_HISTORY_KEY, JSON.stringify(items.slice(0, MAX_HISTORY)))
|
||
}
|
||
|
||
const getHistory = () => readHistory()
|
||
|
||
/** 写入关键词(去重置顶) */
|
||
const addHistory = (keyword: string) => {
|
||
const trimmed = keyword.trim()
|
||
if (!trimmed) return
|
||
const next = [trimmed, ...readHistory().filter(item => item !== trimmed)].slice(0, MAX_HISTORY)
|
||
writeHistory(next)
|
||
}
|
||
|
||
const removeHistory = (keyword: string) => {
|
||
writeHistory(readHistory().filter(item => item !== keyword))
|
||
}
|
||
|
||
const clearHistory = () => {
|
||
uni.removeStorageSync(SEARCH_HISTORY_KEY)
|
||
}
|
||
|
||
return {
|
||
getHistory,
|
||
addHistory,
|
||
removeHistory,
|
||
clearHistory,
|
||
}
|
||
}
|