esp-js-react 8.1.1-next.0 → 9.0.0-beta.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 (49) hide show
  1. package/.dist/esp-react.esm.js +713 -0
  2. package/.dist/esp-react.esm.js.map +1 -0
  3. package/.dist/esp-react.js +696 -775
  4. package/.dist/esp-react.js.map +1 -1
  5. package/.dist/esp-react.min.js +20 -3
  6. package/.dist/esp-react.min.js.map +1 -1
  7. package/.dist/typings/connectableComponent.d.ts +5 -6
  8. package/.dist/typings/espApp.d.ts +25 -0
  9. package/.dist/typings/espEventBusContextProvider.d.ts +41 -0
  10. package/.dist/typings/espModulesContext.d.ts +3 -0
  11. package/.dist/typings/espStoreContextProvider.d.ts +62 -0
  12. package/.dist/typings/index.d.ts +13 -9
  13. package/.dist/typings/regionView.d.ts +19 -0
  14. package/.dist/typings/useSyncModelWithSelector.d.ts +9 -16
  15. package/README.md +62 -22
  16. package/package.json +53 -45
  17. package/.dist/esp-react.min.js.LICENSE.txt +0 -9
  18. package/.dist/typings/connect.d.ts +0 -8
  19. package/.dist/typings/espModelContextProvider.d.ts +0 -63
  20. package/.dist/typings/espRouterContextProvider.d.ts +0 -54
  21. package/.dist/typings/polimer/polimerModelBuilderExtentsions.d.ts +0 -6
  22. package/.dist/typings/viewBinder.d.ts +0 -13
  23. package/.dist/typings/viewBindingDecorator.d.ts +0 -34
  24. package/.yarnignore +0 -15
  25. package/docs/images/esp-agile-demo.gif +0 -0
  26. package/jest.config.js +0 -19
  27. package/src/connect.tsx +0 -27
  28. package/src/connectableComponent.tsx +0 -99
  29. package/src/espModelContextProvider.tsx +0 -101
  30. package/src/espRouterContextProvider.tsx +0 -97
  31. package/src/index.ts +0 -68
  32. package/src/polimer/polimerModelBuilderExtentsions.ts +0 -36
  33. package/src/useSyncModelWithSelector.ts +0 -223
  34. package/src/viewBinder.tsx +0 -51
  35. package/src/viewBindingDecorator.ts +0 -113
  36. package/tests/connectableComponentTests.tsx +0 -477
  37. package/tests/espModelContextProviderTests.tsx +0 -150
  38. package/tests/espRouterContextProviderTests.tsx +0 -56
  39. package/tests/indexTests.ts +0 -47
  40. package/tests/testApi/asserts.ts +0 -102
  41. package/tests/testApi/routerSpy.ts +0 -24
  42. package/tests/testApi/testApi.tsx +0 -100
  43. package/tests/testApi/testModel.ts +0 -43
  44. package/tests/testApi/useStoreReceivedProps.ts +0 -14
  45. package/tests/testApi/viewFactory.tsx +0 -31
  46. package/tests/useSyncModelWithSelectorTests.tsx +0 -330
  47. package/tests/viewBinderTests.tsx +0 -61
  48. package/tsconfig.json +0 -14
  49. package/webpack.config.js +0 -27
