esp-js-react 8.0.3-next.0 → 8.0.5-next.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/src/index.ts CHANGED
@@ -40,13 +40,12 @@ export {
40
40
  ConnectableComponent,
41
41
  } from './connectableComponent';
42
42
  export {
43
- UseModelSelector,
44
- useModelSelector,
45
- EditableModelSelectorOptions,
46
- modelSelectorOptions,
47
- ModelSelectorOptions,
48
- ModelSelectorEqualityFn,
49
- } from './useModelSelector';
43
+ useSyncModelWithSelector,
44
+ SyncModelWithSelectorOptionsBuilder,
45
+ syncModelWithSelectorOptions,
46
+ SyncModelWithSelectorOptions,
47
+ SyncModelWithSelectorEqualityFn,
48
+ } from './useSyncModelWithSelector';
50
49
  export {
51
50
  RouterProvider,
52
51
  RouterProviderProps,
@@ -60,10 +59,8 @@ export {
60
59
  } from './espRouterContextProvider';
61
60
  export {
62
61
  useGetModelId,
63
- GetModelIdDelegate,
64
62
  GetModelIdContext,
65
63
  useGetModel,
66
- GetModelDelegate,
67
64
  GetModelContext,
68
65
  PublishModelEventDelegate,
69
66
  PublishModelEventContext,
@@ -0,0 +1,208 @@
1
+ import {useMemo} from 'react';
2
+ import {useSyncExternalStoreWithSelector} from 'use-sync-external-store/with-selector';
3
+ import {Router, utils} from 'esp-js';
4
+ import {useRouter} from './espRouterContextProvider';
5
+ import {useGetModelId} from './espModelContextProvider';
6
+ import {tryGetPolimerImmutableModel} from './polimer/getEspPolimerImmutableModel';
7
+
8
+ export type SyncModelWithSelectorEqualityFn<T> = (last: T, next: T) => boolean;
9
+
10
+ /**
11
+ * Options affecting the subscription of the model to the Router.
12
+ *
13
+ * Use syncModelWithSelectorOptions() to create an instance of this type with sensible defaults.
14
+ *
15
+ * @param modelId - the modelId of the model to be observed via the esp Router.
16
+ * @param tryPreSelectPolimerImmutableModel - if true, and the esp model is an esp-js-polimer model, the immutable model will be used when calling the selector.
17
+ * @param equalityFn - Equality function which will be applied against TSelected, defaults to instance equality (a === b).
18
+ */
19
+ export type SyncModelWithSelectorOptions<TSelected> = {
20
+ modelId?: string,
21
+ tryPreSelectPolimerImmutableModel: boolean,
22
+ equalityFn: SyncModelWithSelectorEqualityFn<TSelected>
23
+ };
24
+
25
+ /**
26
+ * Convenience API to build SyncModelWithSelectorOptions<TSelected>, has sensible defaulting.
27
+ */
28
+ export interface SyncModelWithSelectorOptionsBuilder<TSelected> extends SyncModelWithSelectorOptions<TSelected> {
29
+ /**
30
+ * Sets the model ID
31
+ * @param modelId - default if unset: undefined
32
+ */
33
+ setModelId(modelId: string): this;
34
+
35
+ /**
36
+ * If the model is a PolimerModel and this set true, PolimerModel.getImmutableModel() will be selected by default.
37
+ * @param value - default if unset: true
38
+ */
39
+ setTryPreSelectPolimerImmutableModel(value: boolean): this;
40
+
41
+ /**
42
+ * Equality function used when comparing the last TSelected with the next.
43
+ * @param fn - default if unset: obj instance equality (e.g. a===b)
44
+ */
45
+ setEqualityFn(fn: (a: TSelected, b: TSelected) => boolean): this;
46
+ }
47
+
48
+ /**
49
+ * Convenience API to create SyncModelWithSelectorOptions
50
+ */
51
+ export const syncModelWithSelectorOptions = <TSelected>() => {
52
+ let modelId = undefined;
53
+ let equalityFn: SyncModelWithSelectorEqualityFn<TSelected> = (a: TSelected, b: TSelected) => a === b;
54
+ let tryPreSelectPolimerImmutableModel = true;
55
+ return {
56
+ get modelId() {
57
+ return modelId;
58
+ },
59
+ setModelId(value: string) {
60
+ modelId = value;
61
+ return this;
62
+ },
63
+ get equalityFn() {
64
+ return equalityFn;
65
+ },
66
+ setEqualityFn(value: SyncModelWithSelectorEqualityFn<TSelected>) {
67
+ equalityFn = value;
68
+ return this;
69
+ },
70
+ get tryPreSelectPolimerImmutableModel() {
71
+ return tryPreSelectPolimerImmutableModel;
72
+ },
73
+ setTryPreSelectPolimerImmutableModel(value: boolean) {
74
+ tryPreSelectPolimerImmutableModel = value;
75
+ return this;
76
+ }
77
+ } as SyncModelWithSelectorOptionsBuilder<TSelected>;
78
+ };
79
+
80
+ const checkArguments = (selector: (model: any) => any, options: SyncModelWithSelectorOptions<any> ) => {
81
+ if (!utils.isFunction(selector)) {
82
+ throw new Error('You must pass a selector function to useSyncModelWithSelector');
83
+ }
84
+ if (!utils.isObject(options)) {
85
+ throw new Error('You must provide options when using useSyncModelWithSelector');
86
+ }
87
+ if (!utils.isFunction(options.equalityFn)) {
88
+ throw new Error('You must provide an equalityFn when using useSyncModelWithSelector');
89
+ }
90
+ };
91
+
92
+ /**
93
+ * A hook which returns model state from the esp Router.
94
+ *
95
+ * This hooks wih observe updates and re-render the component if the model changes.
96
+ *
97
+ * To use this, please ensure your V-DOM has the EspRouterContextProvider at a higher node, and optionally EspModelContextProvider.
98
+ *
99
+ * @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.
100
+ * @param options
101
+ */
102
+ export const useSyncModelWithSelector = <TModel, TSelected>(
103
+ selector: (model: TModel) => TSelected,
104
+ options: SyncModelWithSelectorOptions<TSelected> = syncModelWithSelectorOptions<TSelected>()
105
+ ): TSelected => {
106
+ checkArguments(selector, options);
107
+ const router = useRouter();
108
+ const modelIdFromContext = useGetModelId();
109
+ const modelId = options?.modelId || modelIdFromContext;
110
+ const tryPreSelectPolimerImmutableModel = options?.tryPreSelectPolimerImmutableModel;
111
+ const equalityFn = options?.equalityFn;
112
+ const dependencies = useMemo(
113
+ () => {
114
+ const canSubscribe = router && utils.isString(modelId) && router.isModelRegistered(modelId);
115
+ if (canSubscribe) {
116
+ return createSubscriptionState(router, modelId, selector, tryPreSelectPolimerImmutableModel);
117
+ }
118
+ return createNoopSubscriptionState();
119
+ },
120
+ // Don't add 'selector' to the dependency list as that will likely change unless the caller memoizes it.
121
+ [router, modelId]
122
+ );
123
+
124
+ // Docs on useSyncExternalStore https://github.com/reactwg/react-18/discussions/86
125
+ // Redux's usage of this: https://github.com/reduxjs/react-redux/blob/master/src/hooks/useSelector.ts
126
+ // Code: https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js
127
+ return useSyncExternalStoreWithSelector(
128
+ dependencies.subscribe,
129
+ dependencies.getSnapshot,
130
+ undefined,
131
+ dependencies.wrappedSelector,
132
+ // equalityFn can't be cached (needs to be a new fn each time)
133
+ // It seems that if it is, you get the last value regardless of if dependencies (and it's associated functions) changes.
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
+ // ESP will always dispatch the model when you initially observe it, because we pre-fetched it, the first updated is ignored below.
152
+ const selectModelOrPolimerModel = (m: any): TModel => {
153
+ // try use get the esp-js-polimer immutable model if possible.
154
+ const nextModel = tryPreSelectPolimerImmutableModel
155
+ ? tryGetPolimerImmutableModel(m)
156
+ : m;
157
+ // If the above didn't manage to get a polimer model,
158
+ // we need to mutate to force useSyncExternalStoreWithSelector to pick up the change.
159
+ // This should only affect older style OO models.
160
+ let modelHasNotMutated = nextModel === m;
161
+ return modelHasNotMutated
162
+ ? Object.create(nextModel)
163
+ : nextModel;
164
+ };
165
+ let isFirstRun = true;
166
+ let model: TModel = selectModelOrPolimerModel(router.getModel(modelId));
167
+ return {
168
+ subscribe: (stateChanged: () => void) => {
169
+ const modelSubscriptionDisposable = router
170
+ .getModelObservable<TModel>(modelId)
171
+ .map(m => selectModelOrPolimerModel(m))
172
+ .subscribe(
173
+ (m: any) => {
174
+ if (isFirstRun) {
175
+ isFirstRun = false;
176
+ return;
177
+ }
178
+ model = m;
179
+ stateChanged();
180
+ }
181
+ );
182
+ return () => {
183
+ model = null;
184
+ modelSubscriptionDisposable.dispose();
185
+ };
186
+ },
187
+ // React expects getSnapshot to be immutable, it'll only re-render if the instance changes
188
+ getSnapshot: () => {
189
+ return model;
190
+ },
191
+ // While getSnapshot needs to model to be immutable,
192
+ // useSyncExternalStoreWithSelector builds on top of this, so the TSelected can defer to an equality check to determine if the change is propagated.
193
+ // The selector here just maps the TSelected, useSyncExternalStoreWithSelector internally does the equality check.
194
+ wrappedSelector: (snapshot: TModel) => {
195
+ return snapshot
196
+ ? selector(snapshot)
197
+ : null;
198
+ }
199
+ };
200
+ };
201
+
202
+ const createNoopSubscriptionState = () => ({
203
+ subscribe: () => {
204
+ return () => {};
205
+ },
206
+ getSnapshot: () => null,
207
+ wrappedSelector: () => null
208
+ });
@@ -28,8 +28,8 @@ describe('index exports', () => {
28
28
  expect(espReact.createViewForModel).toBeDefined();
29
29
  expect(espReact.connect).toBeDefined();
30
30
  expect(espReact.ConnectableComponent).toBeDefined();
31
- expect(espReact.useModelSelector).toBeDefined();
32
- expect(espReact.modelSelectorOptions).toBeDefined();
31
+ expect(espReact.useSyncModelWithSelector).toBeDefined();
32
+ expect(espReact.syncModelWithSelectorOptions).toBeDefined();
33
33
  expect(espReact.RouterProvider).toBeDefined();
34
34
  expect(espReact.EspRouterContextProvider).toBeDefined();
35
35
  expect(espReact.RouterContext).toBeDefined();
@@ -5,8 +5,10 @@ import {RouterSpy} from './routerSpy';
5
5
  import {TestPropStore} from './useStoreReceivedProps';
6
6
 
7
7
  export type ViewAsserts = {
8
- valueIs(expected: string): ViewAsserts;
9
8
  modelIdIs(expected: string): ViewAsserts
9
+ modelIdIsNotInDom(): ViewAsserts
10
+ valueIs(expected: string): ViewAsserts;
11
+ valueIsNotInDom(): ViewAsserts;
10
12
  propIs(propName: string, expected: string): ViewAsserts
11
13
  viewNameElementTextIs(viewName: string);
12
14
  htmlElementInnerTextIs(elementsTestId: string, expectedText: string): ViewAsserts
@@ -19,11 +21,21 @@ export const viewAsserts = (renderResult: RenderResult) => {
19
21
  expect(idElement).toHaveTextContent(expected);
20
22
  return this;
21
23
  },
24
+ modelIdIsNotInDom() {
25
+ let idElement = renderResult.queryByTestId('modelIdDisplay');
26
+ expect(idElement).not.toBeInTheDocument();
27
+ return this;
28
+ },
22
29
  valueIs(expected: string) {
23
30
  let valueElement = renderResult.getByTestId('valueDisplay');
24
31
  expect(valueElement).toHaveTextContent(expected);
25
32
  return this;
26
33
  },
34
+ valueIsNotInDom() {
35
+ let idElement = renderResult.queryByTestId('valueDisplay');
36
+ expect(idElement).not.toBeInTheDocument();
37
+ return this;
38
+ },
27
39
  propIs(propName: string, expected: string) {
28
40
  let span = renderResult.getByTestId('span-with-props-as-attributes');
29
41
  let attributeName = `data-${propName}`;
@@ -2,7 +2,7 @@ import {useTestPropStore} from './useStoreReceivedProps';
2
2
  import * as React from 'react';
3
3
 
4
4
  export const viewFactory = (name: string) => {
5
- return (props: { modelId: string; value: string, [key: string]: any }) => {
5
+ return (props: { modelId?: string; value?: string, [key: string]: any }) => {
6
6
  let testPropStore = useTestPropStore();
7
7
  testPropStore.pushProps(props);
8
8
  return (
@@ -1,15 +1,16 @@
1
1
  import 'jest';
2
2
  import * as React from 'react';
3
3
  import {act} from 'react';
4
- import {modelSelectorOptions, useModelSelector} from '../src';
4
+ import {EspModelContextProvider, EspRouterContextProvider, syncModelWithSelectorOptions, useSyncModelWithSelector} from '../src';
5
5
  import {TestModel, TestModelImmutableState} from './testApi/testModel';
6
- import {ViewMetadata} from './testApi/viewFactory';
6
+ import {viewFactory, ViewMetadata} from './testApi/viewFactory';
7
7
  import {routerAsserts} from './testApi/asserts';
8
8
  import {testApi, TestApi} from './testApi/testApi';
9
+ import {TestPropStoreContext} from './testApi/useStoreReceivedProps';
9
10
 
10
11
  type SelectedObject = { id: string, value: string };
11
12
 
12
- describe('useModelSelector', () => {
13
+ describe('useSyncModelWithSelector', () => {
13
14
  let api: TestApi;
14
15
 
15
16
  beforeEach(() => {
@@ -20,7 +21,7 @@ describe('useModelSelector', () => {
20
21
  const modelId = 'modelId';
21
22
 
22
23
  const View = () => {
23
- const valuesObj = useModelSelector<TestModelImmutableState, SelectedObject>(
24
+ const valuesObj = useSyncModelWithSelector<TestModelImmutableState, SelectedObject>(
24
25
  model => {
25
26
  return {id: model.modelId, value: model.value};
26
27
  },
@@ -57,9 +58,9 @@ describe('useModelSelector', () => {
57
58
  const modelId = 'modelId';
58
59
 
59
60
  const View = () => {
60
- const values: string[] = useModelSelector<TestModelImmutableState, string[]>(
61
+ const values: string[] = useSyncModelWithSelector<TestModelImmutableState, string[]>(
61
62
  model => [model.modelId, model.value],
62
- modelSelectorOptions().setModelId(modelId)
63
+ syncModelWithSelectorOptions().setModelId(modelId)
63
64
  );
64
65
  if (!values) {
65
66
  return;
@@ -85,15 +86,15 @@ describe('useModelSelector', () => {
85
86
  const modelId = 'modelId';
86
87
 
87
88
  const View = () => {
88
- const values = useModelSelector<TestModelImmutableState, SelectedObject>(
89
+ const values = useSyncModelWithSelector<TestModelImmutableState, SelectedObject>(
89
90
  model => ({id: model.modelId, value: model.value}),
90
- modelSelectorOptions<SelectedObject>()
91
+ syncModelWithSelectorOptions<SelectedObject>()
91
92
  .setEqualityFn((a, b) => {
92
93
  if (!a) {
93
94
  return false; // first time
94
95
  }
95
96
  // delegate to model, set via the test, to see if we're 'equal'
96
- // If this returns true, useModelSelector internally assume the last snapshot is the same thus doesn't propagate the last snapshot.
97
+ // If this returns true, useSyncModelWithSelector internally assume the last snapshot is the same thus doesn't propagate the last snapshot.
97
98
  return b.value === 'assume-no-change';
98
99
  })
99
100
  );
@@ -139,9 +140,9 @@ describe('useModelSelector', () => {
139
140
  const modelId2 = 'modelId2';
140
141
 
141
142
  const View = (props: {modelId: string}) => {
142
- const values = useModelSelector<TestModelImmutableState, SelectedObject>(
143
+ const values = useSyncModelWithSelector<TestModelImmutableState, SelectedObject>(
143
144
  model => ({id: model.modelId, value: model.value}),
144
- modelSelectorOptions().setModelId(props.modelId)
145
+ syncModelWithSelectorOptions().setModelId(props.modelId)
145
146
  );
146
147
  if (!values) {
147
148
  return;
@@ -171,8 +172,8 @@ describe('useModelSelector', () => {
171
172
  .valueIs('initial-value');
172
173
  api.doReRender(View, undefined);
173
174
  api.asserts.view
174
- .modelIdIs('')
175
- .valueIs('');
175
+ .modelIdIsNotInDom()
176
+ .valueIsNotInDom();
176
177
  api.setupTestModel(modelId2);
177
178
  api.doReRender(View, modelId2);
178
179
  api.asserts.view
@@ -191,12 +192,12 @@ describe('useModelSelector', () => {
191
192
  const modelId = 'modelId';
192
193
 
193
194
  const View = () => {
194
- const values: string[] = useModelSelector<TestModel, string[]>(
195
+ const values: string[] = useSyncModelWithSelector<TestModel, string[]>(
195
196
  model => {
196
197
  // here we're expecting to receive a TestModel, not testModelInstance[GetEspPolimerImmutableModelConsts.HandlerFunctionName]()
197
198
  return [model.state.modelId, model.state.value];
198
199
  },
199
- modelSelectorOptions().setTryPreSelectPolimerImmutableModel(false)
200
+ syncModelWithSelectorOptions().setTryPreSelectPolimerImmutableModel(false)
200
201
  );
201
202
  if (!values) {
202
203
  return;
@@ -221,9 +222,9 @@ describe('useModelSelector', () => {
221
222
  const modelId = 'modelId';
222
223
 
223
224
  const View = () => {
224
- const model: TestModel = useModelSelector<TestModel, TestModel>(
225
+ const model: TestModel = useSyncModelWithSelector<TestModel, TestModel>(
225
226
  m => m,
226
- modelSelectorOptions().setTryPreSelectPolimerImmutableModel(false)
227
+ syncModelWithSelectorOptions().setTryPreSelectPolimerImmutableModel(false)
227
228
  );
228
229
  if (!model) {
229
230
  return;
@@ -252,4 +253,78 @@ describe('useModelSelector', () => {
252
253
  .valueIs('updated');
253
254
  });
254
255
  });
256
+
257
+ describe('noop argument edge cases', () => {
258
+ const View = viewFactory('View1');
259
+
260
+ it('falsey router', () => {
261
+ api.doRender((
262
+ <TestPropStoreContext.Provider value={api.propStore}>
263
+ <EspRouterContextProvider router={undefined}>
264
+ <EspModelContextProvider modelId={'some-modelId'}>
265
+ <View />,
266
+ </EspModelContextProvider>
267
+ </EspRouterContextProvider>
268
+ </TestPropStoreContext.Provider>
269
+ ));
270
+ api.asserts.props
271
+ .receivedPropCountIs(1)
272
+ .propAtIndexHasModelId(0, undefined)
273
+ .propAtIndex(0, props => {
274
+ expect(props.modelId).not.toBeDefined();
275
+ expect(props.value).not.toBeDefined();
276
+ });
277
+ });
278
+
279
+ it('falsey modelId', () => {
280
+ api.doRender((
281
+ <TestPropStoreContext.Provider value={api.propStore}>
282
+ <EspRouterContextProvider router={api.router}>
283
+ <EspModelContextProvider modelId={undefined}>
284
+ <View />,
285
+ </EspModelContextProvider>
286
+ </EspRouterContextProvider>
287
+ </TestPropStoreContext.Provider>
288
+ ));
289
+ api.asserts.props
290
+ .receivedPropCountIs(1)
291
+ .propAtIndexHasModelId(0, undefined)
292
+ .propAtIndex(0, props => {
293
+ expect(props.modelId).not.toBeDefined();
294
+ expect(props.value).not.toBeDefined();
295
+ });
296
+ });
297
+ });
298
+
299
+ describe('argument checking', () => {
300
+ it('throws if selector incorrect', () => {
301
+ expect(() => {
302
+ useSyncModelWithSelector(null, syncModelWithSelectorOptions());
303
+ }).toThrow(new Error('You must pass a selector function to useSyncModelWithSelector'));
304
+ expect(() => {
305
+ useSyncModelWithSelector(undefined, syncModelWithSelectorOptions());
306
+ }).toThrow(new Error('You must pass a selector function to useSyncModelWithSelector'));
307
+ expect(() => {
308
+ const x: any = {};
309
+ useSyncModelWithSelector(x, syncModelWithSelectorOptions());
310
+ }).toThrow(new Error('You must pass a selector function to useSyncModelWithSelector'));
311
+ });
312
+ it('throws if options incorrect', () => {
313
+ expect(() => {
314
+ useSyncModelWithSelector((m) => m, null);
315
+ }).toThrow(new Error('You must provide options when using useSyncModelWithSelector'));
316
+ expect(() => {
317
+ useSyncModelWithSelector((m) => m, syncModelWithSelectorOptions().setEqualityFn(null));
318
+ }).toThrow(new Error('You must provide an equalityFn when using useSyncModelWithSelector'));
319
+ expect(() => {
320
+ useSyncModelWithSelector(
321
+ (m) => m,
322
+ {
323
+ modelId: '',
324
+ equalityFn: null,
325
+ tryPreSelectPolimerImmutableModel: true
326
+ });
327
+ }).toThrow(new Error('You must provide an equalityFn when using useSyncModelWithSelector'));
328
+ });
329
+ });
255
330
  });
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  viewBinding,
3
- ViewBinder, ViewBinderConnectable
3
+ ViewBinder,
4
4
  } from '../src';
5
5
  import {testApi, TestApi} from './testApi/testApi';
6
6
  import * as React from 'react';
@@ -1,183 +0,0 @@
1
- import {useMemo} from 'react';
2
- import {useSyncExternalStoreWithSelector} from 'use-sync-external-store/with-selector';
3
- import {Guard, utils} from 'esp-js';
4
- import {useRouter} from './espRouterContextProvider';
5
- import {useGetModelId} from './espModelContextProvider';
6
- import {tryGetPolimerImmutableModel} from './polimer/getEspPolimerImmutableModel';
7
-
8
- export type ModelSelectorEqualityFn<T> = (last: T, next: T) => boolean;
9
-
10
- /**
11
- * Options affecting the subscription of the model to the Router.
12
- *
13
- * Use modelSelectorOptions() to create an instance of this type with sensible defaults.
14
- *
15
- * @param modelId - the modelId of the model to be observed via the esp Router.
16
- * @param tryPreSelectPolimerImmutableModel - if true, and the esp model is an esp-js-polimer model, the immutable model will be used when calling the selector.
17
- * @param equalityFn - Equality function which will be applied against TSelected, defaults to instance equality (a === b).
18
- */
19
- export type ModelSelectorOptions<TSelected> = {
20
- modelId?: string,
21
- tryPreSelectPolimerImmutableModel: boolean,
22
- equalityFn: ModelSelectorEqualityFn<TSelected>
23
- };
24
-
25
- /**
26
- * Convenience API to build ModelSelectorOptions<TSelected>, has sensible defaulting.
27
- */
28
- export interface EditableModelSelectorOptions<TSelected> extends ModelSelectorOptions<TSelected> {
29
- /**
30
- * Sets the model ID
31
- * @param modelId - default if unset: undefined
32
- */
33
- setModelId(modelId: string): this;
34
-
35
- /**
36
- * If the model is a PolimerModel and this set true, PolimerModel.getImmutableModel() will be selected by default.
37
- * @param value - default if unset: true
38
- */
39
- setTryPreSelectPolimerImmutableModel(value: boolean): this;
40
-
41
- /**
42
- * Equality function used when comparing the last TSelected with the next.
43
- * @param fn - default if unset: obj instance equality (e.g. a===b)
44
- */
45
- setEqualityFn(fn: (a: TSelected, b: TSelected) => boolean): this;
46
- }
47
-
48
- /**
49
- * Convenience API to create ModelSelectorOptions
50
- */
51
- export const modelSelectorOptions = <TSelected>() => {
52
- let modelId = undefined;
53
- let equalityFn: ModelSelectorEqualityFn<TSelected> = (a: TSelected, b: TSelected) => a === b;
54
- let tryPreSelectPolimerImmutableModel = true;
55
- return {
56
- get modelId() {
57
- return modelId;
58
- },
59
- setModelId(value: string) {
60
- modelId = value;
61
- return this;
62
- },
63
- get equalityFn() {
64
- return equalityFn;
65
- },
66
- setEqualityFn(value: ModelSelectorEqualityFn<TSelected>) {
67
- equalityFn = value;
68
- return this;
69
- },
70
- get tryPreSelectPolimerImmutableModel() {
71
- return tryPreSelectPolimerImmutableModel;
72
- },
73
- setTryPreSelectPolimerImmutableModel(value: boolean) {
74
- tryPreSelectPolimerImmutableModel = value;
75
- return this;
76
- }
77
- } as EditableModelSelectorOptions<TSelected>;
78
- };
79
-
80
- /**
81
- * A hook which returns model state from the esp Router.
82
- *
83
- * This hooks wih observe updates and re-render the component if the model changes.
84
- *
85
- * To use this, please ensure your V-DOM has the EspRouterContextProvider at a higher node, and optionally EspModelContextProvider.
86
- *
87
- * @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.
88
- * @param options
89
- */
90
- export type UseModelSelector = <TModel, TSelected>(
91
- selector: (model: TModel) => TSelected,
92
- options?: ModelSelectorOptions<TSelected>
93
- ) => TSelected;
94
-
95
- export const useModelSelector: UseModelSelector = <TModel, TSelected>(
96
- selector: (model: TModel) => TSelected,
97
- options: ModelSelectorOptions<TSelected> = modelSelectorOptions<TSelected>()
98
- ) => {
99
- Guard.isFunction(selector, 'You must pass a selector function to connectSelector');
100
- const router = useRouter();
101
- const modelId = options?.modelId || useGetModelId();
102
- const tryPreSelectPolimerImmutableModel = options?.tryPreSelectPolimerImmutableModel;
103
- const equalityFn = options?.equalityFn;
104
- const dependencies = useMemo(
105
- () => {
106
- // Because of how useSyncExternalStore works, there is an implicit dependency between the subscribe and getSnapshot functions.
107
- // When the subscription receives the new state from the Router, it can't pass this directly onto getSnapshot, React calls that when it deems it needs to.
108
- // Given that, we need to cache the state which getSnapshot will return.
109
- //
110
- // It's not ideal but shouldn't be a problem as here we've wrapped all these dependent functions inside a single useMemo()
111
- let model: TModel = null;
112
- return {
113
- subscribe: (stateChanged: () => void) => {
114
- const modelSubscriptionDisposable = router
115
- .getModelObservable(modelId)
116
- .subscribe(
117
- (m: any) => {
118
- // try and get a submodel to render
119
- const nextModel = tryPreSelectPolimerImmutableModel
120
- ? tryGetPolimerImmutableModel(m)
121
- : m;
122
- // if the above didn't manage to get a submodel,
123
- // we need to mutate to force useSyncExternalStoreWithSelector to pick up the change
124
- model = nextModel === m
125
- ? Object.create(nextModel)
126
- : nextModel;
127
- stateChanged();
128
- }
129
- );
130
- return () => {
131
- model = null;
132
- modelSubscriptionDisposable.dispose();
133
- };
134
- },
135
- // React expects getSnapshot to be immutable, it'll only re-render if the instance changes
136
- getSnapshot: () => {
137
- return model;
138
- },
139
- // While getSnapshot needs to model to be immutable,
140
- // useSyncExternalStoreWithSelector builds on top of this, so the TSelected can defer to an equality check to determine if the change is propagated.
141
- // The selector here just maps the TSelected, useSyncExternalStoreWithSelector internally does the equality check.
142
- wrappedSelector: (snapshot: TModel) => {
143
- // The first time this renders, react calls getSnapshot and the selector before the router has pushed a change.
144
- // In that case, there is no state for any component to process, therefore, we return null;
145
- return snapshot
146
- ? selector(snapshot)
147
- : null;
148
- }
149
- };
150
- },
151
- // Don't cache check against 'selector' argument as that will likely change unless the caller memoizes it.
152
- [router, modelId]
153
- );
154
-
155
- // If we don't have a modelId, we still need to return a hook so React doesn't complain.
156
- // Additionally, we need to let the above expiration (dependencies) run to unsubscribe from any previous subscription.
157
- if (utils.stringIsEmpty(modelId)) {
158
- return useSyncExternalStoreWithSelector(
159
- noopSubscription.subscribe,
160
- noopSubscription.getSnapshot,
161
- undefined,
162
- noopSubscription.wrappedSelector,
163
- equalityFn
164
- );
165
- }
166
-
167
- // Docs on useSyncExternalStore https://github.com/reactwg/react-18/discussions/86
168
- // Redux's usage of this: https://github.com/reduxjs/react-redux/blob/master/src/hooks/useSelector.ts
169
- // Code: https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js
170
- return useSyncExternalStoreWithSelector(
171
- dependencies.subscribe,
172
- dependencies.getSnapshot,
173
- undefined,
174
- dependencies.wrappedSelector,
175
- equalityFn,
176
- );
177
- };
178
-
179
- const noopSubscription = {
180
- subscribe: () => { },
181
- getSnapshot: () => null,
182
- wrappedSelector: () => true
183
- };