@pomwik/afterdb-react 0.0.0-stage → 0.20.1

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.
Files changed (52) hide show
  1. package/CHANGES-FROM-UPSTREAM.md +57 -0
  2. package/LICENSE +177 -0
  3. package/NOTICE +9 -0
  4. package/README.md +10 -2
  5. package/dist/RealmContext.d.ts +153 -0
  6. package/dist/RealmContext.d.ts.map +1 -0
  7. package/dist/RealmProvider.d.ts +95 -0
  8. package/dist/RealmProvider.d.ts.map +1 -0
  9. package/dist/cachedCollection.d.ts +58 -0
  10. package/dist/cachedCollection.d.ts.map +1 -0
  11. package/dist/cachedObject.d.ts +48 -0
  12. package/dist/cachedObject.d.ts.map +1 -0
  13. package/dist/helpers.d.ts +22 -0
  14. package/dist/helpers.d.ts.map +1 -0
  15. package/dist/index.cjs +2818 -0
  16. package/dist/index.cjs.map +1 -0
  17. package/dist/index.d.ts +100 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +2809 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/tsconfig.types.tsbuildinfo +1 -0
  22. package/dist/types.d.ts +64 -0
  23. package/dist/types.d.ts.map +1 -0
  24. package/dist/useObject.d.ts +30 -0
  25. package/dist/useObject.d.ts.map +1 -0
  26. package/dist/useQuery.d.ts +31 -0
  27. package/dist/useQuery.d.ts.map +1 -0
  28. package/dist/useRealm.d.ts +12 -0
  29. package/dist/useRealm.d.ts.map +1 -0
  30. package/package.json +117 -4
  31. package/src/RealmContext.ts +196 -0
  32. package/src/RealmProvider.tsx +251 -0
  33. package/src/__tests__/RealmProvider.test.tsx +583 -0
  34. package/src/__tests__/createRealmTestContext.ts +68 -0
  35. package/src/__tests__/helpers.ts +35 -0
  36. package/src/__tests__/mocks.ts +154 -0
  37. package/src/__tests__/profileHook.tsx +76 -0
  38. package/src/__tests__/setup.ts +22 -0
  39. package/src/__tests__/tsconfig.json +14 -0
  40. package/src/__tests__/useObjectHook.test.tsx +158 -0
  41. package/src/__tests__/useObjectRender.test.tsx +630 -0
  42. package/src/__tests__/useQueryHook.test.tsx +209 -0
  43. package/src/__tests__/useQueryRender.test.tsx +463 -0
  44. package/src/cachedCollection.ts +210 -0
  45. package/src/cachedObject.ts +164 -0
  46. package/src/helpers.ts +60 -0
  47. package/src/index.tsx +130 -0
  48. package/src/runtime.d.ts +31 -0
  49. package/src/types.ts +92 -0
  50. package/src/useObject.tsx +227 -0
  51. package/src/useQuery.tsx +205 -0
  52. package/src/useRealm.tsx +41 -0
