@fireproof/core 0.20.0-dev-preview-60 → 0.20.0-dev-preview-61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/react/index.cjs +21 -32
- package/react/index.cjs.map +1 -1
- package/react/index.js +21 -32
- package/react/index.js.map +1 -1
- package/react/metafile-cjs.json +1 -1
- package/react/metafile-esm.json +1 -1
- package/tests/react/use-fireproof-db-switch.test.tsx +0 -91
package/package.json
CHANGED
package/react/index.cjs
CHANGED
@@ -158,46 +158,35 @@ function createUseLiveQuery(database) {
|
|
158
158
|
return function useLiveQuery(mapFn, query = {}, initialRows = []) {
|
159
159
|
const [result, setResult] = (0, import_react2.useState)(() => {
|
160
160
|
const docs = initialRows.map((r) => r.doc).filter((r) => !!r);
|
161
|
-
return
|
162
|
-
|
163
|
-
|
164
|
-
|
165
|
-
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
},
|
171
|
-
docs
|
172
|
-
);
|
161
|
+
return {
|
162
|
+
rows: initialRows,
|
163
|
+
docs,
|
164
|
+
length: docs.length,
|
165
|
+
map: (fn) => docs.map(fn),
|
166
|
+
filter: (fn) => docs.filter(fn),
|
167
|
+
forEach: (fn) => docs.forEach(fn),
|
168
|
+
[Symbol.iterator]: () => docs[Symbol.iterator]()
|
169
|
+
};
|
173
170
|
});
|
174
171
|
const queryString = (0, import_react2.useMemo)(() => JSON.stringify(query), [query]);
|
175
172
|
const mapFnString = (0, import_react2.useMemo)(() => mapFn.toString(), [mapFn]);
|
176
173
|
const refreshRows = (0, import_react2.useCallback)(async () => {
|
177
174
|
const res = await database.query(mapFn, query);
|
178
175
|
const docs = res.rows.map((r) => r.doc).filter((r) => !!r);
|
179
|
-
setResult(
|
180
|
-
|
181
|
-
|
182
|
-
|
183
|
-
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
|
189
|
-
},
|
190
|
-
docs
|
191
|
-
)
|
192
|
-
);
|
193
|
-
}, [database, mapFnString, queryString]);
|
176
|
+
setResult({
|
177
|
+
...res,
|
178
|
+
docs,
|
179
|
+
length: docs.length,
|
180
|
+
map: (fn) => docs.map(fn),
|
181
|
+
filter: (fn) => docs.filter(fn),
|
182
|
+
forEach: (fn) => docs.forEach(fn),
|
183
|
+
[Symbol.iterator]: () => docs[Symbol.iterator]()
|
184
|
+
});
|
185
|
+
}, [mapFnString, queryString]);
|
194
186
|
(0, import_react2.useEffect)(() => {
|
195
187
|
refreshRows();
|
196
|
-
|
197
|
-
|
198
|
-
unsubscribe();
|
199
|
-
};
|
200
|
-
}, [database, refreshRows]);
|
188
|
+
return database.subscribe(refreshRows);
|
189
|
+
}, [refreshRows]);
|
201
190
|
return result;
|
202
191
|
};
|
203
192
|
}
|
package/react/index.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/react/index.ts","../../../src/react/use-fireproof.ts","../../../src/react/use-document.ts","../../../src/react/utils.ts","../../../src/react/use-live-query.ts","../../../src/react/use-all-docs.ts","../../../src/react/use-changes.ts","../../../src/react/img-file.ts"],"sourcesContent":["export { FireproofCtx, useFireproof } from \"./use-fireproof.js\";\nexport * from \"./types.js\";\nexport * from \"./img-file.js\";\n","import type { ConfigOpts, Database } from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport type { UseFireproof } from \"./types.js\";\nimport { createUseDocument } from \"./use-document.js\";\nimport { createUseLiveQuery } from \"./use-live-query.js\";\nimport { createUseAllDocs } from \"./use-all-docs.js\";\nimport { createUseChanges } from \"./use-changes.js\";\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n const useDocument = createUseDocument(database);\n const useLiveQuery = createUseLiveQuery(database);\n const useAllDocs = createUseAllDocs(database);\n const useChanges = createUseChanges(database);\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n\n// Export types\nexport type {\n LiveQueryResult,\n UseDocumentResult,\n AllDocsResult,\n ChangesResult,\n UseDocument,\n UseLiveQuery,\n UseAllDocs,\n UseChanges,\n UseFireproof,\n} from \"./types.js\";\n","import { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { DocSet, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport { deepClone } from \"./utils.js\";\nimport type { DeleteDocFn, StoreDocFn, UseDocumentInitialDocOrFn, UseDocumentResult } from \"./types.js\";\n\n/**\n * Implementation of the useDocument hook\n */\nexport function createUseDocument(database: Database) {\n const updateHappenedRef = useRef(false);\n\n return function useDocument<T extends DocTypes>(initialDocOrFn?: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn ?? ({} as T);\n }\n\n const originalInitialDoc = useMemo(() => deepClone({ ...initialDoc }), []);\n\n const [doc, setDoc] = useState(initialDoc);\n\n const refresh = useCallback(async () => {\n const gotDoc = doc._id ? await database.get<T>(doc._id).catch(() => initialDoc) : initialDoc;\n setDoc(gotDoc);\n }, [doc._id]);\n\n const save: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n updateHappenedRef.current = false;\n const toSave = existingDoc ?? doc;\n const res = await database.put(toSave);\n\n if (!updateHappenedRef.current && !doc._id && !existingDoc) {\n setDoc((d) => ({ ...d, _id: res.id }));\n }\n\n return res;\n },\n [doc],\n );\n\n const remove: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? doc._id;\n if (!id) throw database.logger.Error().Msg(`Document must have an _id to be removed`).AsError();\n const gotDoc = await database.get<T>(id).catch(() => undefined);\n if (!gotDoc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [doc, initialDoc],\n );\n\n // New granular update methods\n const merge = useCallback((newDoc: Partial<T>) => {\n updateHappenedRef.current = true;\n setDoc((prev) => ({ ...prev, ...newDoc }));\n }, []);\n\n const replace = useCallback((newDoc: T) => {\n updateHappenedRef.current = true;\n setDoc(newDoc);\n }, []);\n\n const reset = useCallback(() => {\n updateHappenedRef.current = true;\n setDoc({ ...originalInitialDoc });\n }, [originalInitialDoc]);\n\n // Legacy-compatible updateDoc\n const updateDoc = useCallback(\n (newDoc?: DocSet<T>, opts = { replace: false, reset: false }) => {\n if (!newDoc) {\n return opts.reset ? reset() : refresh();\n }\n return opts.replace ? replace(newDoc as T) : merge(newDoc);\n },\n [refresh, reset, replace, merge],\n );\n\n useEffect(() => {\n if (!doc._id) return;\n return database.subscribe((changes) => {\n if (updateHappenedRef.current) {\n return;\n }\n if (changes.find((c) => c._id === doc._id)) {\n void refresh();\n }\n }, true);\n }, [doc._id, refresh]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const submit = useCallback(\n async (e?: Event) => {\n if (e?.preventDefault) e.preventDefault();\n await save();\n reset();\n },\n [save, reset],\n );\n\n // Primary Object API with both new and legacy methods\n const apiObject = {\n doc: { ...doc } as DocWithId<T>,\n merge,\n replace,\n reset,\n refresh,\n save,\n remove,\n submit,\n };\n\n // Make the object properly iterable\n const tuple = [{ ...doc }, updateDoc, save, remove, reset, refresh];\n Object.assign(apiObject, tuple);\n Object.defineProperty(apiObject, Symbol.iterator, {\n enumerable: false,\n value: function* () {\n yield* tuple;\n },\n });\n\n return apiObject as UseDocumentResult<T>;\n };\n}\n","/**\n * Deep clone a value\n */\nexport function deepClone<T>(value: T): T {\n return (structuredClone ?? ((v: T) => JSON.parse(JSON.stringify(v))))(value);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { DocFragment, DocTypes, DocWithId, IndexKeyType, IndexRow, MapFn, Database } from \"@fireproof/core\";\nimport type { LiveQueryResult } from \"./types.js\";\n\n// Internal shadow type for array-like behavior\ntype ArrayLikeQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> = LiveQueryResult<T, K, R> &\n DocWithId<T>[];\n\n/**\n * Implementation of the useLiveQuery hook\n */\nexport function createUseLiveQuery(database: Database) {\n return function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<ArrayLikeQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return Object.assign(\n {\n docs,\n rows: initialRows,\n length: docs.length,\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n },\n docs,\n );\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n const docs = res.rows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n setResult(\n Object.assign(\n {\n docs,\n rows: res.rows,\n length: docs.length,\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n },\n docs,\n ),\n );\n }, [database, mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows();\n const unsubscribe = database.subscribe(refreshRows);\n return () => {\n unsubscribe();\n };\n }, [database, refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AllDocsQueryOpts, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { AllDocsResult } from \"./types.js\";\n\n/**\n * Implementation of the useAllDocs hook\n */\nexport function createUseAllDocs(database: Database) {\n return function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ChangesOptions, ClockHead, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { ChangesResult } from \"./types.js\";\n\n/**\n * Implementation of the useChanges hook\n */\nexport function createUseChanges(database: Database) {\n return function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { DocFileMeta } from \"@fireproof/core\";\nimport React, { useState, useEffect, ImgHTMLAttributes } from \"react\";\n\nconst { URL } = globalThis;\n\n// Union type to support both direct File objects and metadata objects\ntype FileType = File | DocFileMeta;\n\ninterface ImgFileProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, \"src\"> {\n file?: FileType;\n /**\n * @deprecated Use 'file' instead. This is for internal use only to support legacy code.\n * @internal\n */\n meta?: FileType;\n}\n\n// Helper function to determine if the object is a File-like object\nfunction isFile(obj: FileType): obj is File {\n return \"type\" in obj && \"size\" in obj && \"stream\" in obj && typeof obj.stream === \"function\";\n}\n\n// Helper function to determine if the object is a DocFileMeta\nfunction isFileMeta(obj: FileType): obj is DocFileMeta {\n return \"type\" in obj && \"size\" in obj && \"file\" in obj && typeof obj.file === \"function\";\n}\n\nexport function ImgFile({ file, meta, ...imgProps }: ImgFileProps) {\n const [imgDataUrl, setImgDataUrl] = useState(\"\");\n\n // Use meta as fallback if file is not provided (for backward compatibility)\n const fileData = file || meta;\n\n useEffect(() => {\n if (!fileData) return;\n\n const loadFile = async () => {\n let fileObj: File | null = null;\n let fileType = \"\";\n\n switch (true) {\n case isFile(fileData):\n fileObj = fileData;\n fileType = fileData.type;\n break;\n case isFileMeta(fileData):\n fileType = fileData.type;\n fileObj = (await fileData.file?.()) || null;\n break;\n }\n\n if (fileObj && /image/.test(fileType)) {\n const src = URL.createObjectURL(fileObj);\n setImgDataUrl(src);\n return () => URL.revokeObjectURL(src);\n }\n };\n\n let isMounted = true;\n let cleanup: (() => void) | undefined;\n\n loadFile().then((result) => {\n if (isMounted) {\n cleanup = result;\n } else if (result) {\n result();\n }\n });\n\n return () => {\n isMounted = false;\n if (cleanup) cleanup();\n };\n }, [fileData]);\n\n return imgDataUrl\n ? React.createElement(\"img\", {\n src: imgDataUrl,\n ...imgProps,\n })\n : null;\n}\n\nexport default ImgFile;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,kBAA0B;;;ACD1B,mBAAkE;;;ACG3D,SAAS,UAAa,OAAa;AACxC,UAAQ,oBAAoB,CAAC,MAAS,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,IAAI,KAAK;AAC7E;;;ADGO,SAAS,kBAAkB,UAAoB;AACpD,QAAM,wBAAoB,qBAAO,KAAK;AAEtC,SAAO,SAAS,YAAgC,gBAAqE;AACnH,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa,kBAAmB,CAAC;AAAA,IACnC;AAEA,UAAM,yBAAqB,sBAAQ,MAAM,UAAU,EAAE,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;AAEzE,UAAM,CAAC,KAAK,MAAM,QAAI,uBAAS,UAAU;AAEzC,UAAM,cAAU,0BAAY,YAAY;AACtC,YAAM,SAAS,IAAI,MAAM,MAAM,SAAS,IAAO,IAAI,GAAG,EAAE,MAAM,MAAM,UAAU,IAAI;AAClF,aAAO,MAAM;AAAA,IACf,GAAG,CAAC,IAAI,GAAG,CAAC;AAEZ,UAAM,WAAsB;AAAA,MAC1B,OAAO,gBAAgB;AACrB,0BAAkB,UAAU;AAC5B,cAAM,SAAS,eAAe;AAC9B,cAAM,MAAM,MAAM,SAAS,IAAI,MAAM;AAEr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B,eAAO,MAAM,IAAI,gBAAgB,GAAG;AAAA,MACtC;AAAA,IACF;AAEA,QAAI,YAAY;AAChB,QAAI;AAEJ,aAAS,EAAE,KAAK,CAAC,WAAW;AAC1B,UAAI,WAAW;AACb,kBAAU;AAAA,MACZ,WAAW,QAAQ;AACjB,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,kBAAY;AACZ,UAAI,QAAS,SAAQ;AAAA,IACvB;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO,aACH,cAAAC,QAAM,cAAc,OAAO;AAAA,IACzB,KAAK;AAAA,IACL,GAAG;AAAA,EACL,CAAC,IACD;AACN;","names":["import_react","import_react","import_react","import_react","React"]}
|
1
|
+
{"version":3,"sources":["../../../src/react/index.ts","../../../src/react/use-fireproof.ts","../../../src/react/use-document.ts","../../../src/react/utils.ts","../../../src/react/use-live-query.ts","../../../src/react/use-all-docs.ts","../../../src/react/use-changes.ts","../../../src/react/img-file.ts"],"sourcesContent":["export { FireproofCtx, useFireproof } from \"./use-fireproof.js\";\nexport * from \"./types.js\";\nexport * from \"./img-file.js\";\n","import type { ConfigOpts, Database } from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport type { UseFireproof } from \"./types.js\";\nimport { createUseDocument } from \"./use-document.js\";\nimport { createUseLiveQuery } from \"./use-live-query.js\";\nimport { createUseAllDocs } from \"./use-all-docs.js\";\nimport { createUseChanges } from \"./use-changes.js\";\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n const useDocument = createUseDocument(database);\n const useLiveQuery = createUseLiveQuery(database);\n const useAllDocs = createUseAllDocs(database);\n const useChanges = createUseChanges(database);\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n\n// Export types\nexport type {\n LiveQueryResult,\n UseDocumentResult,\n AllDocsResult,\n ChangesResult,\n UseDocument,\n UseLiveQuery,\n UseAllDocs,\n UseChanges,\n UseFireproof,\n} from \"./types.js\";\n","import { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { DocSet, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport { deepClone } from \"./utils.js\";\nimport type { DeleteDocFn, StoreDocFn, UseDocumentInitialDocOrFn, UseDocumentResult } from \"./types.js\";\n\n/**\n * Implementation of the useDocument hook\n */\nexport function createUseDocument(database: Database) {\n const updateHappenedRef = useRef(false);\n\n return function useDocument<T extends DocTypes>(initialDocOrFn?: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn ?? ({} as T);\n }\n\n const originalInitialDoc = useMemo(() => deepClone({ ...initialDoc }), []);\n\n const [doc, setDoc] = useState(initialDoc);\n\n const refresh = useCallback(async () => {\n const gotDoc = doc._id ? await database.get<T>(doc._id).catch(() => initialDoc) : initialDoc;\n setDoc(gotDoc);\n }, [doc._id]);\n\n const save: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n updateHappenedRef.current = false;\n const toSave = existingDoc ?? doc;\n const res = await database.put(toSave);\n\n if (!updateHappenedRef.current && !doc._id && !existingDoc) {\n setDoc((d) => ({ ...d, _id: res.id }));\n }\n\n return res;\n },\n [doc],\n );\n\n const remove: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? doc._id;\n if (!id) throw database.logger.Error().Msg(`Document must have an _id to be removed`).AsError();\n const gotDoc = await database.get<T>(id).catch(() => undefined);\n if (!gotDoc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [doc, initialDoc],\n );\n\n // New granular update methods\n const merge = useCallback((newDoc: Partial<T>) => {\n updateHappenedRef.current = true;\n setDoc((prev) => ({ ...prev, ...newDoc }));\n }, []);\n\n const replace = useCallback((newDoc: T) => {\n updateHappenedRef.current = true;\n setDoc(newDoc);\n }, []);\n\n const reset = useCallback(() => {\n updateHappenedRef.current = true;\n setDoc({ ...originalInitialDoc });\n }, [originalInitialDoc]);\n\n // Legacy-compatible updateDoc\n const updateDoc = useCallback(\n (newDoc?: DocSet<T>, opts = { replace: false, reset: false }) => {\n if (!newDoc) {\n return opts.reset ? reset() : refresh();\n }\n return opts.replace ? replace(newDoc as T) : merge(newDoc);\n },\n [refresh, reset, replace, merge],\n );\n\n useEffect(() => {\n if (!doc._id) return;\n return database.subscribe((changes) => {\n if (updateHappenedRef.current) {\n return;\n }\n if (changes.find((c) => c._id === doc._id)) {\n void refresh();\n }\n }, true);\n }, [doc._id, refresh]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const submit = useCallback(\n async (e?: Event) => {\n if (e?.preventDefault) e.preventDefault();\n await save();\n reset();\n },\n [save, reset],\n );\n\n // Primary Object API with both new and legacy methods\n const apiObject = {\n doc: { ...doc } as DocWithId<T>,\n merge,\n replace,\n reset,\n refresh,\n save,\n remove,\n submit,\n };\n\n // Make the object properly iterable\n const tuple = [{ ...doc }, updateDoc, save, remove, reset, refresh];\n Object.assign(apiObject, tuple);\n Object.defineProperty(apiObject, Symbol.iterator, {\n enumerable: false,\n value: function* () {\n yield* tuple;\n },\n });\n\n return apiObject as UseDocumentResult<T>;\n };\n}\n","/**\n * Deep clone a value\n */\nexport function deepClone<T>(value: T): T {\n return (structuredClone ?? ((v: T) => JSON.parse(JSON.stringify(v))))(value);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { DocFragment, DocTypes, DocWithId, IndexKeyType, IndexRow, MapFn, Database } from \"@fireproof/core\";\nimport type { LiveQueryResult } from \"./types.js\";\n\n/**\n * Implementation of the useLiveQuery hook\n */\nexport function createUseLiveQuery(database: Database) {\n return function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<LiveQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return {\n rows: initialRows,\n docs,\n length: docs.length,\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n } as LiveQueryResult<T, K, R>;\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n const docs = res.rows.map((r) => r.doc as DocWithId<T>).filter((r): r is DocWithId<T> => !!r);\n setResult({\n ...res,\n docs,\n length: docs.length,\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n } as LiveQueryResult<T, K, R>);\n }, [mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AllDocsQueryOpts, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { AllDocsResult } from \"./types.js\";\n\n/**\n * Implementation of the useAllDocs hook\n */\nexport function createUseAllDocs(database: Database) {\n return function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ChangesOptions, ClockHead, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { ChangesResult } from \"./types.js\";\n\n/**\n * Implementation of the useChanges hook\n */\nexport function createUseChanges(database: Database) {\n return function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { DocFileMeta } from \"@fireproof/core\";\nimport React, { useState, useEffect, ImgHTMLAttributes } from \"react\";\n\nconst { URL } = globalThis;\n\n// Union type to support both direct File objects and metadata objects\ntype FileType = File | DocFileMeta;\n\ninterface ImgFileProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, \"src\"> {\n file?: FileType;\n /**\n * @deprecated Use 'file' instead. This is for internal use only to support legacy code.\n * @internal\n */\n meta?: FileType;\n}\n\n// Helper function to determine if the object is a File-like object\nfunction isFile(obj: FileType): obj is File {\n return \"type\" in obj && \"size\" in obj && \"stream\" in obj && typeof obj.stream === \"function\";\n}\n\n// Helper function to determine if the object is a DocFileMeta\nfunction isFileMeta(obj: FileType): obj is DocFileMeta {\n return \"type\" in obj && \"size\" in obj && \"file\" in obj && typeof obj.file === \"function\";\n}\n\nexport function ImgFile({ file, meta, ...imgProps }: ImgFileProps) {\n const [imgDataUrl, setImgDataUrl] = useState(\"\");\n\n // Use meta as fallback if file is not provided (for backward compatibility)\n const fileData = file || meta;\n\n useEffect(() => {\n if (!fileData) return;\n\n const loadFile = async () => {\n let fileObj: File | null = null;\n let fileType = \"\";\n\n switch (true) {\n case isFile(fileData):\n fileObj = fileData;\n fileType = fileData.type;\n break;\n case isFileMeta(fileData):\n fileType = fileData.type;\n fileObj = (await fileData.file?.()) || null;\n break;\n }\n\n if (fileObj && /image/.test(fileType)) {\n const src = URL.createObjectURL(fileObj);\n setImgDataUrl(src);\n return () => URL.revokeObjectURL(src);\n }\n };\n\n let isMounted = true;\n let cleanup: (() => void) | undefined;\n\n loadFile().then((result) => {\n if (isMounted) {\n cleanup = result;\n } else if (result) {\n result();\n }\n });\n\n return () => {\n isMounted = false;\n if (cleanup) cleanup();\n };\n }, [fileData]);\n\n return imgDataUrl\n ? React.createElement(\"img\", {\n src: imgDataUrl,\n ...imgProps,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","import_react","import_react","import_react","React"]}
|
package/react/index.js
CHANGED
@@ -120,46 +120,35 @@ function createUseLiveQuery(database) {
|
|
120
120
|
return function useLiveQuery(mapFn, query = {}, initialRows = []) {
|
121
121
|
const [result, setResult] = useState2(() => {
|
122
122
|
const docs = initialRows.map((r) => r.doc).filter((r) => !!r);
|
123
|
-
return
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
},
|
133
|
-
docs
|
134
|
-
);
|
123
|
+
return {
|
124
|
+
rows: initialRows,
|
125
|
+
docs,
|
126
|
+
length: docs.length,
|
127
|
+
map: (fn) => docs.map(fn),
|
128
|
+
filter: (fn) => docs.filter(fn),
|
129
|
+
forEach: (fn) => docs.forEach(fn),
|
130
|
+
[Symbol.iterator]: () => docs[Symbol.iterator]()
|
131
|
+
};
|
135
132
|
});
|
136
133
|
const queryString = useMemo2(() => JSON.stringify(query), [query]);
|
137
134
|
const mapFnString = useMemo2(() => mapFn.toString(), [mapFn]);
|
138
135
|
const refreshRows = useCallback2(async () => {
|
139
136
|
const res = await database.query(mapFn, query);
|
140
137
|
const docs = res.rows.map((r) => r.doc).filter((r) => !!r);
|
141
|
-
setResult(
|
142
|
-
|
143
|
-
|
144
|
-
|
145
|
-
|
146
|
-
|
147
|
-
|
148
|
-
|
149
|
-
|
150
|
-
|
151
|
-
},
|
152
|
-
docs
|
153
|
-
)
|
154
|
-
);
|
155
|
-
}, [database, mapFnString, queryString]);
|
138
|
+
setResult({
|
139
|
+
...res,
|
140
|
+
docs,
|
141
|
+
length: docs.length,
|
142
|
+
map: (fn) => docs.map(fn),
|
143
|
+
filter: (fn) => docs.filter(fn),
|
144
|
+
forEach: (fn) => docs.forEach(fn),
|
145
|
+
[Symbol.iterator]: () => docs[Symbol.iterator]()
|
146
|
+
});
|
147
|
+
}, [mapFnString, queryString]);
|
156
148
|
useEffect2(() => {
|
157
149
|
refreshRows();
|
158
|
-
|
159
|
-
|
160
|
-
unsubscribe();
|
161
|
-
};
|
162
|
-
}, [database, refreshRows]);
|
150
|
+
return database.subscribe(refreshRows);
|
151
|
+
}, [refreshRows]);
|
163
152
|
return result;
|
164
153
|
};
|
165
154
|
}
|
package/react/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/react/use-fireproof.ts","../../../src/react/use-document.ts","../../../src/react/utils.ts","../../../src/react/use-live-query.ts","../../../src/react/use-all-docs.ts","../../../src/react/use-changes.ts","../../../src/react/img-file.ts"],"sourcesContent":["import type { ConfigOpts, Database } from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport type { UseFireproof } from \"./types.js\";\nimport { createUseDocument } from \"./use-document.js\";\nimport { createUseLiveQuery } from \"./use-live-query.js\";\nimport { createUseAllDocs } from \"./use-all-docs.js\";\nimport { createUseChanges } from \"./use-changes.js\";\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n const useDocument = createUseDocument(database);\n const useLiveQuery = createUseLiveQuery(database);\n const useAllDocs = createUseAllDocs(database);\n const useChanges = createUseChanges(database);\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n\n// Export types\nexport type {\n LiveQueryResult,\n UseDocumentResult,\n AllDocsResult,\n ChangesResult,\n UseDocument,\n UseLiveQuery,\n UseAllDocs,\n UseChanges,\n UseFireproof,\n} from \"./types.js\";\n","import { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { DocSet, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport { deepClone } from \"./utils.js\";\nimport type { DeleteDocFn, StoreDocFn, UseDocumentInitialDocOrFn, UseDocumentResult } from \"./types.js\";\n\n/**\n * Implementation of the useDocument hook\n */\nexport function createUseDocument(database: Database) {\n const updateHappenedRef = useRef(false);\n\n return function useDocument<T extends DocTypes>(initialDocOrFn?: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn ?? ({} as T);\n }\n\n const originalInitialDoc = useMemo(() => deepClone({ ...initialDoc }), []);\n\n const [doc, setDoc] = useState(initialDoc);\n\n const refresh = useCallback(async () => {\n const gotDoc = doc._id ? await database.get<T>(doc._id).catch(() => initialDoc) : initialDoc;\n setDoc(gotDoc);\n }, [doc._id]);\n\n const save: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n updateHappenedRef.current = false;\n const toSave = existingDoc ?? doc;\n const res = await database.put(toSave);\n\n if (!updateHappenedRef.current && !doc._id && !existingDoc) {\n setDoc((d) => ({ ...d, _id: res.id }));\n }\n\n return res;\n },\n [doc],\n );\n\n const remove: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? doc._id;\n if (!id) throw database.logger.Error().Msg(`Document must have an _id to be removed`).AsError();\n const gotDoc = await database.get<T>(id).catch(() => undefined);\n if (!gotDoc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [doc, initialDoc],\n );\n\n // New granular update methods\n const merge = useCallback((newDoc: Partial<T>) => {\n updateHappenedRef.current = true;\n setDoc((prev) => ({ ...prev, ...newDoc }));\n }, []);\n\n const replace = useCallback((newDoc: T) => {\n updateHappenedRef.current = true;\n setDoc(newDoc);\n }, []);\n\n const reset = useCallback(() => {\n updateHappenedRef.current = true;\n setDoc({ ...originalInitialDoc });\n }, [originalInitialDoc]);\n\n // Legacy-compatible updateDoc\n const updateDoc = useCallback(\n (newDoc?: DocSet<T>, opts = { replace: false, reset: false }) => {\n if (!newDoc) {\n return opts.reset ? reset() : refresh();\n }\n return opts.replace ? replace(newDoc as T) : merge(newDoc);\n },\n [refresh, reset, replace, merge],\n );\n\n useEffect(() => {\n if (!doc._id) return;\n return database.subscribe((changes) => {\n if (updateHappenedRef.current) {\n return;\n }\n if (changes.find((c) => c._id === doc._id)) {\n void refresh();\n }\n }, true);\n }, [doc._id, refresh]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const submit = useCallback(\n async (e?: Event) => {\n if (e?.preventDefault) e.preventDefault();\n await save();\n reset();\n },\n [save, reset],\n );\n\n // Primary Object API with both new and legacy methods\n const apiObject = {\n doc: { ...doc } as DocWithId<T>,\n merge,\n replace,\n reset,\n refresh,\n save,\n remove,\n submit,\n };\n\n // Make the object properly iterable\n const tuple = [{ ...doc }, updateDoc, save, remove, reset, refresh];\n Object.assign(apiObject, tuple);\n Object.defineProperty(apiObject, Symbol.iterator, {\n enumerable: false,\n value: function* () {\n yield* tuple;\n },\n });\n\n return apiObject as UseDocumentResult<T>;\n };\n}\n","/**\n * Deep clone a value\n */\nexport function deepClone<T>(value: T): T {\n return (structuredClone ?? ((v: T) => JSON.parse(JSON.stringify(v))))(value);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { DocFragment, DocTypes, DocWithId, IndexKeyType, IndexRow, MapFn, Database } from \"@fireproof/core\";\nimport type { LiveQueryResult } from \"./types.js\";\n\n// Internal shadow type for array-like behavior\ntype ArrayLikeQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> = LiveQueryResult<T, K, R> &\n DocWithId<T>[];\n\n/**\n * Implementation of the useLiveQuery hook\n */\nexport function createUseLiveQuery(database: Database) {\n return function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<ArrayLikeQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return Object.assign(\n {\n docs,\n rows: initialRows,\n length: docs.length,\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n },\n docs,\n );\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n const docs = res.rows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n setResult(\n Object.assign(\n {\n docs,\n rows: res.rows,\n length: docs.length,\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n },\n docs,\n ),\n );\n }, [database, mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows();\n const unsubscribe = database.subscribe(refreshRows);\n return () => {\n unsubscribe();\n };\n }, [database, refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AllDocsQueryOpts, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { AllDocsResult } from \"./types.js\";\n\n/**\n * Implementation of the useAllDocs hook\n */\nexport function createUseAllDocs(database: Database) {\n return function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ChangesOptions, ClockHead, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { ChangesResult } from \"./types.js\";\n\n/**\n * Implementation of the useChanges hook\n */\nexport function createUseChanges(database: Database) {\n return function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { DocFileMeta } from \"@fireproof/core\";\nimport React, { useState, useEffect, ImgHTMLAttributes } from \"react\";\n\nconst { URL } = globalThis;\n\n// Union type to support both direct File objects and metadata objects\ntype FileType = File | DocFileMeta;\n\ninterface ImgFileProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, \"src\"> {\n file?: FileType;\n /**\n * @deprecated Use 'file' instead. This is for internal use only to support legacy code.\n * @internal\n */\n meta?: FileType;\n}\n\n// Helper function to determine if the object is a File-like object\nfunction isFile(obj: FileType): obj is File {\n return \"type\" in obj && \"size\" in obj && \"stream\" in obj && typeof obj.stream === \"function\";\n}\n\n// Helper function to determine if the object is a DocFileMeta\nfunction isFileMeta(obj: FileType): obj is DocFileMeta {\n return \"type\" in obj && \"size\" in obj && \"file\" in obj && typeof obj.file === \"function\";\n}\n\nexport function ImgFile({ file, meta, ...imgProps }: ImgFileProps) {\n const [imgDataUrl, setImgDataUrl] = useState(\"\");\n\n // Use meta as fallback if file is not provided (for backward compatibility)\n const fileData = file || meta;\n\n useEffect(() => {\n if (!fileData) return;\n\n const loadFile = async () => {\n let fileObj: File | null = null;\n let fileType = \"\";\n\n switch (true) {\n case isFile(fileData):\n fileObj = fileData;\n fileType = fileData.type;\n break;\n case isFileMeta(fileData):\n fileType = fileData.type;\n fileObj = (await fileData.file?.()) || null;\n break;\n }\n\n if (fileObj && /image/.test(fileType)) {\n const src = URL.createObjectURL(fileObj);\n setImgDataUrl(src);\n return () => URL.revokeObjectURL(src);\n }\n };\n\n let isMounted = true;\n let cleanup: (() => void) | undefined;\n\n loadFile().then((result) => {\n if (isMounted) {\n cleanup = result;\n } else if (result) {\n result();\n }\n });\n\n return () => {\n isMounted = false;\n if (cleanup) cleanup();\n };\n }, [fileData]);\n\n return imgDataUrl\n ? React.createElement(\"img\", {\n src: imgDataUrl,\n ...imgProps,\n })\n : null;\n}\n\nexport default ImgFile;\n"],"mappings":";AACA,SAAS,iBAAiB;;;ACD1B,SAAS,aAAa,WAAW,SAAS,UAAU,cAAc;;;ACG3D,SAAS,UAAa,OAAa;AACxC,UAAQ,oBAAoB,CAAC,MAAS,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,IAAI,KAAK;AAC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AAG;AAAA,EACL,CAAC,IACD;AACN;","names":["useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useState","useEffect"]}
|
1
|
+
{"version":3,"sources":["../../../src/react/use-fireproof.ts","../../../src/react/use-document.ts","../../../src/react/utils.ts","../../../src/react/use-live-query.ts","../../../src/react/use-all-docs.ts","../../../src/react/use-changes.ts","../../../src/react/img-file.ts"],"sourcesContent":["import type { ConfigOpts, Database } from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport type { UseFireproof } from \"./types.js\";\nimport { createUseDocument } from \"./use-document.js\";\nimport { createUseLiveQuery } from \"./use-live-query.js\";\nimport { createUseAllDocs } from \"./use-all-docs.js\";\nimport { createUseChanges } from \"./use-changes.js\";\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n const useDocument = createUseDocument(database);\n const useLiveQuery = createUseLiveQuery(database);\n const useAllDocs = createUseAllDocs(database);\n const useChanges = createUseChanges(database);\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n\n// Export types\nexport type {\n LiveQueryResult,\n UseDocumentResult,\n AllDocsResult,\n ChangesResult,\n UseDocument,\n UseLiveQuery,\n UseAllDocs,\n UseChanges,\n UseFireproof,\n} from \"./types.js\";\n","import { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { DocSet, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport { deepClone } from \"./utils.js\";\nimport type { DeleteDocFn, StoreDocFn, UseDocumentInitialDocOrFn, UseDocumentResult } from \"./types.js\";\n\n/**\n * Implementation of the useDocument hook\n */\nexport function createUseDocument(database: Database) {\n const updateHappenedRef = useRef(false);\n\n return function useDocument<T extends DocTypes>(initialDocOrFn?: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn ?? ({} as T);\n }\n\n const originalInitialDoc = useMemo(() => deepClone({ ...initialDoc }), []);\n\n const [doc, setDoc] = useState(initialDoc);\n\n const refresh = useCallback(async () => {\n const gotDoc = doc._id ? await database.get<T>(doc._id).catch(() => initialDoc) : initialDoc;\n setDoc(gotDoc);\n }, [doc._id]);\n\n const save: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n updateHappenedRef.current = false;\n const toSave = existingDoc ?? doc;\n const res = await database.put(toSave);\n\n if (!updateHappenedRef.current && !doc._id && !existingDoc) {\n setDoc((d) => ({ ...d, _id: res.id }));\n }\n\n return res;\n },\n [doc],\n );\n\n const remove: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? doc._id;\n if (!id) throw database.logger.Error().Msg(`Document must have an _id to be removed`).AsError();\n const gotDoc = await database.get<T>(id).catch(() => undefined);\n if (!gotDoc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [doc, initialDoc],\n );\n\n // New granular update methods\n const merge = useCallback((newDoc: Partial<T>) => {\n updateHappenedRef.current = true;\n setDoc((prev) => ({ ...prev, ...newDoc }));\n }, []);\n\n const replace = useCallback((newDoc: T) => {\n updateHappenedRef.current = true;\n setDoc(newDoc);\n }, []);\n\n const reset = useCallback(() => {\n updateHappenedRef.current = true;\n setDoc({ ...originalInitialDoc });\n }, [originalInitialDoc]);\n\n // Legacy-compatible updateDoc\n const updateDoc = useCallback(\n (newDoc?: DocSet<T>, opts = { replace: false, reset: false }) => {\n if (!newDoc) {\n return opts.reset ? reset() : refresh();\n }\n return opts.replace ? replace(newDoc as T) : merge(newDoc);\n },\n [refresh, reset, replace, merge],\n );\n\n useEffect(() => {\n if (!doc._id) return;\n return database.subscribe((changes) => {\n if (updateHappenedRef.current) {\n return;\n }\n if (changes.find((c) => c._id === doc._id)) {\n void refresh();\n }\n }, true);\n }, [doc._id, refresh]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const submit = useCallback(\n async (e?: Event) => {\n if (e?.preventDefault) e.preventDefault();\n await save();\n reset();\n },\n [save, reset],\n );\n\n // Primary Object API with both new and legacy methods\n const apiObject = {\n doc: { ...doc } as DocWithId<T>,\n merge,\n replace,\n reset,\n refresh,\n save,\n remove,\n submit,\n };\n\n // Make the object properly iterable\n const tuple = [{ ...doc }, updateDoc, save, remove, reset, refresh];\n Object.assign(apiObject, tuple);\n Object.defineProperty(apiObject, Symbol.iterator, {\n enumerable: false,\n value: function* () {\n yield* tuple;\n },\n });\n\n return apiObject as UseDocumentResult<T>;\n };\n}\n","/**\n * Deep clone a value\n */\nexport function deepClone<T>(value: T): T {\n return (structuredClone ?? ((v: T) => JSON.parse(JSON.stringify(v))))(value);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { DocFragment, DocTypes, DocWithId, IndexKeyType, IndexRow, MapFn, Database } from \"@fireproof/core\";\nimport type { LiveQueryResult } from \"./types.js\";\n\n/**\n * Implementation of the useLiveQuery hook\n */\nexport function createUseLiveQuery(database: Database) {\n return function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<LiveQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return {\n rows: initialRows,\n docs,\n length: docs.length,\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n } as LiveQueryResult<T, K, R>;\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n const docs = res.rows.map((r) => r.doc as DocWithId<T>).filter((r): r is DocWithId<T> => !!r);\n setResult({\n ...res,\n docs,\n length: docs.length,\n map: <U>(fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U) => docs.map(fn),\n filter: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean) => docs.filter(fn),\n forEach: (fn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n } as LiveQueryResult<T, K, R>);\n }, [mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AllDocsQueryOpts, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { AllDocsResult } from \"./types.js\";\n\n/**\n * Implementation of the useAllDocs hook\n */\nexport function createUseAllDocs(database: Database) {\n return function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ChangesOptions, ClockHead, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { ChangesResult } from \"./types.js\";\n\n/**\n * Implementation of the useChanges hook\n */\nexport function createUseChanges(database: Database) {\n return function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n };\n}\n","import { DocFileMeta } from \"@fireproof/core\";\nimport React, { useState, useEffect, ImgHTMLAttributes } from \"react\";\n\nconst { URL } = globalThis;\n\n// Union type to support both direct File objects and metadata objects\ntype FileType = File | DocFileMeta;\n\ninterface ImgFileProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, \"src\"> {\n file?: FileType;\n /**\n * @deprecated Use 'file' instead. This is for internal use only to support legacy code.\n * @internal\n */\n meta?: FileType;\n}\n\n// Helper function to determine if the object is a File-like object\nfunction isFile(obj: FileType): obj is File {\n return \"type\" in obj && \"size\" in obj && \"stream\" in obj && typeof obj.stream === \"function\";\n}\n\n// Helper function to determine if the object is a DocFileMeta\nfunction isFileMeta(obj: FileType): obj is DocFileMeta {\n return \"type\" in obj && \"size\" in obj && \"file\" in obj && typeof obj.file === \"function\";\n}\n\nexport function ImgFile({ file, meta, ...imgProps }: ImgFileProps) {\n const [imgDataUrl, setImgDataUrl] = useState(\"\");\n\n // Use meta as fallback if file is not provided (for backward compatibility)\n const fileData = file || meta;\n\n useEffect(() => {\n if (!fileData) return;\n\n const loadFile = async () => {\n let fileObj: File | null = null;\n let fileType = \"\";\n\n switch (true) {\n case isFile(fileData):\n fileObj = fileData;\n fileType = fileData.type;\n break;\n case isFileMeta(fileData):\n fileType = fileData.type;\n fileObj = (await fileData.file?.()) || null;\n break;\n }\n\n if (fileObj && /image/.test(fileType)) {\n const src = URL.createObjectURL(fileObj);\n setImgDataUrl(src);\n return () => URL.revokeObjectURL(src);\n }\n };\n\n let isMounted = true;\n let cleanup: (() => void) | undefined;\n\n loadFile().then((result) => {\n if (isMounted) {\n cleanup = result;\n } else if (result) {\n result();\n }\n });\n\n return () => {\n isMounted = false;\n if (cleanup) cleanup();\n };\n }, [fileData]);\n\n return imgDataUrl\n ? React.createElement(\"img\", {\n src: imgDataUrl,\n ...imgProps,\n })\n : null;\n}\n\nexport default ImgFile;\n"],"mappings":";AACA,SAAS,iBAAiB;;;ACD1B,SAAS,aAAa,WAAW,SAAS,UAAU,cAAc;;;ACG3D,SAAS,UAAa,OAAa;AACxC,UAAQ,oBAAoB,CAAC,MAAS,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,IAAI,KAAK;AAC7E;;;ADGO,SAAS,kBAAkB,UAAoB;AACpD,QAAM,oBAAoB,OAAO,KAAK;AAEtC,SAAO,SAAS,YAAgC,gBAAqE;AACnH,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa,kBAAmB,CAAC;AAA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QAAM,CAAC,YAAY,aAAa,IAAID,UAAS,EAAE;AAG/C,QAAM,WAAW,QAAQ;AAEzB,EAAAC,WAAU,MAAM;AACd,QAAI,CAAC,SAAU;AAEf,UAAM,WAAW,YAAY;AAC3B,UAAI,UAAuB;AAC3B,UAAI,WAAW;AAEf,cAAQ,MAAM;AAAA,QACZ,KAAK,OAAO,QAAQ;AAClB,oBAAU;AACV,qBAAW,SAAS;AACpB;AAAA,QACF,KAAK,WAAW,QAAQ;AACtB,qBAAW,SAAS;AACpB,oBAAW,MAAM,SAAS,OAAO,KAAM;AACvC;AAAA,MACJ;AAEA,UAAI,WAAW,QAAQ,KAAK,QAAQ,GAAG;AACrC,cAAM,MAAM,IAAI,gBAAgB,OAAO;AACvC,sBAAc,GAAG;AACjB,eAAO,MAAM,IAAI,gBAAgB,GAAG;AAAA,MACtC;AAAA,IACF;AAEA,QAAI,YAAY;AAChB,QAAI;AAEJ,aAAS,EAAE,KAAK,CAAC,WAAW;AAC1B,UAAI,WAAW;AACb,kBAAU;AAAA,MACZ,WAAW,QAAQ;AACjB,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,kBAAY;AACZ,UAAI,QAAS,SAAQ;AAAA,IACvB;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO,aACH,MAAM,cAAc,OAAO;AAAA,IACzB,KAAK;AAAA,IACL,GAAG;AAAA,EACL,CAAC,IACD;AACN;","names":["useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useState","useEffect"]}
|
package/react/metafile-cjs.json
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":3958,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":
|
1
|
+
{"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":3958,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":2307,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-all-docs.ts":{"bytes":934,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-changes.ts":{"bytes":974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-fireproof.ts":{"bytes":2247,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/use-document.ts","kind":"import-statement","original":"./use-document.js"},{"path":"src/react/use-live-query.ts","kind":"import-statement","original":"./use-live-query.js"},{"path":"src/react/use-all-docs.ts","kind":"import-statement","original":"./use-all-docs.js"},{"path":"src/react/use-changes.ts","kind":"import-statement","original":"./use-changes.js"}],"format":"esm"},"src/react/types.ts":{"bytes":2407,"imports":[],"format":"esm"},"src/react/img-file.ts":{"bytes":2248,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/index.ts":{"bytes":124,"imports":[{"path":"src/react/use-fireproof.ts","kind":"import-statement","original":"./use-fireproof.js"},{"path":"src/react/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/react/img-file.ts","kind":"import-statement","original":"./img-file.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":20110},"dist/fireproof-core/react/index.cjs":{"imports":[{"path":"@fireproof/core","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/react/index.ts","inputs":{"src/react/index.ts":{"bytesInOutput":197},"src/react/use-fireproof.ts":{"bytesInOutput":502},"src/react/use-document.ts":{"bytesInOutput":3458},"src/react/utils.ts":{"bytesInOutput":107},"src/react/use-live-query.ts":{"bytesInOutput":1383},"src/react/use-all-docs.ts":{"bytesInOutput":657},"src/react/use-changes.ts":{"bytesInOutput":679},"src/react/img-file.ts":{"bytesInOutput":1499}},"bytes":10163}}}
|
package/react/metafile-esm.json
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":3958,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":
|
1
|
+
{"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":3958,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":2307,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-all-docs.ts":{"bytes":934,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-changes.ts":{"bytes":974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-fireproof.ts":{"bytes":2247,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/use-document.ts","kind":"import-statement","original":"./use-document.js"},{"path":"src/react/use-live-query.ts","kind":"import-statement","original":"./use-live-query.js"},{"path":"src/react/use-all-docs.ts","kind":"import-statement","original":"./use-all-docs.js"},{"path":"src/react/use-changes.ts","kind":"import-statement","original":"./use-changes.js"}],"format":"esm"},"src/react/types.ts":{"bytes":2407,"imports":[],"format":"esm"},"src/react/img-file.ts":{"bytes":2248,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/index.ts":{"bytes":124,"imports":[{"path":"src/react/use-fireproof.ts","kind":"import-statement","original":"./use-fireproof.js"},{"path":"src/react/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/react/img-file.ts","kind":"import-statement","original":"./img-file.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.js.map":{"imports":[],"exports":[],"inputs":{},"bytes":20140},"dist/fireproof-core/react/index.js":{"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["FireproofCtx","ImgFile","useFireproof"],"entryPoint":"src/react/index.ts","inputs":{"src/react/use-fireproof.ts":{"bytesInOutput":484},"src/react/use-document.ts":{"bytesInOutput":3262},"src/react/utils.ts":{"bytesInOutput":107},"src/react/use-live-query.ts":{"bytesInOutput":1377},"src/react/use-all-docs.ts":{"bytesInOutput":669},"src/react/use-changes.ts":{"bytesInOutput":691},"src/react/index.ts":{"bytesInOutput":0},"src/react/img-file.ts":{"bytesInOutput":1476}},"bytes":8381}}}
|
@@ -1,91 +0,0 @@
|
|
1
|
-
import { renderHook, waitFor } from "@testing-library/react";
|
2
|
-
import { describe, expect, it } from "vitest";
|
3
|
-
import { fireproof, useFireproof } from "use-fireproof";
|
4
|
-
import type { Database, LiveQueryResult } from "use-fireproof";
|
5
|
-
|
6
|
-
// Test timeout value for CI
|
7
|
-
const TEST_TIMEOUT = 45000;
|
8
|
-
|
9
|
-
describe("HOOK: useFireproof database switching", () => {
|
10
|
-
const db1Name = "db1";
|
11
|
-
const db2Name = "db2";
|
12
|
-
let db1: Database, db2: Database;
|
13
|
-
|
14
|
-
beforeEach(async () => {
|
15
|
-
// Setup two databases with different data
|
16
|
-
db1 = fireproof(db1Name);
|
17
|
-
db2 = fireproof(db2Name);
|
18
|
-
|
19
|
-
// Add data to db1
|
20
|
-
await db1.put({ foo: "db1-data" });
|
21
|
-
|
22
|
-
// Add different data to db2
|
23
|
-
await db2.put({ foo: "db2-data" });
|
24
|
-
});
|
25
|
-
|
26
|
-
it(
|
27
|
-
"should switch databases and update query results when database name changes",
|
28
|
-
async () => {
|
29
|
-
let query: LiveQueryResult<{ foo: string }, string>;
|
30
|
-
let currentDbName: string;
|
31
|
-
let currentDb: Database;
|
32
|
-
|
33
|
-
// Initial render with db1
|
34
|
-
const { rerender } = renderHook(
|
35
|
-
({ dbName }) => {
|
36
|
-
const result = useFireproof(dbName);
|
37
|
-
currentDbName = result.database.name;
|
38
|
-
currentDb = result.database;
|
39
|
-
query = result.useLiveQuery<{ foo: string }>("foo");
|
40
|
-
return result;
|
41
|
-
},
|
42
|
-
{ initialProps: { dbName: db1Name } },
|
43
|
-
);
|
44
|
-
|
45
|
-
// Verify initial state with db1
|
46
|
-
await waitFor(() => {
|
47
|
-
expect(currentDbName).toBe(db1Name);
|
48
|
-
expect(currentDb.name).toBe(db1Name);
|
49
|
-
expect(query.rows.map((row) => row.doc?.foo)).toEqual(["db1-data"]);
|
50
|
-
});
|
51
|
-
|
52
|
-
// Switch to db2
|
53
|
-
rerender({ dbName: db2Name });
|
54
|
-
|
55
|
-
// Verify state with db2
|
56
|
-
await waitFor(() => {
|
57
|
-
expect(currentDbName).toBe(db2Name);
|
58
|
-
expect(currentDb.name).toBe(db2Name);
|
59
|
-
expect(query.rows.map((row) => row.doc?.foo)).toEqual(["db2-data"]);
|
60
|
-
});
|
61
|
-
|
62
|
-
// Switch back to db1
|
63
|
-
rerender({ dbName: db1Name });
|
64
|
-
|
65
|
-
// Verify state is back to db1
|
66
|
-
await waitFor(() => {
|
67
|
-
expect(currentDbName).toBe(db1Name);
|
68
|
-
expect(currentDb.name).toBe(db1Name);
|
69
|
-
expect(query.rows.map((row) => row.doc?.foo)).toEqual(["db1-data"]);
|
70
|
-
});
|
71
|
-
|
72
|
-
// Test that changes to the new database are reflected
|
73
|
-
await db2.put({ foo: "db2-updated" });
|
74
|
-
rerender({ dbName: db2Name });
|
75
|
-
|
76
|
-
await waitFor(() => {
|
77
|
-
expect(currentDbName).toBe(db2Name);
|
78
|
-
expect(currentDb.name).toBe(db2Name);
|
79
|
-
expect(query.rows.map((row) => row.doc?.foo)).toEqual(["db2-data", "db2-updated"]);
|
80
|
-
});
|
81
|
-
},
|
82
|
-
TEST_TIMEOUT,
|
83
|
-
);
|
84
|
-
|
85
|
-
afterEach(async () => {
|
86
|
-
await db1.close();
|
87
|
-
await db1.destroy();
|
88
|
-
await db2.close();
|
89
|
-
await db2.destroy();
|
90
|
-
});
|
91
|
-
});
|