@open-pioneer/reactivity 0.1.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # @open-pioneer/reactivity
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5d3aafd: Initial release.
8
+
9
+ You can use the hook `useReactiveSnapshot` to write React components that make use of the reactivity API of [@conterra/reactivity-core](https://www.npmjs.com/package/@conterra/reactivity-core).
10
+ Quick example:
11
+
12
+ ```tsx
13
+ export function YourComponent({ model }) {
14
+ // model is implemented using the reactivity API
15
+ const fullName = useReactiveSnapshot(() => {
16
+ return `${model.firstName} ${model.lastName}`;
17
+ }, [model]);
18
+
19
+ // Name is automatically kept up-to-date.
20
+ return <div>Hello {fullName}</div>;
21
+ }
22
+ ```
23
+
24
+ The reactivity API is not directly used in any trails packages at this time.
25
+ However, moving forward, most packages will use the reactivity API as _the_ common reactivity system.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # @open-pioneer/reactivity
2
+
3
+ This package provides hooks and helpers to work with the reactivity API provided by [@conterra/reactivity-core](https://www.npmjs.com/package/@conterra/reactivity-core).
4
+
5
+ > NOTE:
6
+ > This package and `@conterra/reactivity-core` are still actively being worked on.
7
+ > There may be breaking changes based on user feedback; stability can not yet be guaranteed.
8
+
9
+ ## Usage
10
+
11
+ ### Rendering reactive values
12
+
13
+ The hook `useReactiveSnapshot(callback, deps)` is integrated with the reactivity API of `@conterra/reactivity-core`.
14
+ The hook will continuously invoke the provided callback and return the current result.
15
+ For this mechanism to work, the values used inside the callback should be based on the reactivity API (or be declared as `deps`).
16
+
17
+ Example:
18
+
19
+ ```tsx
20
+ // YourComponent.tsx
21
+ import { useReactiveSnapshot } from "@open-pioneer/reactivity";
22
+ import { Model } from "./Model";
23
+
24
+ export interface YourComponentProps {
25
+ // Some model class or interface based on the reactivity API.
26
+ // In this case, the model has the properties `firstName` and `lastName`, both are (reactive) strings.
27
+ model: Model;
28
+ }
29
+
30
+ export function YourComponent({ model }: YourComponentProps) {
31
+ const fullName = useReactiveSnapshot(() => {
32
+ // You can compute arbitrary values based on your model, even objects or array.
33
+ // This callback is called whenever any dependency changed, this case if firstName or
34
+ // lastName are updated.
35
+ // Keep in mind that this callback should not have any side effects, because it may run any number of times.
36
+ return `${model.firstName} ${model.lastName}`;
37
+ }, [model]);
38
+
39
+ // Name is automatically kept up-to-date.
40
+ return <div>Hello {fullName}</div>;
41
+ }
42
+ ```
43
+
44
+ - `callback` is a function that accesses reactive values which are based on signals (see example below) and returns some computed _result_.
45
+ In the example above, we used the values of `firstName` and `lastName`.
46
+ The access to those values was tracked by `useReactiveSnapshot`; updates will result in the React component rendering with the updated `fullName`.
47
+ - `deps` are an array of React dependencies (such as props or local variables), very similar to `useEffect` or `useMemo`.
48
+ The hook cannot detect changes of values that are _not_ based on the reactivity API (such as react props), so they need to be listed here.
49
+ In this case we had to specify the `model` itself (it may change as well!) but not its properties.
50
+
51
+ To complete the example from above, here is the full source of a compatible `Model` implementation:
52
+
53
+ ```ts
54
+ // Model.ts
55
+ import { reactive } from "@conterra/reactivity-core";
56
+
57
+ export class Model {
58
+ // Private storage. Signals are not exposed in this example.
59
+ #firstName = reactive("John");
60
+ #lastName = reactive("Doe");
61
+
62
+ // Public getters to access the current values, with a convenient API.
63
+ get firstName(): string {
64
+ return this.#firstName.value;
65
+ }
66
+
67
+ get lastName(): string {
68
+ return this.#lastName.value;
69
+ }
70
+
71
+ // Update the name values.
72
+ // Any UI connected to the model via useReactiveSnapshot() will automatically update.
73
+ updateName(newFirstName: string, newLastName: string): void {
74
+ this.#firstName.value = newFirstName;
75
+ this.#lastName.value = newLastName;
76
+ }
77
+ }
78
+ ```
79
+
80
+ More details are available in this package's API documentation and the [README of @conterra/reactivity-core](https://www.npmjs.com/package/@conterra/reactivity-core).
81
+
82
+ ### ESLint configuration
83
+
84
+ You can use React's `exhaustive-deps` linting rule to check the dependencies of `useReactiveSnapshot` and `useComputed` (see [Documentation](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#advanced-configuration)).
85
+ This will apply the same rules used by `useEffect` etc. to the configured hooks.
86
+
87
+ Example:
88
+
89
+ ```jsonc
90
+ // .eslintrc
91
+ {
92
+ // ...
93
+ "rules": {
94
+ // ...
95
+ "react-hooks/exhaustive-deps": [
96
+ "warn",
97
+ {
98
+ "additionalHooks": "(useReactiveSnapshot|useComputed)"
99
+ }
100
+ ]
101
+ }
102
+ }
103
+ ```
104
+
105
+ ## License
106
+
107
+ Apache-2.0 (see `LICENSE` file)
package/index.d.ts ADDED
@@ -0,0 +1,117 @@
1
+ import { ReadonlyReactive, Reactive } from "@conterra/reactivity-core";
2
+ import { DependencyList } from "react";
3
+ /**
4
+ * Creates a new signal with the initial value `undefined`.
5
+ *
6
+ * The initial value will only be applied on the very first call to this hook.
7
+ * The same signal instance will be returned when this hook is called on the next render.
8
+ * This is very similar (in concept) to React's builtin `useState` hook.
9
+ *
10
+ * @example
11
+ *
12
+ * ```jsx
13
+ * function YourComponent() {
14
+ * const mySignal = useReactive();
15
+ * const someEventHandler = () => {
16
+ * // Update the value after some event
17
+ * mySignal.value = "new value";
18
+ * };
19
+ *
20
+ * // Always returns the current value, re-renders if necessary.
21
+ * const currentValue = useReactiveValue(mySignal);
22
+ * }
23
+ * ```
24
+ */
25
+ export declare function useReactive<T>(): Reactive<T | undefined>;
26
+ /**
27
+ * Creates a new signal with the given initial value.
28
+ *
29
+ * @see {@link useReactive()}.
30
+ */
31
+ export declare function useReactive<T>(initialValue: T): Reactive<T>;
32
+ /**
33
+ * Creates a new computed signal that evaluates the given `compute` function.
34
+ *
35
+ * The hook returns the same signal for as long as `deps` remains the same.
36
+ * When `deps` change, a new signal will be created.
37
+ *
38
+ * @example
39
+ *
40
+ * Defining a simple computed value in your react component:
41
+ *
42
+ * ```jsx
43
+ * function MyComponent(props) {
44
+ * // Creates a computed value based on the given function.
45
+ * // The computed value will be re-created whenever one of the listed dependencies changes.
46
+ * // While the computed value can track all its _reactive_ dependencies automatically (`.value` reads etc.)
47
+ * // the reactive value itself used here might change (different props) - this cannot be detected automatically.
48
+ * const computed = useComputed(() => props.someReactive.value * 2, [props.someReactive]);
49
+ *
50
+ * // Watches on `computed` and returns its current value.
51
+ * const currentValue = useReactiveValue(computed);
52
+ * }
53
+ * ```
54
+ *
55
+ * > If the body of your compute function depends on non-reactive values (such as react props or state),
56
+ * > list those values in the `deps` array.
57
+ *
58
+ * @see {@link useReactiveValue()}
59
+ * @see {@link useReactiveSnapshot()}
60
+ */
61
+ export declare function useComputed<T>(compute: () => T, deps: DependencyList): ReadonlyReactive<T>;
62
+ /**
63
+ * Watches the given reactive object and returns its current value.
64
+ *
65
+ * > NOTE: The return value of this hook should be considered read-only.
66
+ *
67
+ * @see {@link useComputed()}
68
+ */
69
+ export declare function useReactiveValue<T>(reactive: ReadonlyReactive<T>): T;
70
+ /**
71
+ * Evaluates the `compute` function and returns its result.
72
+ *
73
+ * The body of the compute function is tracked: it
74
+ * will be re-evaluated whenever its reactive dependencies change.
75
+ * The outer react component will re-render whenever `compute` returns a new value.
76
+ *
77
+ * > NOTE: The return value of this hook should be considered read-only.
78
+ *
79
+ * @example
80
+ *
81
+ * Simple Example:
82
+ *
83
+ * ```jsx
84
+ * // A reactive signal from anywhere (global data, props, ...).
85
+ * const name = reactive("User");
86
+ *
87
+ * function YourComponent() {
88
+ * const nameSnapshot = useReactiveSnapshot(() => name.value);
89
+ * // snapshot is automatically up to date
90
+ * }
91
+ * ```
92
+ *
93
+ * @example
94
+ *
95
+ * Multiple values, with props:
96
+ *
97
+ * ```jsx
98
+ * function YourComponent({firstName, lastName}) {
99
+ * // You can use complex expressions in your compute function,
100
+ * // just like in a computed signal.
101
+ * // React-dependencies used in the callback must be listed in the second argument,
102
+ * // just like when using `useMemo()` or `useEffect`.
103
+ * const snapshot = useReactiveSnapshot(() => {
104
+ * return {
105
+ * firstName: firstName.value,
106
+ * lastName: lastName.value,
107
+ * fullName: `${firstName.value} ${lastName.value}`
108
+ * };
109
+ * }, [firstName, lastName]);
110
+ * // snapshot.firstName, snapshot.lastName, snapshot.fullName are available and up to date
111
+ * }
112
+ * ```
113
+ *
114
+ * @see
115
+ * This hook is based on {@link useComputed()} and {@link useReactiveValue()}.
116
+ */
117
+ export declare function useReactiveSnapshot<T>(compute: () => T, deps: DependencyList): T;
package/index.js ADDED
@@ -0,0 +1,51 @@
1
+ import { reactive, computed, watch } from '@conterra/reactivity-core';
2
+ import { useMemo, useRef, useCallback, useSyncExternalStore, useDebugValue } from 'react';
3
+
4
+ function useReactive(initialValue) {
5
+ return useMemo(() => reactive(initialValue), []);
6
+ }
7
+ function useComputed(compute, deps) {
8
+ const computeRef = useRef(compute);
9
+ computeRef.current = compute;
10
+ const computedDeps = useComputedDeps(deps);
11
+ return useMemo(() => {
12
+ return computed(() => computeRef.current());
13
+ }, [computedDeps]);
14
+ }
15
+ function useReactiveValue(reactive2) {
16
+ const getSnapshot = useCallback(() => {
17
+ return reactive2.peek();
18
+ }, [reactive2]);
19
+ const subscribe = useCallback(
20
+ (cb) => {
21
+ const handle = watch(() => [reactive2.value], cb);
22
+ return () => handle.destroy();
23
+ },
24
+ [reactive2]
25
+ );
26
+ const value = useSyncExternalStore(subscribe, getSnapshot);
27
+ useDebugValue(value);
28
+ return value;
29
+ }
30
+ function useReactiveSnapshot(compute, deps) {
31
+ const computedSnapshot = useComputed(compute, deps);
32
+ const snapshot = useReactiveValue(computedSnapshot);
33
+ useDebugValue(snapshot);
34
+ return snapshot;
35
+ }
36
+ function useComputedDeps(deps) {
37
+ const computedDeps = useRef();
38
+ if (computedDeps.current == null || !shallowEqual(computedDeps.current, deps)) {
39
+ computedDeps.current = deps ?? [];
40
+ }
41
+ return computedDeps.current;
42
+ }
43
+ function shallowEqual(a, b) {
44
+ if (a === b) {
45
+ return true;
46
+ }
47
+ return a.length === (b?.length ?? 0) && a.every((v, i) => v === b[i]);
48
+ }
49
+
50
+ export { useComputed, useReactive, useReactiveSnapshot, useReactiveValue };
51
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { ReadonlyReactive, Reactive, computed, reactive, watch } from \"@conterra/reactivity-core\";\nimport {\n DependencyList,\n useCallback,\n useDebugValue,\n useMemo,\n useRef,\n useSyncExternalStore\n} from \"react\";\n\n/**\n * Creates a new signal with the initial value `undefined`.\n *\n * The initial value will only be applied on the very first call to this hook.\n * The same signal instance will be returned when this hook is called on the next render.\n * This is very similar (in concept) to React's builtin `useState` hook.\n *\n * @example\n *\n * ```jsx\n * function YourComponent() {\n * const mySignal = useReactive();\n * const someEventHandler = () => {\n * // Update the value after some event\n * mySignal.value = \"new value\";\n * };\n *\n * // Always returns the current value, re-renders if necessary.\n * const currentValue = useReactiveValue(mySignal);\n * }\n * ```\n */\nexport function useReactive<T>(): Reactive<T | undefined>;\n\n/**\n * Creates a new signal with the given initial value.\n *\n * @see {@link useReactive()}.\n */\nexport function useReactive<T>(initialValue: T): Reactive<T>;\n\nexport function useReactive<T>(initialValue?: T): Reactive<T | undefined> {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => reactive(initialValue), []);\n}\n\n/**\n * Creates a new computed signal that evaluates the given `compute` function.\n *\n * The hook returns the same signal for as long as `deps` remains the same.\n * When `deps` change, a new signal will be created.\n *\n * @example\n *\n * Defining a simple computed value in your react component:\n *\n * ```jsx\n * function MyComponent(props) {\n * // Creates a computed value based on the given function.\n * // The computed value will be re-created whenever one of the listed dependencies changes.\n * // While the computed value can track all its _reactive_ dependencies automatically (`.value` reads etc.)\n * // the reactive value itself used here might change (different props) - this cannot be detected automatically.\n * const computed = useComputed(() => props.someReactive.value * 2, [props.someReactive]);\n *\n * // Watches on `computed` and returns its current value.\n * const currentValue = useReactiveValue(computed);\n * }\n * ```\n *\n * > If the body of your compute function depends on non-reactive values (such as react props or state),\n * > list those values in the `deps` array.\n *\n * @see {@link useReactiveValue()}\n * @see {@link useReactiveSnapshot()}\n */\nexport function useComputed<T>(compute: () => T, deps: DependencyList): ReadonlyReactive<T> {\n const computeRef = useRef(compute);\n computeRef.current = compute;\n\n const computedDeps = useComputedDeps(deps);\n return useMemo(() => {\n computedDeps; // not really used, but computed must be recreated when this value changes\n return computed(() => computeRef.current());\n }, [computedDeps]);\n}\n\n/**\n * Watches the given reactive object and returns its current value.\n *\n * > NOTE: The return value of this hook should be considered read-only.\n *\n * @see {@link useComputed()}\n */\nexport function useReactiveValue<T>(reactive: ReadonlyReactive<T>): T {\n const getSnapshot = useCallback(() => {\n return reactive.peek();\n }, [reactive]);\n const subscribe = useCallback(\n (cb: () => void) => {\n const handle = watch(() => [reactive.value], cb);\n return () => handle.destroy();\n },\n [reactive]\n );\n const value = useSyncExternalStore(subscribe, getSnapshot);\n useDebugValue(value);\n return value;\n}\n\n/**\n * Evaluates the `compute` function and returns its result.\n *\n * The body of the compute function is tracked: it\n * will be re-evaluated whenever its reactive dependencies change.\n * The outer react component will re-render whenever `compute` returns a new value.\n *\n * > NOTE: The return value of this hook should be considered read-only.\n *\n * @example\n *\n * Simple Example:\n *\n * ```jsx\n * // A reactive signal from anywhere (global data, props, ...).\n * const name = reactive(\"User\");\n *\n * function YourComponent() {\n * const nameSnapshot = useReactiveSnapshot(() => name.value);\n * // snapshot is automatically up to date\n * }\n * ```\n *\n * @example\n *\n * Multiple values, with props:\n *\n * ```jsx\n * function YourComponent({firstName, lastName}) {\n * // You can use complex expressions in your compute function,\n * // just like in a computed signal.\n * // React-dependencies used in the callback must be listed in the second argument,\n * // just like when using `useMemo()` or `useEffect`.\n * const snapshot = useReactiveSnapshot(() => {\n * return {\n * firstName: firstName.value,\n * lastName: lastName.value,\n * fullName: `${firstName.value} ${lastName.value}`\n * };\n * }, [firstName, lastName]);\n * // snapshot.firstName, snapshot.lastName, snapshot.fullName are available and up to date\n * }\n * ```\n *\n * @see\n * This hook is based on {@link useComputed()} and {@link useReactiveValue()}.\n */\nexport function useReactiveSnapshot<T>(compute: () => T, deps: DependencyList): T {\n // We create an internal computed value that executes the compute function;\n // this way the implementation of `compute` is automatically tracked.\n // getSnapshot and subscribe simply watch the current value of that computed value.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const computedSnapshot = useComputed(compute, deps);\n const snapshot = useReactiveValue(computedSnapshot);\n useDebugValue(snapshot);\n return snapshot;\n}\n\nfunction useComputedDeps(deps: DependencyList): DependencyList {\n const computedDeps = useRef<DependencyList>();\n if (computedDeps.current == null || !shallowEqual(computedDeps.current, deps)) {\n computedDeps.current = deps ?? [];\n }\n return computedDeps.current;\n}\n\nfunction shallowEqual(a: DependencyList, b: DependencyList): boolean {\n if (a === b) {\n return true;\n }\n return a.length === (b?.length ?? 0) && a.every((v, i) => v === b![i]);\n}\n"],"names":["reactive"],"mappings":";;;AA2CO,SAAS,YAAe,YAA2C,EAAA;AAEtE,EAAA,OAAO,QAAQ,MAAM,QAAA,CAAS,YAAY,CAAA,EAAG,EAAE,CAAA,CAAA;AACnD,CAAA;AA+BgB,SAAA,WAAA,CAAe,SAAkB,IAA2C,EAAA;AACxF,EAAM,MAAA,UAAA,GAAa,OAAO,OAAO,CAAA,CAAA;AACjC,EAAA,UAAA,CAAW,OAAU,GAAA,OAAA,CAAA;AAErB,EAAM,MAAA,YAAA,GAAe,gBAAgB,IAAI,CAAA,CAAA;AACzC,EAAA,OAAO,QAAQ,MAAM;AAEjB,IAAA,OAAO,QAAS,CAAA,MAAM,UAAW,CAAA,OAAA,EAAS,CAAA,CAAA;AAAA,GAC9C,EAAG,CAAC,YAAY,CAAC,CAAA,CAAA;AACrB,CAAA;AASO,SAAS,iBAAoBA,SAAkC,EAAA;AAClE,EAAM,MAAA,WAAA,GAAc,YAAY,MAAM;AAClC,IAAA,OAAOA,UAAS,IAAK,EAAA,CAAA;AAAA,GACzB,EAAG,CAACA,SAAQ,CAAC,CAAA,CAAA;AACb,EAAA,MAAM,SAAY,GAAA,WAAA;AAAA,IACd,CAAC,EAAmB,KAAA;AAChB,MAAA,MAAM,SAAS,KAAM,CAAA,MAAM,CAACA,SAAS,CAAA,KAAK,GAAG,EAAE,CAAA,CAAA;AAC/C,MAAO,OAAA,MAAM,OAAO,OAAQ,EAAA,CAAA;AAAA,KAChC;AAAA,IACA,CAACA,SAAQ,CAAA;AAAA,GACb,CAAA;AACA,EAAM,MAAA,KAAA,GAAQ,oBAAqB,CAAA,SAAA,EAAW,WAAW,CAAA,CAAA;AACzD,EAAA,aAAA,CAAc,KAAK,CAAA,CAAA;AACnB,EAAO,OAAA,KAAA,CAAA;AACX,CAAA;AAiDgB,SAAA,mBAAA,CAAuB,SAAkB,IAAyB,EAAA;AAK9E,EAAM,MAAA,gBAAA,GAAmB,WAAY,CAAA,OAAA,EAAS,IAAI,CAAA,CAAA;AAClD,EAAM,MAAA,QAAA,GAAW,iBAAiB,gBAAgB,CAAA,CAAA;AAClD,EAAA,aAAA,CAAc,QAAQ,CAAA,CAAA;AACtB,EAAO,OAAA,QAAA,CAAA;AACX,CAAA;AAEA,SAAS,gBAAgB,IAAsC,EAAA;AAC3D,EAAA,MAAM,eAAe,MAAuB,EAAA,CAAA;AAC5C,EAAI,IAAA,YAAA,CAAa,WAAW,IAAQ,IAAA,CAAC,aAAa,YAAa,CAAA,OAAA,EAAS,IAAI,CAAG,EAAA;AAC3E,IAAa,YAAA,CAAA,OAAA,GAAU,QAAQ,EAAC,CAAA;AAAA,GACpC;AACA,EAAA,OAAO,YAAa,CAAA,OAAA,CAAA;AACxB,CAAA;AAEA,SAAS,YAAA,CAAa,GAAmB,CAA4B,EAAA;AACjE,EAAA,IAAI,MAAM,CAAG,EAAA;AACT,IAAO,OAAA,IAAA,CAAA;AAAA,GACX;AACA,EAAA,OAAO,CAAE,CAAA,MAAA,MAAY,CAAG,EAAA,MAAA,IAAU,CAAM,CAAA,IAAA,CAAA,CAAE,KAAM,CAAA,CAAC,CAAG,EAAA,CAAA,KAAM,CAAM,KAAA,CAAA,CAAG,CAAC,CAAC,CAAA,CAAA;AACzE;;;;"}
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "type": "module",
3
+ "name": "@open-pioneer/reactivity",
4
+ "version": "0.1.0",
5
+ "description": "Provides integration for the reactivity API.",
6
+ "keywords": [
7
+ "open-pioneer-trails"
8
+ ],
9
+ "homepage": "https://github.com/open-pioneer",
10
+ "license": "Apache-2.0",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/open-pioneer/trails-core-packages",
14
+ "directory": "src/packages/reactivity"
15
+ },
16
+ "peerDependencies": {
17
+ "react": "^18.3.1",
18
+ "@conterra/reactivity-core": "^0.4.0"
19
+ },
20
+ "exports": {
21
+ "./package.json": "./package.json",
22
+ ".": {
23
+ "import": "./index.js",
24
+ "types": "./index.d.ts"
25
+ }
26
+ },
27
+ "openPioneerFramework": {
28
+ "services": [],
29
+ "i18n": {
30
+ "languages": []
31
+ },
32
+ "ui": {
33
+ "references": []
34
+ },
35
+ "properties": [],
36
+ "packageFormatVersion": "1.0.0"
37
+ }
38
+ }