file.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 base64Image2Blob(base64Data: string, contentType: string) {
  32. const byteCharacters = atob(base64Data);
  33. const byteNumbers = new Array(byteCharacters.length);
  34. for (let i = 0; i < byteCharacters.length; i++) {
  35. byteNumbers[i] = byteCharacters.charCodeAt(i);
  36. }
  37. const byteArray = new Uint8Array(byteNumbers);
  38. return new Blob([byteArray], { type: contentType });
  39. }
  40. export function saveFileData(db, fileId, data) {
  41. // save file content and return url start with `indexeddb://`
  42. db.add({ id: fileId, data });
  43. return `indexeddb://${StoreKey.File}@${fileId}`;
  44. }
  45. export async function getFileData(db, fileId, contentType = "image/png") {
  46. const { data } = await db.getByID(fileId);
  47. if (typeof data == "object") {
  48. return URL.createObjectURL(data);
  49. }
  50. return `data:${contentType};base64,${data}`;
  51. }
  52. export function IndexDBImage({ src, alt, onClick, db, className }) {
  53. const [data, setData] = useState(src);
  54. const imgId = useMemo(
  55. () => src.replace("indexeddb://", "").split("@").pop(),
  56. [src],
  57. );
  58. useEffect(() => {
  59. getFileData(db, imgId)
  60. .then((data) => setData(data))
  61. .catch((e) => setData(src));
  62. }, [src, imgId]);
  63. return (
  64. <img
  65. className={className}
  66. src={data}
  67. alt={alt}
  68. onClick={(e) => onClick(data, e)}
  69. />
  70. );
  71. }