WEB.BUILDING.GENIOUS / hooks /use-chat-history.ts
Humbl3m33's picture
Rename use-chat-history.ts to hooks/use-chat-history.ts
c6276fe verified
"use client"
import { useCallback } from "react"
import { useToast } from "@/hooks/use-toast"
export function useChatHistory() {
const { toast } = useToast()
const exportHistory = useCallback(async () => {
try {
const response = await fetch("/api/export/json")
const data = await response.json()
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: "application/json",
})
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = `chat-history-${new Date().toISOString().split("T")[0]}.json`
a.click()
URL.revokeObjectURL(url)
toast({
title: "Export successful",
description: "Chat history exported to JSON file",
})
} catch (error) {
toast({
title: "Export failed",
description: "Could not export chat history",
variant: "destructive",
})
}
}, [toast])
const exportHTML = useCallback(async () => {
try {
const response = await fetch("/api/export/html")
const blob = await response.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = `chat-export-${new Date().toISOString().split("T")[0]}.html`
a.click()
URL.revokeObjectURL(url)
toast({
title: "HTML export successful",
description: "Chat history exported to HTML file",
})
} catch (error) {
toast({
title: "Export failed",
description: "Could not export to HTML",
variant: "destructive",
})
}
}, [toast])
const importHistory = useCallback(() => {
const input = document.createElement("input")
input.type = "file"
input.accept = ".json"
input.onchange = async (e) => {
const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
try {
const text = await file.text()
const data = JSON.parse(text)
const response = await fetch("/api/import", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
})
if (response.ok) {
toast({
title: "Import successful",
description: "Chat history imported successfully",
})
window.location.reload() // Refresh to show imported data
} else {
throw new Error("Import failed")
}
} catch (error) {
toast({
title: "Import failed",
description: "Could not import chat history",
variant: "destructive",
})
}
}
input.click()
}, [toast])
return {
exportHistory,
exportHTML,
importHistory,
}
}