file.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { useState, useMemo, useEffect } from "react";
  2. import { initDB } from "react-indexed-db-hook";
  3. import { StoreKey } from "@/app/constant";
  4. import { useIndexedDB } from "react-indexed-db-hook";
  5. export const FileDbConfig = {
  6. name: "@chatgpt-next-web/file",
  7. version: 1,
  8. objectStoresMeta: [
  9. {
  10. store: StoreKey.File,
  11. storeConfig: { keyPath: "id", autoIncrement: true },
  12. storeSchema: [
  13. { name: "data", keypath: "data", options: { unique: false } },
  14. {
  15. name: "created_at",
  16. keypath: "created_at",
  17. options: { unique: false },
  18. },
  19. ],
  20. },
  21. ],
  22. };
  23. export function FileDbInit() {
  24. if (typeof window !== "undefined") {
  25. initDB(FileDbConfig);
  26. }
  27. }
  28. export function useFileDB() {
  29. return useIndexedDB(StoreKey.File);
  30. }
  31. export function saveFileData(db, fileId, data) {
  32. // save file content and return url start with `indexeddb://`
  33. db.add({ id: fileId, data });
  34. return `indexeddb://${StoreKey.File}@${fileId}`;
  35. }
  36. export async function getFileData(db, fileId, contentType = "image/png") {
  37. const { data } = await db.getByID(fileId);
  38. return `data:${contentType};base64,${data}`;
  39. }
  40. export function IndexDBImage({ src, alt, onClick, db, className }) {
  41. const [data, setData] = useState(src);
  42. const imgId = useMemo(
  43. () => src.replace("indexeddb://", "").split("@").pop(),
  44. [src],
  45. );
  46. useEffect(() => {
  47. getFileData(db, imgId)
  48. .then((data) => setData(data))
  49. .catch((e) => setData(src));
  50. }, [src, imgId]);
  51. return (
  52. <img
  53. className={className}
  54. src={data}
  55. alt={alt}
  56. onClick={(e) => onClick(data, e)}
  57. />
  58. );
  59. }