51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
const STAR_KEY = 'jinrong.analyst.starredQuestions'
|
|||
|
|
const RECENT_KEY = 'jinrong.analyst.recentQuestions'
|
||
|
|
const MAX_RECENT = 8
|
||
|
|
|
||
|
|
export type RecentQuestion = { question: string; at: number }
|
||
|
|
|
||
|
|
function readJson<T>(key: string, fallback: T): T {
|
||
|
|
try {
|
||
|
|
const raw = localStorage.getItem(key)
|
||
|
|
if (!raw) return fallback
|
||
|
|
return JSON.parse(raw) as T
|
||
|
|
} catch {
|
||
|
|
return fallback
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export function loadStarredQuestions(): string[] {
|
||
|
|
const list = readJson<string[]>(STAR_KEY, [])
|
||
|
|
return Array.isArray(list) ? list : []
|
||
|
|
}
|
||
|
|
|
||
|
|
export function saveStarredQuestions(questions: string[]): void {
|
||
|
|
localStorage.setItem(STAR_KEY, JSON.stringify(questions.slice(0, 30)))
|
||
|
|
}
|
||
|
|
|
||
|
|
export function toggleStarredQuestion(question: string): string[] {
|
||
|
|
const q = question.trim()
|
||
|
|
if (!q) return loadStarredQuestions()
|
||
|
|
const set = new Set(loadStarredQuestions())
|
||
|
|
if (set.has(q)) set.delete(q)
|
||
|
|
else set.add(q)
|
||
|
|
const next = [...set]
|
||
|
|
saveStarredQuestions(next)
|
||
|
|
return next
|
||
|
|
}
|
||
|
|
|
||
|
|
export function loadRecentQuestions(): RecentQuestion[] {
|
||
|
|
const list = readJson<RecentQuestion[]>(RECENT_KEY, [])
|
||
|
|
return Array.isArray(list) ? list : []
|
||
|
|
}
|
||
|
|
|
||
|
|
export function pushRecentQuestion(question: string): RecentQuestion[] {
|
||
|
|
const q = question.trim()
|
||
|
|
if (!q) return loadRecentQuestions()
|
||
|
|
const now = Date.now()
|
||
|
|
const rest = loadRecentQuestions().filter((r) => r.question !== q)
|
||
|
|
const next = [{ question: q, at: now }, ...rest].slice(0, MAX_RECENT)
|
||
|
|
localStorage.setItem(RECENT_KEY, JSON.stringify(next))
|
||
|
|
return next
|
||
|
|
}
|