@@ -1,101 +0,0 @@
1
- import * as React from 'react';
2
- import {DefaultModelAddress, Router} from 'esp-js';
3
- import {useContext, useCallback, createContext, PropsWithChildren} from 'react';
4
- import {useRouter} from './espRouterContextProvider';
5
-
6
- export const GetModelIdContext = createContext<string>(null);
7
- /**
8
- * Returns a function to get the ID of the model connected at a higher point in the V-DOM.
9
- *
10
- * To use this, please ensure your V-DOM has the EspModelContextProvider at a higher node.
11
- */
12
- export const useGetModelId = () => useContext(GetModelIdContext);
13
-
14
- export const GetModelContext = createContext<object>(null);
15
- /**
16
- * Returns a function which will return the model connected at a higher point in the V-DOM.
17
- *
18
- * To use this, please ensure your V-DOM has the EspModelContextProvider at a higher node.
19
- */
20
- export const useGetModel = <TModel,>() => useContext(GetModelContext) as TModel;
21
-
22
- export type PublishModelEventDelegate = { (eventType: string, event: any): void; (eventData: {eventType: string, event: any}): void; };
23
- const createPublishModelEvent = (router: Router, modelId: string) => {
24
- function publishModelEvent(eventType: string, event: any): void;
25
- function publishModelEvent(eventData: {eventType: string, event: any}): void;
26
- function publishModelEvent(...args: any[]) {
27
- if (args.length === 1) {
28
- router.publishEvent(modelId, args[0].eventType, args[0].event);
29
- } else {
30
- router.publishEvent(modelId, args[0], args[1]);
31
- }
32
- }
33
- return publishModelEvent;
34
- };
35
- export const PublishModelEventContext = createContext<PublishModelEventDelegate>(null);
36
-
37
- /**
38
- * Returns a function which can be used to publish an event to the model connected at a higher point in the V-DOM.
39
- *
40
- * Effectively, this is a version of usePublishEvent() which closes over the relevant modelId.
41
- *
42
- * To use this, please ensure your V-DOM has the EspModelContextProvider at a higher node.
43
- */
44
- export const usePublishModelEvent = () => useContext(PublishModelEventContext);
45
-
46
- export type PublishModelEventWithEntityKeyDelegate = {(entityKey: string, eventType: string, event: any): void; (eventData: {entityKey: string, eventType: string, event: any}): void; };
47
- const createPublishModelEventWithEntityKey = (router: Router, modelId: string) => {
48
- function publishModelEventWithEntityKey(entityKey: string, eventType: string, event: any): void;
49
- function publishModelEventWithEntityKey(eventData: {entityKey: string, eventType: string, event: any}): void;
50
- function publishModelEventWithEntityKey(...args: any[]) {
51
- if (args.length === 1) {
52
- router.publishEvent(new DefaultModelAddress(modelId, args[0].entityKey), args[0].eventType, args[0].event);
53
- } else {
54
- router.publishEvent(new DefaultModelAddress(modelId, args[0]), args[1], args[2]);
55
- }
56
- }
57
- return publishModelEventWithEntityKey;
58
- };
59
- export const PublishModelEventWithEntityKeyContext = createContext<PublishModelEventWithEntityKeyDelegate>(null);
60
- /**
61
- * Returns a function which can be used to publish an event to the model connected at a higher point in the V-DOM, allows an entityKey to be specified.
62
- *
63
- * Effectively, this is a version of usePublishEvent() which closes over the modelId.
64
- *
65
- * To use this, please ensure your V-DOM has the EspModelContextProvider at a higher node.
66
- */
67
- export const usePublishModelEventWithEntityKey = () => useContext(PublishModelEventWithEntityKeyContext);
68
-
69
- export interface EspModelContextProviderProps {
70
- modelId: string;
71
- model?: any;
72
- }
73
-
74
- /**
75
- * Sets up various ESP context so ESP hooks are available below this point in the V-DOM
76
- *
77
- * To use this, please ensure your V-DOM has the EspRouterContextProvider at a higher node.
78
- * @param modelId
79
- * @param children
80
- * @param model
81
- * @constructor
82
- */
83
- export const EspModelContextProvider = ({modelId, children, model}: PropsWithChildren<EspModelContextProviderProps>) => {
84
- const router = useRouter();
85
- // modelId may have been set by a higher level version of this component, so we try and get it from context if it's not set by props.
86
- let modelIdFromContext = useGetModelId();
87
- modelId = modelId || modelIdFromContext;
88
- const publishModelEvent: PublishModelEventDelegate = useCallback(createPublishModelEvent(router, modelId), [router, modelId]);
89
- const publishModelEventWithEntityKey: PublishModelEventWithEntityKeyDelegate = useCallback(createPublishModelEventWithEntityKey(router, modelId), [router, modelId]);
90
- return (
91
- <GetModelIdContext.Provider value={modelId}>
92
- <PublishModelEventContext.Provider value={publishModelEvent}>
93
- <PublishModelEventWithEntityKeyContext.Provider value={publishModelEventWithEntityKey}>
94
- <GetModelContext.Provider value={model}>
95
- {children}
96
- </GetModelContext.Provider>
97
- </PublishModelEventWithEntityKeyContext.Provider>
98
- </PublishModelEventContext.Provider>
99
- </GetModelIdContext.Provider>
100
- );
101
- };
@@ -1,97 +0,0 @@
1
- // notice_start
2
- /*
3
- * Copyright 2015 Dev Shop Limited
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
- // notice_end
18
-
19
- import * as React from 'react';
20
- import {ModelAddress, Router} from 'esp-js';
21
- import {PropsWithChildren, createContext, useContext, useCallback} from 'react';
22
-
23
- export const RouterContext = createContext<Router>(null);
24
-
25
- /**
26
- * Get the esp Router from context.
27
- *
28
- * To use this, please ensure your V-DOM has the EspRouterContextProvider at a higher node:
29
- *
30
- * <EspRouterContextProvider router={router}>
31
- * <YourComponents />
32
- * </EspRouterContextProvider>
33
- */
34
- export const useRouter = () => {
35
- return useContext(RouterContext);
36
- };
37
-
38
- export type PublishEventDelegate = {(modelIdOrModelAddress: string | ModelAddress, eventType: string, event: any): void; (eventData: { address: string | ModelAddress, eventType: string, event: any }): void; };
39
- const createPublishEvent = (router: Router) => {
40
- function publishEvent(modelIdOrModelAddress: string | ModelAddress, eventType: string, event: any): void;
41
- function publishEvent(eventData: { address: string | ModelAddress, eventType: string, event: any }): void;
42
- function publishEvent(...args: any[]): void {
43
- if (args.length === 1) {
44
- router.publishEvent(args[0].address, args[0].eventType, args[0].event);
45
- } else {
46
- router.publishEvent(args[0], args[1], args[2]);
47
- }
48
- }
49
- return publishEvent;
50
- };
51
- export const PublishEventContext = createContext<PublishEventDelegate>(null);
52
-
53
- /**
54
- * Returns a function which can be used to publish an event.
55
- *
56
- * To use this, please ensure your V-DOM has the EspRouterContextProvider at a higher node:
57
- *
58
- * <EspRouterContextProvider router={router}>
59
- * <YourComponents />
60
- * </EspRouterContextProvider>
61
- */
62
- export const usePublishEvent = () => useContext(PublishEventContext);
63
-
64
- export type EspRouterContextProviderProps = PropsWithChildren<{ router: Router; }>;
65
-
66
- /**
67
- * Used to set the router on the RouterContext making it available to components down the tree via the useRouter() hook.
68
- *
69
- * Also sets up the usePublishEvent() hook so nested components can publish to the router.
70
- */
71
- export const EspRouterContextProvider = ({children, router}: EspRouterContextProviderProps) => {
72
- // Router may have been set by a higher level version of this component, so we try and get it from context if it's not set by props.
73
- let routerFromContext = useRouter();
74
- router = router || routerFromContext;
75
- const publishEvent: PublishEventDelegate = useCallback(createPublishEvent(router), [router]);
76
- return (
77
- <RouterContext.Provider value={router}>
78
- <PublishEventContext.Provider value={publishEvent}>
79
- {children}
80
- </PublishEventContext.Provider>
81
- </RouterContext.Provider>
82
- );
83
- };
84
-
85
- /**
86
- * Used to set the router on the RouterContext making it available to components down the tree (via useRouter()).
87
- *
88
- * @deprecated use EspRouterContextProvider
89
- */
90
- export const RouterProvider = EspRouterContextProvider;
91
-
92
- /**
93
- * Props for RouterProvider
94
- *
95
- * @deprecated use EspRouterContextProviderProps
96
- */
97
- export type RouterProviderProps = EspRouterContextProviderProps;
package/src/index.ts DELETED
@@ -1,68 +0,0 @@
1
- // notice_start
2
- /*
3
- * Copyright 2015 Dev Shop Limited
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
- // notice_end
18
- //
19
-
20
- // import for side effects
21
- import './polimer/polimerModelBuilderExtentsions';
22
-
23
- export {ViewBinder} from './viewBinder';
24
- export {viewBinding, DEFAULT_VIEW_KEY} from './viewBindingDecorator';
25
- export {createViewForModel} from './viewBindingDecorator';
26
- export {
27
- connect,
28
- ConnectableComponentFactory
29
- } from './connect';
30
- export {
31
- CreatePublishEventProps,
32
- MapModelToProps,
33
- ConnectableComponentProps,
34
- ConnectableComponentChildProps,
35
- ConnectableComponent,
36
- } from './connectableComponent';
37
- export {
38
- useSyncModelWithSelector,
39
- SyncModelWithSelectorOptionsBuilder,
40
- syncModelWithSelectorOptions,
41
- SyncModelWithSelectorOptions,
42
- SyncModelWithSelectorEqualityFn,
43
- } from './useSyncModelWithSelector';
44
- export {
45
- RouterProvider,
46
- RouterProviderProps,
47
- EspRouterContextProvider,
48
- EspRouterContextProviderProps,
49
- RouterContext,
50
- useRouter,
51
- PublishEventDelegate,
52
- PublishEventContext,
53
- usePublishEvent,
54
- } from './espRouterContextProvider';
55
- export {
56
- useGetModelId,
57
- GetModelIdContext,
58
- useGetModel,
59
- GetModelContext,
60
- PublishModelEventDelegate,
61
- PublishModelEventContext,
62
- usePublishModelEvent,
63
- PublishModelEventWithEntityKeyDelegate,
64
- PublishModelEventWithEntityKeyContext,
65
- usePublishModelEventWithEntityKey,
66
- EspModelContextProvider,
67
- EspModelContextProviderProps,
68
- } from './espModelContextProvider';
@@ -1,36 +0,0 @@
1
- import {PolimerModelBuilder, PolimerModel} from 'esp-js-polimer';
2
- import {DEFAULT_VIEW_KEY, viewBinding} from '../viewBindingDecorator';
3
-
4
- declare module 'esp-js-polimer/.dist/typings/modelBuilderUpdater' {
5
- export interface PolimerModelBuilder<TModel> {
6
- withViewBindings?(view: any, displayContext?: string): PolimerModelBuilder<TModel>;
7
- }
8
- }
9
-
10
- interface ViewMappings {
11
- [displayContext: string]: any;
12
- }
13
-
14
- PolimerModelBuilder.prototype.withViewBindings = function (view: any, displayContext: string = DEFAULT_VIEW_KEY): PolimerModelBuilder<any> {
15
- let builder = this;
16
- // store some metadata on the builder which we'll use later to tack onto the model
17
- let viewMappings: ViewMappings = builder._viewMappings || { };
18
- viewMappings[displayContext] = view;
19
- builder._viewMappings = viewMappings;
20
- return this;
21
- };
22
-
23
- // we need to replace the registerWithRouter in order to dynamically add the
24
- // @viewBinding decorator to it
25
- let registerWithRouter = PolimerModelBuilder.prototype.registerWithRouter;
26
- PolimerModelBuilder.prototype.registerWithRouter = function (): PolimerModel<any> {
27
- let builder = this;
28
- let model = registerWithRouter.call(builder);
29
- let viewMappings: ViewMappings = builder._viewMappings;
30
- if (viewMappings) {
31
- Object.keys(viewMappings).forEach(displayContext => {
32
- viewBinding(viewMappings[displayContext], displayContext)(model.constructor);
33
- });
34
- }
35
- return model;
36
- };
@@ -1,223 +0,0 @@
1
- import {useMemo} from 'react';
2
- import {useSyncExternalStoreWithSelector} from 'use-sync-external-store/with-selector';
3
- import {Logger, Router, utils} from 'esp-js';
4
- import {useRouter} from './espRouterContextProvider';
5
- import {useGetModelId} from './espModelContextProvider';
6
- import {PolimerModel} from 'esp-js-polimer';
7
-
8
- export type SyncModelWithSelectorEqualityFn<T> = (last: T, next: T) => boolean;
9
-
10
- export const logger = Logger.create('useSyncModelWithSelector');
11
-
12
- /**
13
- * Options affecting the subscription of the model to the Router.
14
- *
15
- * Use syncModelWithSelectorOptions() to create an instance of this type with sensible defaults.
16
- *
17
- * @param modelId - the modelId of the model to be observed via the esp Router.
18
- * @param tryPreSelectPolimerImmutableModel - if true, and the esp model is an esp-js-polimer model, the immutable model will be used when calling the selector.
19
- * @param equalityFn - Equality function which will be applied against TSelected, defaults to instance equality (a === b).
20
- */
21
- export type SyncModelWithSelectorOptions<TSelected> = {
22
- modelId?: string,
23
- tryPreSelectPolimerImmutableModel: boolean,
24
- equalityFn: SyncModelWithSelectorEqualityFn<TSelected>
25
- };
26
-
27
- /**
28
- * Convenience API to build SyncModelWithSelectorOptions<TSelected>, has sensible defaulting.
29
- */
30
- export interface SyncModelWithSelectorOptionsBuilder<TSelected> extends SyncModelWithSelectorOptions<TSelected> {
31
- /**
32
- * Sets the model ID
33
- * @param modelId - default if unset: undefined
34
- */
35
- setModelId(modelId: string): this;
36
-
37
- /**
38
- * If the model is a PolimerModel and this set true, PolimerModel.getImmutableModel() will be selected by default.
39
- * @param value - default if unset: true
40
- */
41
- setTryPreSelectPolimerImmutableModel(value: boolean): this;
42
-
43
- /**
44
- * Equality function used when comparing the last TSelected with the next.
45
- * @param fn - default if unset: obj instance equality (e.g. a===b)
46
- */
47
- setEqualityFn(fn: (a: TSelected, b: TSelected) => boolean): this;
48
- }
49
-
50
- /**
51
- * Convenience API to create SyncModelWithSelectorOptions
52
- */
53
- export const syncModelWithSelectorOptions = <TSelected>() => {
54
- let modelId = undefined;
55
- let equalityFn: SyncModelWithSelectorEqualityFn<TSelected> = (a: TSelected, b: TSelected) => a === b;
56
- let tryPreSelectPolimerImmutableModel = true;
57
- return {
58
- get modelId() {
59
- return modelId;
60
- },
61
- setModelId(value: string) {
62
- modelId = value;
63
- return this;
64
- },
65
- get equalityFn() {
66
- return equalityFn;
67
- },
68
- setEqualityFn(value: SyncModelWithSelectorEqualityFn<TSelected>) {
69
- equalityFn = value;
70
- return this;
71
- },
72
- get tryPreSelectPolimerImmutableModel() {
73
- return tryPreSelectPolimerImmutableModel;
74
- },
75
- setTryPreSelectPolimerImmutableModel(value: boolean) {
76
- tryPreSelectPolimerImmutableModel = value;
77
- return this;
78
- }
79
- } as SyncModelWithSelectorOptionsBuilder<TSelected>;
80
- };
81
-
82
- const checkArguments = (selector: (model: any) => any, options: SyncModelWithSelectorOptions<any> ) => {
83
- if (!utils.isFunction(selector)) {
84
- throw new Error('You must pass a selector function to useSyncModelWithSelector');
85
- }
86
- if (!utils.isObject(options)) {
87
- throw new Error('You must provide options when using useSyncModelWithSelector');
88
- }
89
- if (!utils.isFunction(options.equalityFn)) {
90
- throw new Error('You must provide an equalityFn when using useSyncModelWithSelector');
91
- }
92
- };
93
-
94
- /**
95
- * A hook which returns model state from the esp Router.
96
- *
97
- * This hooks wih observe updates and re-render the component if the model changes.
98
- *
99
- * To use this, please ensure your V-DOM has the EspRouterContextProvider at a higher node, and optionally EspModelContextProvider.
100
- *
101
- * @param selector - a function to select a selection of the model - the selector does not need to be memoized, this selector will be cached against the modelId.
102
- * @param options
103
- */
104
- export const useSyncModelWithSelector = <TModel, TSelected>(
105
- selector: (model: TModel) => TSelected,
106
- options: SyncModelWithSelectorOptions<TSelected> = syncModelWithSelectorOptions<TSelected>()
107
- ): TSelected => {
108
- checkArguments(selector, options);
109
- const router = useRouter();
110
- const modelIdFromContext = useGetModelId();
111
- const modelId = options?.modelId || modelIdFromContext;
112
- const tryPreSelectPolimerImmutableModel = options?.tryPreSelectPolimerImmutableModel;
113
- const equalityFn = options?.equalityFn;
114
- const dependencies = useMemo(
115
- () => {
116
- const canSubscribe = router && utils.isString(modelId) && router.isModelRegistered(modelId);
117
- if (canSubscribe) {
118
- return createSubscriptionState(router, modelId, selector, tryPreSelectPolimerImmutableModel);
119
- }
120
- return createNoopSubscriptionState();
121
- },
122
- // Don't add 'selector' to the dependency list as that will likely change unless the caller memoizes it.
123
- [router, modelId]
124
- );
125
-
126
- // Docs on useSyncExternalStore https://github.com/reactwg/react-18/discussions/86
127
- // Redux's usage of this: https://github.com/reduxjs/react-redux/blob/master/src/hooks/useSelector.ts
128
- // Code: https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js
129
- return useSyncExternalStoreWithSelector(
130
- dependencies.subscribe,
131
- dependencies.getSnapshot,
132
- undefined,
133
- dependencies.wrappedSelector,
134
- equalityFn,
135
- );
136
- };
137
-
138
- const createSubscriptionState = <TModel, TSelected>(
139
- router: Router,
140
- modelId: string,
141
- selector: (model: TModel) => TSelected,
142
- tryPreSelectPolimerImmutableModel: boolean
143
- ) => {
144
- // Because of how useSyncExternalStore works, there is an implicit dependency between the subscribe and getSnapshot functions.
145
- // When the subscription receives the new state from the Router, it can't pass this directly onto getSnapshot,
146
- // React calls that when it deems it needs to.
147
- // Given that, we need to cache the state which getSnapshot will return.
148
- //
149
- // Another edge case with useSyncExternalStore:
150
- // It will call getSnapshot before it calls subscribe, to account for this we need to fetch the model first.
151
- let currentModel: TModel;
152
- let onStateChanged: () => void = null;
153
- const modelSubscriptionDisposable = router
154
- .getModelObservable<TModel>(modelId)
155
- .subscribe(
156
- (m: any) => {
157
- // try and get the esp-js-polimer immutable model if possible, this should mutate when any state changes
158
- const nextModel = tryPreSelectPolimerImmutableModel && PolimerModel.isPolimerModel(m)
159
- ? m.getEspPolimerImmutableModel()
160
- // If the above didn't manage to get a polimer model,
161
- // we need to mutate to force useSyncExternalStoreWithSelector to pick up the change.
162
- // This should only affect older style OO models.
163
- : Object.create(m);
164
- warnIfModelInstanceHasNotChanged(modelId, currentModel, nextModel);
165
- currentModel = nextModel;
166
- if (onStateChanged) {
167
- onStateChanged();
168
- }
169
- }
170
- );
171
- return {
172
- subscribe: (stateChanged: () => void) => {
173
- onStateChanged = stateChanged;
174
- return () => {
175
- onStateChanged = null;
176
- currentModel = null;
177
- modelSubscriptionDisposable.dispose();
178
- };
179
- },
180
- // React expects getSnapshot to be immutable, it'll only re-render if the instance changes
181
- getSnapshot: () => {
182
- return currentModel;
183
- },
184
- // While getSnapshot needs to model to be immutable,
185
- // useSyncExternalStoreWithSelector builds on top of this, so the TSelected can defer to an equality check to determine if the change is propagated.
186
- // The selector here just maps the TSelected, useSyncExternalStoreWithSelector internally does the equality check.
187
- wrappedSelector: (snapshot: TModel) => {
188
- return snapshot
189
- ? selector(snapshot)
190
- : null;
191
- }
192
- };
193
- };
194
-
195
- const createNoopSubscriptionState = () => ({
196
- subscribe: () => {
197
- return () => {};
198
- },
199
- getSnapshot: () => null,
200
- wrappedSelector: () => null
201
- });
202
-
203
- const warnIfModelInstanceHasNotChanged = (modelId: string, lastModel: any, nextModel: string) => {
204
- if (process.env.NODE_ENV === 'production') {
205
- return;
206
- }
207
- if (utils.stringIsEmpty(modelId)) {
208
- return;
209
- }
210
- if (lastModel === nextModel) {
211
- let stack: string | undefined = undefined;
212
- try {
213
- // noinspection ExceptionCaughtLocallyJS
214
- throw new Error();
215
- } catch (e) {
216
- stack = (e as Error).stack;
217
- }
218
- logger.warn(
219
- `useSyncModelWithSelector had detected the latest model update hasn't mutated. This will cause odd render bugs. modelId: ${modelId}`,
220
- stack
221
- );
222
- }
223
- };
@@ -1,51 +0,0 @@
1
- // notice_start
2
- /*
3
- * Copyright 2015 Dev Shop Limited
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
- // notice_end
18
-
19
- import * as React from 'react';
20
- import {createViewForModel} from './viewBindingDecorator';
21
- import {useRouter} from './espRouterContextProvider';
22
-
23
- export interface ViewBinderProps {
24
- model: any;
25
- viewContext?: string;
26
- /**
27
- * ...rest props, these will be passed to the child
28
- */
29
- [key: string]: any;
30
- }
31
-
32
- /**
33
- * Takes a model with a @viewBinding decorator and dynamically crates the view specified by the decorator
34
- */
35
- export const ViewBinder: React.FC<ViewBinderProps> = ({model, viewContext, ...rest}) => {
36
- if (model) {
37
- const router = useRouter();
38
- const newProps = {
39
- model,
40
- router,
41
- ...rest
42
- };
43
- return createViewForModel(
44
- model,
45
- newProps,
46
- viewContext,
47
- null
48
- );
49
- }
50
- return null;
51
- };
@@ -1,113 +0,0 @@
1
- // notice_start
2
- /*
3
- * Copyright 2015 Dev Shop Limited
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
- // notice_end
18
-
19
- import * as React from 'react';
20
- import {Guard} from 'esp-js';
21
-
22
- export const DEFAULT_VIEW_KEY = 'default-view-key';
23
-
24
- function getMetadata(target) {
25
- if (!target._viewMetadata) {
26
- target._viewMetadata = new ViewMetadata();
27
- }
28
- return target._viewMetadata;
29
- }
30
-
31
- /**
32
- * Tries to get a view for the given model.
33
- *
34
- * It does this using the following order:
35
- * 1) If a @viewBinding decorator was used and a display context was given, try get a view for that
36
- * 2) Else if a view was explicitly provided use that
37
- * 3) Else if a @viewBinding decorator was used and there is a view associated with the default display context, use that view
38
- * @param model
39
- * @param props
40
- * @param displayContext
41
- * @param view
42
- */
43
- export function createViewForModel(model: any, props: object, displayContext: string, view: React.ComponentType) {
44
- let finalView: React.ComponentType = view; // default to that passed in, if any.
45
-
46
- // displayContext = displayContext || DEFAULT_VIEW_KEY;
47
- // the view decorator isn't on the instance, it's on the constructor function that created that instance
48
- if (model) {
49
- let constructorFunction = model.constructor;
50
- if (constructorFunction._viewMetadata) {
51
- let viewMetadata = constructorFunction._viewMetadata;
52
- if (displayContext && viewMetadata.hasRegisteredViewContext(displayContext)) {
53
- let viewMetadataRegistration = viewMetadata.viewRegistrations[displayContext];
54
- // we've found a view for the display context, use that
55
- finalView = viewMetadataRegistration.view;
56
- }
57
-
58
- // if we've not found a view yet, and one wasn't provided, is there a default one?
59
- if (!finalView && viewMetadata.hasRegisteredViewContext(DEFAULT_VIEW_KEY)) {
60
- let viewMetadataRegistration = viewMetadata.viewRegistrations[DEFAULT_VIEW_KEY];
61
- finalView = viewMetadataRegistration.view;
62
- }
63
- }
64
- }
65
- if (!finalView) {
66
- throw new Error(`No suitable view found for model id '${model.modelId}' using context '${displayContext}'`);
67
- }
68
- return React.createElement(finalView, props);
69
- }
70
-
71
- /**
72
- * An ES7 style decorator that associates a model with a view
73
- * @param view the react component that will be used to display this model
74
- * @param displayContext an optional context allowing for different views to display the same model
75
- * @returns {Function}
76
- */
77
- export function viewBinding(view: any, displayContext: string = DEFAULT_VIEW_KEY) {
78
- Guard.isDefined(view, 'view must be defined');
79
- Guard.isString(displayContext, 'displayContext must be a string');
80
- return function (target: any) {
81
- let viewMetadata = getMetadata(target);
82
- if (viewMetadata.hasRegisteredViewContext(displayContext)) {
83
- throw new Error(`Context ${displayContext} already registered for view`);
84
- }
85
- viewMetadata.viewRegistrations[displayContext] = new ViewMetadataRegistration(view, displayContext);
86
- };
87
- }
88
-
89
- export class ViewMetadata {
90
- private _viewRegistrations = {};
91
-
92
- get viewRegistrations() {
93
- return this._viewRegistrations;
94
- }
95
-
96
- hasRegisteredViewContext(displayContext) {
97
- return typeof this._viewRegistrations[displayContext] !== 'undefined';
98
- }
99
- }
100
-
101
- export class ViewMetadataRegistration {
102
-
103
- constructor(private _view, private _displayContext) {
104
- }
105
-
106
- get view() {
107
- return this._view;
108
- }
109
-
110
- get displayContext() {
111
- return this._displayContext;
112
- }
113
- }