@@ -0,0 +1,154 @@
1
+ ////////////////////////////////////////////////////////////////////////////
2
+ //
3
+ // Copyright 2024 Realm Inc.
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ //
17
+ ////////////////////////////////////////////////////////////////////////////
18
+
19
+ import { act } from "@testing-library/react-native";
20
+ import { EstimateProgressNotificationCallback, ProgressRealmPromise, Realm } from "realm";
21
+ import { sleep } from "./helpers";
22
+
23
+ /**
24
+ * Mocks {@link Realm.ProgressRealmPromise} with a custom
25
+ * promise completion and progress handler.
26
+ */
27
+ export class MockedProgressRealmPromise extends Promise<Realm> implements ProgressRealmPromise {
28
+ private progressHandler?: (callback: EstimateProgressNotificationCallback) => void;
29
+ private cancelHandler?: () => void;
30
+ private realmPromise!: Promise<Realm>;
31
+
32
+ constructor(
33
+ getRealm: () => Promise<Realm>,
34
+ options?: {
35
+ progress?: (callback: EstimateProgressNotificationCallback) => void;
36
+ cancel?: () => void;
37
+ },
38
+ ) {
39
+ let realmPromise: Promise<Realm>;
40
+ super((resolve) => {
41
+ realmPromise = getRealm();
42
+ realmPromise.then((realm) => resolve(realm));
43
+ });
44
+ // @ts-expect-error realmPromise value will be assigned right away
45
+ this.realmPromise = realmPromise;
46
+ this.progressHandler = options?.progress;
47
+ this.cancelHandler = options?.cancel;
48
+ }
49
+
50
+ get [Symbol.toStringTag]() {
51
+ return "MockedProgressRealmPromise";
52
+ }
53
+
54
+ cancel = () => {
55
+ if (!this.cancelHandler) {
56
+ throw new Error("cancel handler not set");
57
+ }
58
+ this.cancelHandler();
59
+ };
60
+
61
+ then<TResult1 = Realm, TResult2 = never>(
62
+ onfulfilled?: ((value: Realm) => TResult1 | PromiseLike<TResult1>) | null | undefined,
63
+ onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,
64
+ ): Promise<TResult1 | TResult2> {
65
+ return this.realmPromise.then(onfulfilled, onrejected);
66
+ }
67
+
68
+ progress = (callback: EstimateProgressNotificationCallback) => {
69
+ if (!this.progressHandler) {
70
+ throw new Error("progress handler not set");
71
+ }
72
+ this.progressHandler(callback);
73
+ return this;
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Mocked {@link ProgressRealmPromise} which resolves after a set delay.
79
+ * If `options.progressValues` is specified, passes it through an
80
+ * equal interval to `Realm.open(...).progress(...)` callback.
81
+ */
82
+ export class MockedProgressRealmPromiseWithDelay extends MockedProgressRealmPromise {
83
+ public currentProgressIndex = 0;
84
+ public progressValues: number[] | undefined;
85
+ private progressTimeout: NodeJS.Timeout | undefined;
86
+
87
+ constructor(
88
+ options: {
89
+ delay?: number;
90
+ /** Progress values which the `Realm.open(...).progress(...)` will receive in an equal interval. */
91
+ progressValues?: number[];
92
+ } = {},
93
+ ) {
94
+ const { progressValues, delay = 100 } = options;
95
+ super(
96
+ async () => {
97
+ await sleep(delay);
98
+ return new Realm();
99
+ },
100
+ {
101
+ progress: (callback) => {
102
+ this.progressTimeout = callMockedProgressNotifications(callback, delay, progressValues);
103
+ },
104
+ cancel: () => clearTimeout(this.progressTimeout),
105
+ },
106
+ );
107
+ this.progressValues = progressValues;
108
+ }
109
+ }
110
+
111
+ /** Calls given callbacks with progressValues in an equal interval */
112
+ export function callMockedProgressNotifications(
113
+ callback: EstimateProgressNotificationCallback,
114
+ timeFrame: number,
115
+ progressValues: number[] = [0, 0.25, 0.5, 0.75, 1],
116
+ ): NodeJS.Timeout {
117
+ let progressIndex = 0;
118
+ let progressInterval: NodeJS.Timeout | undefined = undefined;
119
+ const sendProgress = () => {
120
+ // Uses act as this causes a component state update.
121
+ act(() => callback(progressValues[progressIndex]));
122
+ progressIndex++;
123
+
124
+ if (progressIndex >= progressValues.length) {
125
+ // Send the next progress update in equidistant time
126
+ clearInterval(progressInterval);
127
+ }
128
+ };
129
+ progressInterval = setInterval(sendProgress, timeFrame / (progressValues.length + 1));
130
+ sendProgress();
131
+ return progressInterval;
132
+ }
133
+
134
+ /**
135
+ * Mocks the Realm.open operation with a delayed, predictable Realm creation.
136
+ * @returns Promise which resolves when the Realm is opened.
137
+ */
138
+ export function mockRealmOpen(
139
+ progressRealmPromise: MockedProgressRealmPromise = new MockedProgressRealmPromiseWithDelay(),
140
+ ): MockedProgressRealmPromise {
141
+ const delayedRealmOpen = jest.spyOn(Realm, "open");
142
+ delayedRealmOpen.mockImplementation(() => progressRealmPromise);
143
+ return progressRealmPromise;
144
+ }
145
+
146
+ /** Mocks a {@link Realm} with a custom syncSession and returns it. */
147
+ export function mockSyncedRealm({ syncSession }: { syncSession: Partial<Realm["syncSession"]> }) {
148
+ const mockedSyncedRealm = new Realm();
149
+
150
+ //@ts-expect-error The mock currently supports supplying a subset of methods
151
+ jest.replaceProperty(mockedSyncedRealm, "syncSession", syncSession);
152
+
153
+ return mockedSyncedRealm;
154
+ }
@@ -0,0 +1,76 @@
1
+ ////////////////////////////////////////////////////////////////////////////
2
+ //
3
+ // Copyright 2024 Realm Inc.
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ //
17
+ ////////////////////////////////////////////////////////////////////////////
18
+
19
+ import React, { Profiler, ProfilerOnRenderCallback } from "react";
20
+ import { renderHook, RenderHookResult, RenderHookOptions } from "@testing-library/react-native";
21
+
22
+ function generateProfilerId() {
23
+ const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
24
+ return `test-${nonce}`;
25
+ }
26
+
27
+ type RenderEvent = {
28
+ phase: "mount" | "update";
29
+ actualDuration: number;
30
+ baseDuration: number;
31
+ };
32
+
33
+ type ProfileWrapper = {
34
+ wrapper: React.ComponentType<React.PropsWithChildren>;
35
+ renders: RenderEvent[];
36
+ };
37
+
38
+ function createProfilerWrapper(Parent: undefined | React.ComponentType<React.PropsWithChildren>): ProfileWrapper {
39
+ const renders: RenderEvent[] = [];
40
+ const id = generateProfilerId();
41
+ const handleRender: ProfilerOnRenderCallback = (
42
+ id,
43
+ phase,
44
+ actualDuration,
45
+ baseDuration,
46
+ startTime,
47
+ commitTime,
48
+ interactions,
49
+ ) => {
50
+ renders.push({ phase, actualDuration, baseDuration });
51
+ };
52
+
53
+ const Wrapper: React.ComponentType<React.PropsWithChildren> = ({ children }) => (
54
+ <Profiler id={id} onRender={handleRender} children={children} />
55
+ );
56
+
57
+ return {
58
+ wrapper: Parent
59
+ ? ({ children }) => (
60
+ <Parent>
61
+ <Wrapper children={children} />
62
+ </Parent>
63
+ )
64
+ : Wrapper,
65
+ renders,
66
+ };
67
+ }
68
+
69
+ export function profileHook<Result, Props>(
70
+ callback: (props: Props) => Result,
71
+ options?: RenderHookOptions<Props>,
72
+ ): RenderHookResult<Result, Props> & { renders: RenderEvent[] } {
73
+ const { wrapper, renders } = createProfilerWrapper(options?.wrapper);
74
+ const result = renderHook<Result, Props>(callback, { ...options, wrapper });
75
+ return { ...result, renders };
76
+ }
@@ -0,0 +1,22 @@
1
+ ////////////////////////////////////////////////////////////////////////////
2
+ //
3
+ // Copyright 2024 Realm Inc.
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ //
17
+ ////////////////////////////////////////////////////////////////////////////
18
+
19
+ import Realm from "realm";
20
+ Realm.flags.THROW_ON_GLOBAL_REALM = true;
21
+ // Enable calling Realm.clearTestState()
22
+ Realm.flags.ALLOW_CLEAR_TEST_STATE = true;
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "types": [
5
+ "jest",
6
+ "node",
7
+ "@testing-library/react-native/extend-expect",
8
+ ]
9
+ },
10
+ "include": [
11
+ "."
12
+ ],
13
+ "exclude": []
14
+ }
@@ -0,0 +1,158 @@
1
+ ////////////////////////////////////////////////////////////////////////////
2
+ //
3
+ // Copyright 2021 Realm Inc.
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ //
17
+ ////////////////////////////////////////////////////////////////////////////
18
+
19
+ import Realm from "realm";
20
+ import { renderHook } from "@testing-library/react-native";
21
+ import assert from "node:assert";
22
+
23
+ import { createUseObject } from "../useObject";
24
+ import { createRealmTestContext } from "./createRealmTestContext";
25
+ import { profileHook } from "./profileHook";
26
+
27
+ const dogSchema: Realm.ObjectSchema = {
28
+ name: "dog",
29
+ primaryKey: "_id",
30
+ properties: {
31
+ _id: "int",
32
+ name: "string",
33
+ age: "int",
34
+ },
35
+ };
36
+
37
+ interface IDog {
38
+ _id: number;
39
+ name: string;
40
+ age: number;
41
+ }
42
+
43
+ const context = createRealmTestContext({ schema: [dogSchema] });
44
+ const useObject = createUseObject(context.useRealm);
45
+
46
+ const testDataSet = [
47
+ { _id: 4, name: "Vincent", age: 5 },
48
+ { _id: 5, name: "River", age: 25 },
49
+ { _id: 6, name: "Schatzi", age: 13 },
50
+ ];
51
+
52
+ describe("useObject", () => {
53
+ beforeEach(() => {
54
+ const realm = context.openRealm();
55
+ realm.write(() => {
56
+ realm.deleteAll();
57
+ testDataSet.forEach((data) => {
58
+ realm.create("dog", data);
59
+ });
60
+ });
61
+ });
62
+
63
+ afterEach(() => {
64
+ context.cleanup();
65
+ });
66
+
67
+ it("can retrieve a single object using useObject", () => {
68
+ const [, river] = testDataSet;
69
+ const { result } = renderHook(() => useObject<IDog>("dog", river._id));
70
+ const object = result.current;
71
+ expect(object).toMatchObject(river);
72
+ });
73
+
74
+ describe("missing objects", () => {
75
+ it("return null", () => {
76
+ const { result } = renderHook(() => useObject<IDog>("dog", 12));
77
+ expect(result.current).toEqual(null);
78
+ });
79
+
80
+ it("rerenders and return object once created", () => {
81
+ const { write, realm } = context;
82
+ const { result, renders } = profileHook(() => useObject<IDog>("dog", 12));
83
+ expect(renders).toHaveLength(1);
84
+ expect(result.current).toEqual(null);
85
+ write(() => {
86
+ realm.create<IDog>("dog", { _id: 12, name: "Lassie", age: 32 });
87
+ });
88
+ expect(renders).toHaveLength(2);
89
+ expect(result.current?.name).toEqual("Lassie");
90
+ });
91
+ });
92
+
93
+ describe("key-path filtering", () => {
94
+ it("can filter notifications using key-path array", async () => {
95
+ const [vincent] = testDataSet;
96
+ const { write } = context;
97
+ const { result, renders } = profileHook(() => useObject<IDog>("dog", vincent._id, ["name"]));
98
+ expect(renders).toHaveLength(1);
99
+ expect(result.current).toMatchObject(vincent);
100
+ // Update the name and expect a re-render
101
+ write(() => {
102
+ assert(result.current);
103
+ result.current.name = "Vince!";
104
+ });
105
+ expect(renders).toHaveLength(2);
106
+ expect(result.current?.name).toEqual("Vince!");
107
+ // Update the age and don't expect a re-render
108
+ write(() => {
109
+ assert(result.current);
110
+ result.current.age = 5;
111
+ });
112
+ expect(renders).toHaveLength(2);
113
+ });
114
+
115
+ it("can filter notifications using key-path string", async () => {
116
+ const [vincent] = testDataSet;
117
+ const { write } = context;
118
+ const { result, renders } = profileHook(() => useObject<IDog>("dog", vincent._id, "age"));
119
+ expect(renders).toHaveLength(1);
120
+ expect(result.current).toMatchObject(vincent);
121
+ // Update the name and expect a re-render
122
+ write(() => {
123
+ assert(result.current);
124
+ result.current.age = 13;
125
+ });
126
+ expect(renders).toHaveLength(2);
127
+ expect(result.current?.age).toEqual(13);
128
+ // Update the age and don't expect a re-render
129
+ write(() => {
130
+ assert(result.current);
131
+ result.current.name = "Vince!";
132
+ });
133
+ expect(renders).toHaveLength(2);
134
+ });
135
+ });
136
+
137
+ describe("passing options object as argument", () => {
138
+ it("rerenders on updates", () => {
139
+ const { write, realm } = context;
140
+
141
+ const vincent = realm.objectForPrimaryKey("dog", 4);
142
+ assert(vincent);
143
+
144
+ const { result, renders } = profileHook(() => useObject<IDog>({ type: "dog", primaryKey: 4, keyPaths: "name" }));
145
+ expect(renders).toHaveLength(1);
146
+ write(() => {
147
+ vincent.name = "Vinnie";
148
+ });
149
+ expect(renders).toHaveLength(2);
150
+ expect(result.current?.name).toEqual("Vinnie");
151
+ // Expect no renders when updating a property outside key-paths
152
+ write(() => {
153
+ vincent.age = 30;
154
+ });
155
+ expect(renders).toHaveLength(2);
156
+ });
157
+ });
158
+ });