diff --git a/memento-note/components/rich-text-editor.tsx b/memento-note/components/rich-text-editor.tsx index 024f5bf..67163ee 100644 --- a/memento-note/components/rich-text-editor.tsx +++ b/memento-note/components/rich-text-editor.tsx @@ -297,7 +297,7 @@ export const RichTextEditor = forwardRef() + +function getCacheKey(content: string, selection: string | null | undefined): string { + // Use content hash + selection as cache key + const textToHash = selection ? content + ':::' + selection : content + // Simple hash function + let hash = 0 + for (let i = 0; i < textToHash.length; i++) { + hash = ((hash << 5) - hash) + textToHash.charCodeAt(i) + hash = hash & hash // Convert to 32bit integer + } + return String(hash) +} + +function getCached(key: string): SuggestChartsResponse | null { + const entry = cache.get(key) + if (!entry) return null + if (Date.now() - entry.timestamp > CACHE_TTL) { + cache.delete(key) + return null + } + console.log('[chart-suggestion] Cache hit for key:', key) + return entry.data +} + +function setCached(key: string, data: SuggestChartsResponse): void { + cache.set(key, { data, timestamp: Date.now() }) + // Limit cache size to 50 entries + if (cache.size > 50) { + const firstKey = cache.keys().next().value + cache.delete(firstKey) + } +} + /** * Call the AI chart suggestions API * @param request - The request parameters * @returns Promise with the chart suggestions */ export async function suggestCharts(request: SuggestChartsRequest): Promise { + // Check cache first + const cacheKey = getCacheKey(request.content || '', request.selection) + const cached = getCached(cacheKey) + if (cached) { + return cached + } + try { const response = await fetch('/api/ai/suggest-charts', { method: 'POST', @@ -56,8 +99,14 @@ export async function suggestCharts(request: SuggestChartsRequest): Promise