Repository navigation
Expand file tree
/
Copy pathHoistComponent.ts
More file actions
472 lines (417 loc) · 18.2 KB
/
Copy pathHoistComponent.ts
File metadata and controls
472 lines (417 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
* This file belongs to Hoist, an application development toolkit
* developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
*
* Copyright © 2026 Extremely Heavy Industries Inc.
*/
import {instanceManager} from '@xh/hoist/core/impl/InstanceManager';
import type {
HoistProps,
DefaultHoistProps,
ElementFactory,
TestSupportProps,
PlainObject
} from './';
import {CreatesSpec, UsesSpec, elementFactory} from './';
import type {ModelSpec, HoistModel} from './model';
import {
useModelLinker,
withLocalModelContext,
ModelLookup,
ModelLookupContext,
modelLookupContextProvider,
uses,
formatSelector
} from './model';
import {logError, throwIf, warnIf, withDefault} from '@xh/hoist/utils/js';
import {getLayoutProps} from '@xh/hoist/utils/react';
import classNames from 'classnames';
import {isFunction, isPlainObject, isObject} from 'lodash';
import {observer, untracked} from '../mobx';
import type {ForwardedRef, FC, ReactNode, FunctionComponent} from 'react';
import {forwardRef, memo, useContext, useEffect, useRef, createElement, useDebugValue} from 'react';
/**
* Type representing props passed to a HoistComponent's render function.
*
* This type removes from its base type several properties that are pulled out by the HoistComponent itself and
* not provided to the render function. `modelConfig` and `modelRef` are resolved into the `model` property.
* `ref` is passed as the second argument to the render function.
*/
export type RenderPropsOf<P extends HoistProps> = P & {
/** Pre-processed by HoistComponent internals into a mounted model. Never passed to render. */
modelConfig: never;
/** Pre-processed by HoistComponent internals and attached to model. Never passed to render. */
modelRef: never;
/** Pre-processed by HoistComponent internals and passed as second argument to render. */
ref: never;
};
/**
* Configuration for creating a Component. May be specified either as a render function,
* or an object containing a render function and associated metadata.
*/
export type ComponentConfig<P extends HoistProps, D extends PlainObject = never> =
| ((props: RenderPropsOf<P>, ref?: ForwardedRef<any>) => ReactNode)
| {
/** Render function defining the component. */
render(props: RenderPropsOf<P>, ref?: ForwardedRef<any>): ReactNode;
/**
* Spec defining the model to be rendered by this component.
* Specify as false for components that don't require a primary model. Otherwise, set to the
* return of {@link uses} or {@link creates} - these factory functions will create a spec for
* either externally-provided or internally-created models. Defaults to `uses('*')`.
*/
model?: ModelSpec<P['model']> | false;
/**
* Base CSS class for this component. Will be combined with any className
* in props, with the combined string passed into render as a prop.
*/
className?: string;
/** Component name for debugging/inspection. */
displayName?: string;
/**
* True (default) to wrap component in a call to `React.memo()`.
* Components that are known to be unable to make effective use of memo (e.g. container
* components) may set this to `false`. Not typically set by application code.
*/
memo?: boolean;
/**
* True (default) to enable MobX-powered reactivity via the
* `observer()` HOC from mobx-react. Components that are known to dereference no observable
* state may set this to `false`, but this is not typically done by application code.
*/
observer?: boolean;
/**
* Static, app-wide configuration for the component, attached to the returned component
* as a typed `defaults` object that applications can modify at bootstrap to customize
* behavior for all instances (e.g. `Button.defaults.minimal = false` in Bootstrap.ts).
*
* Most commonly used to supply default values for selected props. May also be used for
* other app-overridable settings that are not exposed as props.
*/
defaults?: D;
};
let cmpIndex = 0; // index for anonymous component dispay names
/**
* The primary entry point for defining Hoist components - functional React components enhanced
* with MobX reactivity and integrated model support.
*
* Accepts a configuration object (or a bare render function) and returns a React functional
* component. The `model` config is the key option: use {@link creates} to have the component
* create and own its backing model, {@link uses} to source a model from props or context, or
* `false` for simple components with no model. Defaults to `uses('*')` if not specified.
*
* Components are wrapped in the MobX `observer` HOC by default, enabling automatic re-rendering
* when observable state read during render changes.
*
* Forward refs ({@link https://reactjs.org/docs/forwarding-refs.html}) are supported by
* specifying a render function with two arguments - the second is treated as a ref, and
* `React.forwardRef` is applied automatically.
*
* Most components should be defined via one of two convenience methods rather than calling
* this function directly:
* - `hoistCmp.factory()` - returns an element factory (the standard pattern for app components).
* - `hoistCmp.withFactory()` - returns a `[Component, factory]` pair (the standard pattern for
* library components that need to export both).
*
* See the core package README (`core/README.md`) for full documentation on component
* configuration, model specs, and context lookup behavior.
*
* Components can also declare a typed `defaults` object in their config to expose static,
* app-wide configuration - most typically default values for selected props, but also other
* settings designed to be overridden by applications at bootstrap (e.g.
* `Button.defaults.minimal = false` in Bootstrap.ts). When specified, the returned component
* exposes a typed `defaults` property.
*
* @param config - specification object, or a render function defining the component.
* @returns a functional React Component for use within Hoist apps.
*/
export function hoistCmp<M extends HoistModel>(
config: ComponentConfig<DefaultHoistProps<M>>
): FC<DefaultHoistProps<M>>;
export function hoistCmp<P extends HoistProps, D extends PlainObject>(
config: ComponentConfig<P, D>
): FC<P> & {defaults: D};
export function hoistCmp<P extends HoistProps>(config: ComponentConfig<P>): FC<P>;
export function hoistCmp<P extends HoistProps>(config: ComponentConfig<P>): FC<P> {
// 0) Pre-process/parse args.
if (isFunction(config)) config = {render: config, displayName: config.name};
// 1) Default and validate the modelSpec.
const modelSpec = withDefault(config.model, uses('*'));
throwIf(
modelSpec && !(modelSpec instanceof UsesSpec) && !(modelSpec instanceof CreatesSpec),
"The 'model' config passed to hoistComponent() is incorrectly specified: provide a spec returned by either uses() or creates()."
);
let render = config.render,
cfg: Config = {
className: config.className,
displayName: config.displayName ? config.displayName : 'HoistCmp' + cmpIndex++,
isMemo: withDefault(config.memo, true),
isObserver: withDefault(config.observer, true),
isForwardRef: render.length === 2,
modelSpec: modelSpec ? modelSpec : null,
defaults: config.defaults ?? null
};
warnIf(
!cfg.isMemo && cfg.isObserver,
'Cannot create an observer component without `memo`. Memo is built-in to MobX observable. Component will be memoized.'
);
// 2) Wrap supplied render function with model and classname, support. Be sure to clone props.
render = cfg.modelSpec ? wrapWithModel(render, cfg) : wrapWithoutModel(render);
if (cfg.className) {
render = wrapWithClassName(render, cfg);
}
if (cfg.modelSpec || cfg.className) {
render = wrapWithClonedProps(render);
}
// 4) Wrap with standard react HOCs, mark, install defaults if specified, and return.
let ret = render as any;
ret.displayName = cfg.displayName;
if (cfg.isForwardRef) ret = forwardRef(ret);
if (cfg.isObserver) ret = observer(ret);
if (cfg.isMemo && !cfg.isObserver) ret = memo(ret);
ret.displayName = cfg.displayName;
ret.isHoistComponent = true;
if (cfg.defaults) ret.defaults = cfg.defaults;
return ret;
}
/**
* Alias for {@link hoistCmp}.
*/
export const hoistComponent = hoistCmp;
/**
* Return an element factory for a newly defined component.
*
* Most typically used by application, this provides a simple element factory.
*/
export function hoistCmpFactory<M extends HoistModel>(
config: ComponentConfig<DefaultHoistProps<M>>
): ElementFactory<DefaultHoistProps<M>>;
export function hoistCmpFactory<P extends HoistProps>(
config: ComponentConfig<P>
): ElementFactory<P>;
export function hoistCmpFactory(config) {
return elementFactory(hoistCmp(config));
}
hoistCmp.factory = hoistCmpFactory;
/**
* Returns a 2-element list containing both the newly defined Component and an elementFactory for it.
* Used by Hoist for exporting Component artifacts that support both JSX and elementFactory based development.
*
* Not typically used by applications.
*/
export function hoistCmpWithFactory<M extends HoistModel>(
config: ComponentConfig<DefaultHoistProps<M>>
): [FC<DefaultHoistProps<M>>, ElementFactory<DefaultHoistProps<M>>];
export function hoistCmpWithFactory<P extends HoistProps, D extends PlainObject>(
config: ComponentConfig<P, D>
): [FC<P> & {defaults: D}, ElementFactory<P>];
export function hoistCmpWithFactory<P extends HoistProps>(
config: ComponentConfig<P>
): [FC<P>, ElementFactory<P>];
export function hoistCmpWithFactory(config) {
const cmp = hoistCmp(config);
return [cmp, elementFactory(cmp)];
}
hoistCmp.withFactory = hoistCmpWithFactory;
//----------------------------
// Implementation
//----------------------------
//----------------------------------
// internal types and core wrappers
//----------------------------------
type RenderFn = (props: HoistProps & TestSupportProps, ref?: ForwardedRef<any>) => ReactNode;
interface Config {
displayName: string;
className: string;
isObserver: boolean;
isForwardRef: boolean;
isMemo: boolean;
modelSpec: ModelSpec;
defaults: PlainObject;
}
interface ResolvedModel {
model: HoistModel;
fromContext: boolean;
isLinked: boolean;
}
function wrapWithClassName(render: RenderFn, cfg: Config): RenderFn {
return (props, ref) => {
props.className = classNames(cfg.className, props.className);
return render(props, ref);
};
}
function wrapWithClonedProps(render: RenderFn): RenderFn {
return (props, ref) => render({...props}, ref);
}
//------------------------------------------------------------------------------------
// Context support for components without their own models.
//------------------------------------------------------------------------------------
function wrapWithoutModel(render: RenderFn): RenderFn {
return (props, ref) => withLocalModelContext(props, null, () => render(props, ref));
}
//------------------------------------------------------------------------------------
// Context support for components with their own models.
//
// Lookup/create model for this component using spec, *AND* potentially publish
// explicitly to children, if needed. This may require inserting a ContextProvider
//------------------------------------------------------------------------------------
function wrapWithModel(render: RenderFn, cfg: Config): RenderFn {
const spec = cfg.modelSpec,
{publishMode} = spec,
publishNone = publishMode === 'none',
publishDefault = publishMode === 'default',
HostCmp = createCmpHost(cfg);
return (props, ref) => {
// 1) Get the model and modelLookup context
const modelLookup = useContext(ModelLookupContext),
resolvedModel = useResolvedModel(props, modelLookup, cfg),
{isLinked, model, fromContext} = resolvedModel;
useDebugValue(model, m => {
if (!m) return 'null';
return [
m.constructor.name,
m.xhId,
isLinked ? 'linked' : fromContext ? 'context' : 'props'
].join(' | ');
});
// 2) insert any new lookup context that needs to be established. Avoid adding if default
// model not changing; cache object to avoid triggering re-renders in context children
const insertLookup = useRef<ModelLookup>(null);
if (
!publishNone &&
model &&
(!modelLookup ||
!fromContext ||
(publishDefault && modelLookup.lookupModel('*') !== model))
) {
const {current} = insertLookup;
if (current?.model != model || current?.parent != modelLookup) {
insertLookup.current = new ModelLookup(model, modelLookup, publishMode);
}
} else {
insertLookup.current = null;
}
// 3) Validate - only after the hooks above, so a failed lookup keeps the hook count stable.
if (!model && !spec.optional && spec instanceof UsesSpec) {
logError(
`Failed to find model with selector '${formatSelector(spec.selector)}'. Ensure the
proper model is available via context, or specify using the 'model' prop.`,
cfg.displayName
);
return cmpErrDisplay({...getLayoutProps(props), children: 'No model found'});
}
// 4) Get the rendering of the component with its model context
// 4a) Create a generic render function, that can be called immediately, or in wrapped component.
const managedRender = () => {
props.model = model;
delete props.modelRef;
delete props.modelConfig;
instanceManager.useTestIdRegistration(props.testId, model);
return withLocalModelContext(props, insertLookup.current ?? modelLookup, () =>
render(props, ref)
);
};
// 4b) Get the element, either running the wrapped function directly, or in a wrapped component if needed
const ret = isLinked
? managedRender()
: createElement(HostCmp, {managedRender, key: model?.xhId});
return insertLookup.current
? modelLookupContextProvider({value: insertLookup.current, children: ret})
: ret;
};
}
//-------------------------------------------------------------------------
// Support to resolve/create model at render-time. Used by wrappers above.
//-------------------------------------------------------------------------
function useResolvedModel(props: HoistProps, modelLookup: ModelLookup, cfg: Config): ResolvedModel {
let ref = useRef<ResolvedModel>(null),
resolvedModel = ref.current;
// 1) Lookup or create the model, as appropriate.
if (!resolvedModel) {
resolvedModel =
cfg.modelSpec instanceof CreatesSpec
? createModel(cfg.modelSpec)
: lookupModel(props, modelLookup, cfg);
// 1a) Cache any linked (created) model. Only create a model once!
if (resolvedModel.isLinked) ref.current = resolvedModel;
}
// 2) Other bookkeeping, following rules of hooks, before return.
const {model, isLinked} = resolvedModel;
useModelLinker(isLinked ? model : null, modelLookup, props);
const {modelRef} = props;
useEffect(() => {
if (isFunction(modelRef)) {
modelRef(model);
} else if (isObject(modelRef)) {
(modelRef as any).current = model;
}
}, [model, modelRef]);
return resolvedModel;
}
function createModel(spec: CreatesSpec<HoistModel>): ResolvedModel {
// Model creation is one-time, don't track.
const model = untracked(() => {
const ret = spec.createFn();
return isFunction(ret) ? new (ret as any)() : ret;
});
return {model, isLinked: true, fromContext: false};
}
function lookupModel(props: HoistProps, modelLookup: ModelLookup, cfg: Config): ResolvedModel {
let {model, modelConfig} = props,
spec = cfg.modelSpec as UsesSpec<HoistModel>,
selector = spec.selector as any;
// 1) props - config
if (spec.createFromConfig) {
if (isPlainObject(modelConfig)) {
const model = untracked(() => new selector(modelConfig));
return {model, isLinked: true, fromContext: false};
}
}
// 2) props - instance
if (model) {
if (!model.isHoistModel || !model.matchesSelector(selector, true)) {
logError(
`Incorrect model passed.
Expected: ${formatSelector(selector)}
Received: ${model.constructor.name}`,
cfg.displayName
);
model = null;
}
return {model, isLinked: false, fromContext: false};
}
// 3) context
if (modelLookup && spec.fromContext) {
const contextModel = modelLookup.lookupModel(selector);
if (contextModel) return {model: contextModel, isLinked: false, fromContext: true};
}
// 4) default create
const create = spec.createDefault;
if (create) {
const model = untracked(() => (isFunction(create) ? create() : new selector()));
return {model, isLinked: true, fromContext: false};
}
return {model: null, isLinked: false, fromContext: false};
}
/**
* @internal
*
* Create Internal wrapper component for HoistComponents with provided models.
*
* Used to ensure that the core of the component is remounted,
* if the provided model changes.
*/
function createCmpHost(cfg: Config): FunctionComponent<any> {
let ret: FunctionComponent<any> = props => props.managedRender();
ret = cfg.isObserver ? observer(ret) : ret;
ret.displayName = cfg.displayName + 'Host';
return ret;
}
/**
* Component to render certain errors caught within hoistComponent.
* @internal
*/
export function setCmpErrorDisplay(ef: ElementFactory) {
cmpErrDisplay = ef;
}
let cmpErrDisplay: ElementFactory = null;