react-cosmos-renderer 6.0.0-canary.660d495.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.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/client.d.ts +1 -0
  3. package/client.js +1 -0
  4. package/dist/client.d.ts +7 -0
  5. package/dist/client.js +7 -0
  6. package/dist/fixture/FixtureCapture/FixtureCapture.d.ts +8 -0
  7. package/dist/fixture/FixtureCapture/FixtureCapture.js +17 -0
  8. package/dist/fixture/FixtureCapture/classState/decorateFixtureRefs/index.d.ts +5 -0
  9. package/dist/fixture/FixtureCapture/classState/decorateFixtureRefs/index.js +46 -0
  10. package/dist/fixture/FixtureCapture/classState/decorateFixtureRefs/isRefSupported.d.ts +4 -0
  11. package/dist/fixture/FixtureCapture/classState/decorateFixtureRefs/isRefSupported.js +19 -0
  12. package/dist/fixture/FixtureCapture/classState/index.d.ts +3 -0
  13. package/dist/fixture/FixtureCapture/classState/index.js +13 -0
  14. package/dist/fixture/FixtureCapture/classState/shared.d.ts +18 -0
  15. package/dist/fixture/FixtureCapture/classState/shared.js +14 -0
  16. package/dist/fixture/FixtureCapture/classState/useFixtureState.d.ts +4 -0
  17. package/dist/fixture/FixtureCapture/classState/useFixtureState.js +153 -0
  18. package/dist/fixture/FixtureCapture/classState/useReadClassState.d.ts +4 -0
  19. package/dist/fixture/FixtureCapture/classState/useReadClassState.js +58 -0
  20. package/dist/fixture/FixtureCapture/props/index.d.ts +3 -0
  21. package/dist/fixture/FixtureCapture/props/index.js +74 -0
  22. package/dist/fixture/FixtureCapture/props/useFixtureProps.d.ts +3 -0
  23. package/dist/fixture/FixtureCapture/props/useFixtureProps.js +68 -0
  24. package/dist/fixture/FixtureCapture/shared/findRelevantElementPaths.d.ts +2 -0
  25. package/dist/fixture/FixtureCapture/shared/findRelevantElementPaths.js +23 -0
  26. package/dist/fixture/FixtureCapture/shared/nodeTree/findElementPaths.d.ts +2 -0
  27. package/dist/fixture/FixtureCapture/shared/nodeTree/findElementPaths.js +22 -0
  28. package/dist/fixture/FixtureCapture/shared/nodeTree/getElementAtPath.d.ts +3 -0
  29. package/dist/fixture/FixtureCapture/shared/nodeTree/getElementAtPath.js +26 -0
  30. package/dist/fixture/FixtureCapture/shared/nodeTree/index.d.ts +11 -0
  31. package/dist/fixture/FixtureCapture/shared/nodeTree/index.js +11 -0
  32. package/dist/fixture/FixtureCapture/shared/nodeTree/setElementAtPath.d.ts +2 -0
  33. package/dist/fixture/FixtureCapture/shared/nodeTree/setElementAtPath.js +35 -0
  34. package/dist/fixture/FixtureCapture/shared/nodeTree/shared.d.ts +2 -0
  35. package/dist/fixture/FixtureCapture/shared/nodeTree/shared.js +6 -0
  36. package/dist/fixture/FixtureContext.d.ts +7 -0
  37. package/dist/fixture/FixtureContext.js +5 -0
  38. package/dist/fixture/Viewport.d.ts +11 -0
  39. package/dist/fixture/Viewport.js +15 -0
  40. package/dist/fixture/useSelect/index.d.ts +2 -0
  41. package/dist/fixture/useSelect/index.js +11 -0
  42. package/dist/fixture/useSelect/shared.d.ts +6 -0
  43. package/dist/fixture/useSelect/shared.js +3 -0
  44. package/dist/fixture/useSelect/useCreateFixtureState.d.ts +2 -0
  45. package/dist/fixture/useSelect/useCreateFixtureState.js +32 -0
  46. package/dist/fixture/useSelect/useCurrentValue.d.ts +2 -0
  47. package/dist/fixture/useSelect/useCurrentValue.js +11 -0
  48. package/dist/fixture/useSelect/useSetValue.d.ts +2 -0
  49. package/dist/fixture/useSelect/useSetValue.js +25 -0
  50. package/dist/fixture/useValue/index.d.ts +7 -0
  51. package/dist/fixture/useValue/index.js +9 -0
  52. package/dist/fixture/useValue/shared.d.ts +3 -0
  53. package/dist/fixture/useValue/shared.js +1 -0
  54. package/dist/fixture/useValue/useCreateFixtureState.d.ts +2 -0
  55. package/dist/fixture/useValue/useCreateFixtureState.js +33 -0
  56. package/dist/fixture/useValue/useCurrentValue.d.ts +2 -0
  57. package/dist/fixture/useValue/useCurrentValue.js +12 -0
  58. package/dist/fixture/useValue/useSetValue.d.ts +3 -0
  59. package/dist/fixture/useValue/useSetValue.js +34 -0
  60. package/dist/fixtureLoaders/ClientFixtureLoader.d.ts +9 -0
  61. package/dist/fixtureLoaders/ClientFixtureLoader.js +18 -0
  62. package/dist/fixtureLoaders/FixtureLoaderConnect.d.ts +11 -0
  63. package/dist/fixtureLoaders/FixtureLoaderConnect.js +19 -0
  64. package/dist/fixtureLoaders/RendererSync.d.ts +8 -0
  65. package/dist/fixtureLoaders/RendererSync.js +52 -0
  66. package/dist/fixtureLoaders/ServerFixtureChangeListener.d.ts +6 -0
  67. package/dist/fixtureLoaders/ServerFixtureChangeListener.js +20 -0
  68. package/dist/fixtureLoaders/ServerFixtureLoader.d.ts +10 -0
  69. package/dist/fixtureLoaders/ServerFixtureLoader.js +21 -0
  70. package/dist/fixtureLoaders/defaultRenderMessage.d.ts +2 -0
  71. package/dist/fixtureLoaders/defaultRenderMessage.js +4 -0
  72. package/dist/fixtureLoaders/useFixtureSelection.d.ts +7 -0
  73. package/dist/fixtureLoaders/useFixtureSelection.js +31 -0
  74. package/dist/fixtureModule/DecoratedFixture.d.ts +9 -0
  75. package/dist/fixtureModule/DecoratedFixture.js +13 -0
  76. package/dist/fixtureModule/FixtureModule.d.ts +14 -0
  77. package/dist/fixtureModule/FixtureModule.js +13 -0
  78. package/dist/fixtureModule/FixtureProvider.d.ts +11 -0
  79. package/dist/fixtureModule/FixtureProvider.js +74 -0
  80. package/dist/fixtureModule/createFixtureNode.d.ts +3 -0
  81. package/dist/fixtureModule/createFixtureNode.js +19 -0
  82. package/dist/fixtureModule/decorateFixture.d.ts +3 -0
  83. package/dist/fixtureModule/decorateFixture.js +4 -0
  84. package/dist/index.d.ts +6 -0
  85. package/dist/index.js +6 -0
  86. package/dist/moduleLoaders/AsyncModuleLoader.d.ts +9 -0
  87. package/dist/moduleLoaders/AsyncModuleLoader.js +14 -0
  88. package/dist/moduleLoaders/LazyModuleLoader.d.ts +10 -0
  89. package/dist/moduleLoaders/LazyModuleLoader.js +25 -0
  90. package/dist/moduleLoaders/StaticModuleLoader.d.ts +10 -0
  91. package/dist/moduleLoaders/StaticModuleLoader.js +8 -0
  92. package/dist/moduleLoaders/importLazyFixtureModules.d.ts +5 -0
  93. package/dist/moduleLoaders/importLazyFixtureModules.js +6 -0
  94. package/dist/rendererConnect/RendererContext.d.ts +10 -0
  95. package/dist/rendererConnect/RendererContext.js +11 -0
  96. package/dist/rendererConnect/createNoopRendererConnect.d.ts +2 -0
  97. package/dist/rendererConnect/createNoopRendererConnect.js +8 -0
  98. package/dist/rendererConnect/createPostMessageConnect.d.ts +2 -0
  99. package/dist/rendererConnect/createPostMessageConnect.js +22 -0
  100. package/dist/rendererConnect/createWebSocketsConnect.d.ts +2 -0
  101. package/dist/rendererConnect/createWebSocketsConnect.js +32 -0
  102. package/index.d.ts +1 -0
  103. package/index.js +1 -0
  104. package/package.json +19 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015-present Ovidiu Cherecheș
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/client.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/client.js';
package/client.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/client.js';
@@ -0,0 +1,7 @@
1
+ export * from './fixture/FixtureCapture/FixtureCapture.js';
2
+ export * from './fixture/FixtureContext.js';
3
+ export * from './fixture/Viewport.js';
4
+ export * from './fixture/useSelect/index.js';
5
+ export * from './fixture/useValue/index.js';
6
+ export * from './fixtureLoaders/ClientFixtureLoader.js';
7
+ export * from './rendererConnect/RendererContext.js';
package/dist/client.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from './fixture/FixtureCapture/FixtureCapture.js';
2
+ export * from './fixture/FixtureContext.js';
3
+ export * from './fixture/Viewport.js';
4
+ export * from './fixture/useSelect/index.js';
5
+ export * from './fixture/useValue/index.js';
6
+ export * from './fixtureLoaders/ClientFixtureLoader.js';
7
+ export * from './rendererConnect/RendererContext.js';
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+ import { FixtureDecoratorId } from 'react-cosmos-core';
3
+ type Props = {
4
+ children: React.ReactNode;
5
+ decoratorId: FixtureDecoratorId;
6
+ };
7
+ export declare function FixtureCapture({ children, decoratorId }: Props): JSX.Element;
8
+ export {};
@@ -0,0 +1,17 @@
1
+ // In a React Server Components setup this is a Client entry point for fixtures.
2
+ // In client fixtures the entire children tree is made out of client components.
3
+ // Server fixtures, however, are rendered on the server and returned as JSON
4
+ // elements that get passed through this client-side FixtureCapture decorator.
5
+ // This results in two types of client-side interaction with server-side props:
6
+ // 1. Props of client side components used in server fixtures.
7
+ // 2. Props of native elements rendered by server components (eg. div, p, etc.)
8
+ 'use client';
9
+ import React from 'react';
10
+ import { useClassStateCapture } from './classState/index.js';
11
+ import { usePropsCapture } from './props/index.js';
12
+ export function FixtureCapture({ children, decoratorId }) {
13
+ let fixture = usePropsCapture(children, decoratorId);
14
+ fixture = useClassStateCapture(fixture, decoratorId);
15
+ // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18051
16
+ return React.createElement(React.Fragment, null, fixture);
17
+ }
@@ -0,0 +1,5 @@
1
+ import { Component, ReactNode } from 'react';
2
+ import { CachedRefHandlers } from '../shared.js';
3
+ type SpyRef = (elPath: string, elRef: null | Component) => unknown;
4
+ export declare function decorateFixtureRefs(fixture: ReactNode, spyRef: SpyRef, cachedRefHandlers: CachedRefHandlers): ReactNode;
5
+ export {};
@@ -0,0 +1,46 @@
1
+ import { cloneElement, } from 'react';
2
+ import { findRelevantElementPaths } from '../../shared/findRelevantElementPaths.js';
3
+ import { setElementAtPath } from '../../shared/nodeTree/index.js';
4
+ import { isRefSupported } from './isRefSupported.js';
5
+ export function decorateFixtureRefs(fixture, spyRef, cachedRefHandlers) {
6
+ const elPaths = findRelevantElementPaths(fixture);
7
+ return elPaths.reduce((decoratedFixture, elPath) => {
8
+ return setElementAtPath(decoratedFixture, elPath, element => {
9
+ if (!isRefSupported(element.type)) {
10
+ return element;
11
+ }
12
+ return cloneElement(element, {
13
+ ref: getDecoratedRef(element.ref, spyRef, elPath, cachedRefHandlers),
14
+ });
15
+ });
16
+ }, fixture);
17
+ }
18
+ function getDecoratedRef(origRef, spyRef, elPath, cachedRefHandlers) {
19
+ const found = cachedRefHandlers[elPath];
20
+ if (found && found.origRef === origRef) {
21
+ return found.handler;
22
+ }
23
+ const handler = decorateRefWithSpy(origRef, spyRef, elPath);
24
+ cachedRefHandlers[elPath] = { origRef, handler };
25
+ return handler;
26
+ }
27
+ function decorateRefWithSpy(origRef, spyRef, elPath) {
28
+ return (elRef) => {
29
+ if (origRef) {
30
+ callOriginalRef(origRef, elRef);
31
+ }
32
+ spyRef(elPath, elRef);
33
+ };
34
+ }
35
+ function callOriginalRef(ref, elRef) {
36
+ if (typeof ref === 'string') {
37
+ console.warn('[decorateFixtureRefs] String refs are not supported');
38
+ return;
39
+ }
40
+ if (typeof ref === 'function') {
41
+ ref(elRef);
42
+ return;
43
+ }
44
+ const refObj = ref;
45
+ refObj.current = elRef;
46
+ }
@@ -0,0 +1,4 @@
1
+ import React from 'react';
2
+ type ElementType = string | React.ComponentType;
3
+ export declare function isRefSupported(elementType: ElementType): boolean;
4
+ export {};
@@ -0,0 +1,19 @@
1
+ import React from 'react';
2
+ import { ForwardRef } from 'react-is';
3
+ export function isRefSupported(elementType) {
4
+ if (typeof elementType === 'string') {
5
+ return false;
6
+ }
7
+ const { $$typeof, prototype } = elementType;
8
+ return ($$typeof === ForwardRef ||
9
+ // Warning: Some functions don't have the .prototype property
10
+ (prototype &&
11
+ // ES6 Class
12
+ // Warning: This will return false is the component is extending a
13
+ // different copy of React than the one used by Cosmos. This is relevant
14
+ // when running Cosmos from an external location instead of node_modules.
15
+ (prototype instanceof React.Component ||
16
+ // React.createClass
17
+ prototype.getInitialState !== undefined) &&
18
+ true));
19
+ }
@@ -0,0 +1,3 @@
1
+ import React from 'react';
2
+ import { FixtureDecoratorId } from 'react-cosmos-core';
3
+ export declare function useClassStateCapture(fixture: React.ReactNode, decoratorId: FixtureDecoratorId): React.ReactNode;
@@ -0,0 +1,13 @@
1
+ import React from 'react';
2
+ import { useFixtureState } from './useFixtureState.js';
3
+ import { useReadClassState } from './useReadClassState.js';
4
+ export function useClassStateCapture(fixture, decoratorId) {
5
+ const elRefs = React.useRef({});
6
+ React.useEffect(() => {
7
+ return () => {
8
+ elRefs.current = {};
9
+ };
10
+ }, []);
11
+ useReadClassState(fixture, decoratorId, elRefs);
12
+ return useFixtureState(fixture, decoratorId, elRefs);
13
+ }
@@ -0,0 +1,18 @@
1
+ import React from 'react';
2
+ export type ElRefs = {
3
+ [elPath: string]: React.Component;
4
+ };
5
+ export type InitialStates = {
6
+ [elPath: string]: {
7
+ type: React.ComponentClass<any>;
8
+ state: {};
9
+ };
10
+ };
11
+ export type CachedRefHandler = {
12
+ origRef: null | React.Ref<any>;
13
+ handler: (elRef: null | React.Component) => unknown;
14
+ };
15
+ export type CachedRefHandlers = {
16
+ [elPath: string]: CachedRefHandler;
17
+ };
18
+ export declare function replaceState(elRef: React.Component, nextState: {}): void;
@@ -0,0 +1,14 @@
1
+ import { isEqual } from 'lodash-es';
2
+ // We need to do this because React doesn't provide a replaceState method
3
+ // (anymore) https://reactjs.org/docs/react-component.html#setstate
4
+ export function replaceState(elRef, nextState) {
5
+ const fullState = resetOriginalKeys(elRef.state, nextState);
6
+ if (!isEqual(fullState, elRef.state)) {
7
+ elRef.setState(fullState);
8
+ }
9
+ }
10
+ function resetOriginalKeys(original, current) {
11
+ return Object.keys(original).reduce((result, key) => Object.keys(result).indexOf(key) === -1
12
+ ? { ...result, [key]: undefined }
13
+ : result, current);
14
+ }
@@ -0,0 +1,4 @@
1
+ import { MutableRefObject, ReactNode } from 'react';
2
+ import { FixtureDecoratorId } from 'react-cosmos-core';
3
+ import { ElRefs } from './shared.js';
4
+ export declare function useFixtureState(fixture: ReactNode, decoratorId: FixtureDecoratorId, elRefs: MutableRefObject<ElRefs>): ReactNode;
@@ -0,0 +1,153 @@
1
+ import { isEqual } from 'lodash-es';
2
+ import { useContext, useEffect, useRef, } from 'react';
3
+ import { createFixtureStateClassState, createValues, extendWithValues, findFixtureStateClassState, getComponentName, getFixtureStateClassState, removeFixtureStateClassState, } from 'react-cosmos-core';
4
+ import { FixtureContext } from '../../FixtureContext.js';
5
+ import { findRelevantElementPaths } from '../shared/findRelevantElementPaths.js';
6
+ import { decorateFixtureRefs } from './decorateFixtureRefs/index.js';
7
+ import { replaceState, } from './shared.js';
8
+ export function useFixtureState(fixture, decoratorId, elRefs) {
9
+ const elPaths = findRelevantElementPaths(fixture);
10
+ const { fixtureState, setFixtureState } = useContext(FixtureContext);
11
+ const lastFixtureState = useFixtureStateRef(fixtureState);
12
+ // Keep a copy of the previous fixture state to observe changes
13
+ const prevFixtureState = useRef(fixtureState);
14
+ // Remember initial state of child components to use as a default when
15
+ // resetting fixture state
16
+ const initialStates = useRef({});
17
+ // Ref handlers are reused because every time we pass a new ref handler to
18
+ // a React element it gets called in the next render loop, even when the
19
+ // associated element instance has been preserved. Having ref handlers fire
20
+ // on every render loop results in unwanted operations and race conditions.
21
+ const cachedRefHandlers = useRef({});
22
+ useEffect(() => {
23
+ return () => {
24
+ initialStates.current = {};
25
+ cachedRefHandlers.current = {};
26
+ };
27
+ }, []);
28
+ useEffect(() => {
29
+ // Remove fixture state for removed child elements (likely via HMR)
30
+ // FIXME: Also invalidate fixture state at this element path if the
31
+ // component type of the corresponding element changed
32
+ const fsProps = getFixtureStateClassState(fixtureState, decoratorId);
33
+ fsProps.forEach(({ elementId }) => {
34
+ const { elPath } = elementId;
35
+ if (elPaths.indexOf(elementId.elPath) === -1) {
36
+ setFixtureState(prevFs => ({
37
+ ...prevFs,
38
+ classState: removeFixtureStateClassState(fixtureState, elementId),
39
+ }));
40
+ if (elRefs.current[elPath]) {
41
+ delete elRefs.current[elPath];
42
+ delete initialStates.current[elPath];
43
+ delete cachedRefHandlers.current[elPath];
44
+ }
45
+ }
46
+ });
47
+ elPaths.forEach(elPath => {
48
+ const elementId = { decoratorId, elPath };
49
+ // Component fixture state can be provided before the fixture mounts (eg.
50
+ // a previous snapshot of a fixture state or the current fixture state
51
+ // from another renderer)
52
+ const fsClassState = findFixtureStateClassState(fixtureState, elementId);
53
+ if (!fsClassState) {
54
+ if (initialStates.current[elPath]) {
55
+ const { state } = initialStates.current[elPath];
56
+ const elRef = elRefs.current[elPath];
57
+ if (!isEqual(elRef.state, state)) {
58
+ replaceState(elRef, state);
59
+ }
60
+ setFixtureState(prevFs => ({
61
+ ...prevFs,
62
+ classState: createFixtureStateClassState({
63
+ fixtureState: prevFs,
64
+ elementId,
65
+ values: createValues(state),
66
+ componentName: getComponentName(elRef.constructor),
67
+ }),
68
+ }));
69
+ }
70
+ }
71
+ else {
72
+ const elRef = elRefs.current[elPath];
73
+ // The el ref can be missing for three reasons:
74
+ // 1. Element type is stateless
75
+ // 2. Element type is a class, but doesn't have state. An instance exists
76
+ // but has been discarded because of its lack of state.
77
+ // 3. Element instance unmounted and is about to remount. When this
78
+ // happens, the new instance will be handled when its ref fires again.
79
+ if (!elRef) {
80
+ return;
81
+ }
82
+ // The child's state can be out of sync with the fixture state for two
83
+ // reasons:
84
+ // 1. The child's state changed internally
85
+ // 2. The fixture state changed
86
+ // Here we're interested in the second scenario. In the first scenario
87
+ // we want to let the component state override the fixture state.
88
+ const prevFsClassState = findFixtureStateClassState(prevFixtureState.current, elementId);
89
+ if (prevFsClassState && !isEqual(prevFsClassState, fsClassState)) {
90
+ return replaceState(elRef, extendWithValues(elRef.state, fsClassState.values));
91
+ }
92
+ }
93
+ });
94
+ }, [
95
+ decoratorId,
96
+ elPaths,
97
+ elRefs,
98
+ fixtureState,
99
+ fixtureState.classState,
100
+ setFixtureState,
101
+ ]);
102
+ // Update prev fixture state ref *after* running effects that reference it
103
+ useEffect(() => {
104
+ prevFixtureState.current = fixtureState;
105
+ });
106
+ return decorateFixtureRefs(fixture, handleRef, cachedRefHandlers.current);
107
+ function handleRef(elPath, elRef) {
108
+ if (!elRef) {
109
+ delete elRefs.current[elPath];
110
+ return;
111
+ }
112
+ // Only track instances with state
113
+ const { state } = elRef;
114
+ if (!state) {
115
+ return;
116
+ }
117
+ elRefs.current[elPath] = elRef;
118
+ setInitialState(initialStates.current, elPath, elRef);
119
+ const elementId = { decoratorId, elPath };
120
+ const fsClassState = findFixtureStateClassState(lastFixtureState.current, elementId);
121
+ if (!fsClassState) {
122
+ setFixtureState(prevFs => ({
123
+ ...prevFs,
124
+ classState: createFixtureStateClassState({
125
+ fixtureState: prevFs,
126
+ elementId,
127
+ values: createValues(state),
128
+ componentName: getComponentName(elRef.constructor),
129
+ }),
130
+ }));
131
+ }
132
+ else {
133
+ replaceState(elRef, extendWithValues(state, fsClassState.values));
134
+ }
135
+ }
136
+ }
137
+ // Make latest fixture state accessible in ref callback
138
+ function useFixtureStateRef(fixtureState) {
139
+ const ref = useRef(fixtureState);
140
+ useEffect(() => {
141
+ ref.current = fixtureState;
142
+ });
143
+ return ref;
144
+ }
145
+ function setInitialState(initialStates, elPath, elRef) {
146
+ const found = initialStates[elPath];
147
+ const type = elRef.constructor;
148
+ // Keep the first state recevied for this type
149
+ const initialStateExists = found && found.type === type;
150
+ if (!initialStateExists && elRef.state) {
151
+ initialStates[elPath] = { type, state: elRef.state };
152
+ }
153
+ }
@@ -0,0 +1,4 @@
1
+ import { MutableRefObject, ReactNode } from 'react';
2
+ import { FixtureDecoratorId } from 'react-cosmos-core';
3
+ import { ElRefs } from './shared.js';
4
+ export declare function useReadClassState(fixture: ReactNode, decoratorId: FixtureDecoratorId, elRefs: MutableRefObject<ElRefs>): void;
@@ -0,0 +1,58 @@
1
+ import { isEqual } from 'lodash-es';
2
+ import { useContext, useEffect, useRef, } from 'react';
3
+ import { createValues, extendWithValues, findFixtureStateClassState, updateFixtureStateClassState, } from 'react-cosmos-core';
4
+ import { FixtureContext } from '../../FixtureContext.js';
5
+ import { findRelevantElementPaths } from '../shared/findRelevantElementPaths.js';
6
+ // How often to check the state of the loaded component and update the fixture
7
+ // state if it changed
8
+ const REFRESH_INTERVAL = 200;
9
+ export function useReadClassState(fixture, decoratorId, elRefs) {
10
+ const elPaths = findRelevantElementPaths(fixture);
11
+ const { fixtureState, setFixtureState } = useContext(FixtureContext);
12
+ const timeoutId = useRef(null);
13
+ useEffect(() => {
14
+ // The check should run even if no element paths are found at mount, because
15
+ // the fixture can change during the lifecycle of a FixtureCapture instance
16
+ // and the updated fixture might contain elements of stateful components
17
+ scheduleStateCheck();
18
+ return () => {
19
+ if (timeoutId.current) {
20
+ clearTimeout(timeoutId.current);
21
+ }
22
+ };
23
+ });
24
+ function scheduleStateCheck() {
25
+ // Is there a better way to listen to component state changes?
26
+ timeoutId.current = window.setTimeout(checkState, REFRESH_INTERVAL);
27
+ }
28
+ function checkState() {
29
+ let fixtureStateChangeScheduled = false;
30
+ Object.keys(elRefs.current).map(async (elPath) => {
31
+ if (elPaths.indexOf(elPath) === -1) {
32
+ throw new Error(`[FixtureCapture] Child ref exists for missing element path "${elPath}"`);
33
+ }
34
+ const { state } = elRefs.current[elPath];
35
+ const elementId = { decoratorId, elPath };
36
+ const fsClassState = findFixtureStateClassState(fixtureState, elementId);
37
+ if (fsClassState &&
38
+ state &&
39
+ !doesFixtureStateMatchClassState(fsClassState, state)) {
40
+ fixtureStateChangeScheduled = true;
41
+ setFixtureState(prevFs => ({
42
+ ...prevFs,
43
+ classState: updateFixtureStateClassState({
44
+ fixtureState: prevFs,
45
+ elementId,
46
+ values: createValues(state),
47
+ }),
48
+ }));
49
+ }
50
+ });
51
+ if (!fixtureStateChangeScheduled) {
52
+ scheduleStateCheck();
53
+ }
54
+ }
55
+ }
56
+ function doesFixtureStateMatchClassState(fsClassState, state) {
57
+ return isEqual(state, extendWithValues(state, fsClassState.values));
58
+ }
@@ -0,0 +1,3 @@
1
+ import { ReactNode } from 'react';
2
+ import { FixtureDecoratorId } from 'react-cosmos-core';
3
+ export declare function usePropsCapture(fixture: ReactNode, decoratorId: FixtureDecoratorId): ReactNode;
@@ -0,0 +1,74 @@
1
+ import { useContext, useEffect, useRef } from 'react';
2
+ import { areNodesEqual, createFixtureStateProps, createValues, findFixtureStateProps, getComponentName, getFixtureStateProps, removeFixtureStateProps, updateFixtureStateProps, } from 'react-cosmos-core';
3
+ import { FixtureContext } from '../../FixtureContext.js';
4
+ import { findRelevantElementPaths } from '../shared/findRelevantElementPaths.js';
5
+ import { getElementAtPath, getExpectedElementAtPath, } from '../shared/nodeTree/index.js';
6
+ import { useFixtureProps } from './useFixtureProps.js';
7
+ export function usePropsCapture(fixture, decoratorId) {
8
+ const { fixtureState, setFixtureState } = useContext(FixtureContext);
9
+ const prevFixtureRef = useRef(fixture);
10
+ const elPaths = findRelevantElementPaths(fixture);
11
+ useEffect(() => {
12
+ // Create empty fixture state
13
+ if (!fixtureState.props && elPaths.length === 0) {
14
+ // Make sure not to override any (currently pending) fixture state props
15
+ setFixtureState(prevFs => ({ ...prevFs, props: prevFs.props || [] }));
16
+ return;
17
+ }
18
+ // Remove fixture state for removed child elements (likely via HMR)
19
+ // FIXME: Also invalidate fixture state at this element path if the
20
+ // component type of the corresponding element changed
21
+ const fsProps = getFixtureStateProps(fixtureState, decoratorId);
22
+ fsProps.forEach(({ elementId }) => {
23
+ if (elPaths.indexOf(elementId.elPath) === -1) {
24
+ setFixtureState(prevFs => ({
25
+ ...prevFs,
26
+ props: removeFixtureStateProps(fixtureState, elementId),
27
+ }));
28
+ }
29
+ });
30
+ elPaths.forEach(elPath => {
31
+ const childEl = getExpectedElementAtPath(fixture, elPath);
32
+ const elementId = { decoratorId, elPath };
33
+ // Component fixture state can be provided before the fixture mounts (eg.
34
+ // a previous snapshot of a fixture state or the current fixture state
35
+ // from another renderer)
36
+ if (!findFixtureStateProps(fixtureState, elementId)) {
37
+ const componentName = getComponentName(childEl.type);
38
+ setFixtureState(prevFs => ({
39
+ ...prevFs,
40
+ props: createFixtureStateProps({
41
+ fixtureState: prevFs,
42
+ elementId,
43
+ values: createValues(childEl.props),
44
+ componentName,
45
+ }),
46
+ }));
47
+ }
48
+ else {
49
+ const prevChildEl = getElementAtPath(prevFixtureRef.current, elPath);
50
+ if (!areNodesEqual(prevChildEl, childEl, false)) {
51
+ setFixtureState(prevFs => ({
52
+ ...prevFs,
53
+ props: updateFixtureStateProps({
54
+ fixtureState,
55
+ elementId,
56
+ values: createValues(childEl.props),
57
+ }),
58
+ }));
59
+ }
60
+ }
61
+ });
62
+ }, [
63
+ fixture,
64
+ decoratorId,
65
+ elPaths,
66
+ fixtureState,
67
+ fixtureState.props,
68
+ setFixtureState,
69
+ ]);
70
+ useEffect(() => {
71
+ prevFixtureRef.current = fixture;
72
+ });
73
+ return useFixtureProps(fixture, fixtureState, decoratorId);
74
+ }
@@ -0,0 +1,3 @@
1
+ import React from 'react';
2
+ import { FixtureDecoratorId, FixtureState } from 'react-cosmos-core';
3
+ export declare function useFixtureProps(fixture: React.ReactNode, fixtureState: FixtureState, decoratorId: FixtureDecoratorId): React.ReactNode;
@@ -0,0 +1,68 @@
1
+ import { isEqual, mapValues } from 'lodash-es';
2
+ import React from 'react';
3
+ import { DEFAULT_RENDER_KEY, extendWithValues, findFixtureStateProps, getComponentName, } from 'react-cosmos-core';
4
+ import { findRelevantElementPaths } from '../shared/findRelevantElementPaths.js';
5
+ import { getChildrenPath, setElementAtPath } from '../shared/nodeTree/index.js';
6
+ export function useFixtureProps(fixture, fixtureState, decoratorId) {
7
+ const propCache = React.useMemo(() => ({}),
8
+ // React.useMemo is used as a cache invalidated by decoratorId
9
+ // eslint-disable-next-line react-hooks/exhaustive-deps
10
+ [decoratorId]);
11
+ const elPaths = findRelevantElementPaths(fixture);
12
+ return elPaths.reduce((extendedFixture, elPath) => {
13
+ const elementId = { decoratorId, elPath };
14
+ const fsProps = findFixtureStateProps(fixtureState, elementId);
15
+ return setElementAtPath(extendedFixture, elPath, element => {
16
+ if (!fsProps || componentTypeChanged(fsProps.componentName)) {
17
+ return {
18
+ ...element,
19
+ key: getElRenderKey(elPath, DEFAULT_RENDER_KEY),
20
+ };
21
+ }
22
+ // Prevent overriding child elements with outdated "children" prop values
23
+ // stored in fixture state
24
+ // See https://github.com/react-cosmos/react-cosmos/pull/920 for context
25
+ const originalProps = element.props;
26
+ const extendedProps = extendWithValues(originalProps, fsProps.values);
27
+ // Preserve identity between renders for indentical non-primitive props
28
+ const cachedProps = mapValues(extendedProps, (value, propName) => {
29
+ const key = getPropCacheKey(elPath, propName);
30
+ if (!propCache.hasOwnProperty(key))
31
+ propCache[key] = originalProps[propName];
32
+ if (isEqual(propCache[key], value))
33
+ return propCache[key];
34
+ propCache[key] = value;
35
+ return value;
36
+ });
37
+ // HACK alert: Editing React Element by hand
38
+ // This is blasphemy, but there are two reasons why React.cloneElement
39
+ // isn't ideal:
40
+ // 1. Props need to overridden (not merged)
41
+ // 2. element.key has to be set to control whether the prev instance
42
+ // should be reused or not
43
+ // To be revised in case this approach causes trouble in the future.
44
+ // Useful links:
45
+ // - https://reactjs.org/docs/react-api.html#cloneelement
46
+ // - https://github.com/facebook/react/blob/15a8f031838a553e41c0b66eb1bcf1da8448104d/packages/react/src/ReactElement.js#L293-L362
47
+ return {
48
+ ...element,
49
+ props: hasChildElPaths(elPaths, elPath)
50
+ ? { ...cachedProps, children: originalProps.children }
51
+ : cachedProps,
52
+ key: getElRenderKey(elPath, fsProps.renderKey),
53
+ };
54
+ function componentTypeChanged(componentName) {
55
+ return componentName !== getComponentName(element.type);
56
+ }
57
+ });
58
+ }, fixture);
59
+ }
60
+ function getPropCacheKey(elPath, propName) {
61
+ return elPath ? `${elPath}-${propName}` : propName;
62
+ }
63
+ function getElRenderKey(elPath, renderKey) {
64
+ return `${elPath}-${renderKey}`;
65
+ }
66
+ function hasChildElPaths(elPaths, elPath) {
67
+ return elPaths.some(p => p.indexOf(getChildrenPath(elPath)) === 0);
68
+ }
@@ -0,0 +1,2 @@
1
+ import React from 'react';
2
+ export declare function findRelevantElementPaths(node: React.ReactNode): string[];
@@ -0,0 +1,23 @@
1
+ import { findElementPaths, getExpectedElementAtPath, } from './nodeTree/index.js';
2
+ export function findRelevantElementPaths(node) {
3
+ const elPaths = findElementPaths(node);
4
+ return elPaths.filter(elPath => {
5
+ const { type } = getExpectedElementAtPath(node, elPath);
6
+ // Ignore symbol types, like StrictMode
7
+ // https://github.com/react-cosmos/react-cosmos/issues/1249
8
+ if (typeof type === 'symbol')
9
+ return false;
10
+ if (typeof type === 'string')
11
+ return isInterestingTag(type);
12
+ const classType = type;
13
+ return classType.cosmosCapture !== false && isInterestingClass(classType);
14
+ });
15
+ }
16
+ function isInterestingTag(tagName) {
17
+ // TODO: Make this customizable
18
+ return tagName !== 'div' && tagName !== 'span';
19
+ }
20
+ function isInterestingClass(type) {
21
+ // TODO: Make this customizable
22
+ return type.name !== 'StyledComponent';
23
+ }
@@ -0,0 +1,2 @@
1
+ import React from 'react';
2
+ export declare function findElementPaths(node: React.ReactNode, curPath?: string): string[];
@@ -0,0 +1,22 @@
1
+ import { flatten } from 'lodash-es';
2
+ import { Fragment } from 'react';
3
+ import { isReactElement } from 'react-cosmos-core';
4
+ import { getChildrenPath } from './shared.js';
5
+ export function findElementPaths(node, curPath = '') {
6
+ if (Array.isArray(node)) {
7
+ return flatten(node.map((child, idx) => findElementPaths(child, `${curPath}[${idx}]`)));
8
+ }
9
+ if (!isReactElement(node)) {
10
+ // At this point the node can be null, boolean, string, number, Portal, etc.
11
+ // https://github.com/facebook/flow/blob/172d28f542f49bbc1e765131c9dfb9e31780f3a2/lib/react.js#L13-L20
12
+ return [];
13
+ }
14
+ const { children } = node.props;
15
+ const childElPaths =
16
+ // Props of elements returned by render functions can't be read here
17
+ typeof children !== 'function'
18
+ ? findElementPaths(children, getChildrenPath(curPath))
19
+ : [];
20
+ // Ignore Fragment elements, but include their children
21
+ return node.type === Fragment ? childElPaths : [curPath, ...childElPaths];
22
+ }
@@ -0,0 +1,3 @@
1
+ import { ReactElement, ReactNode } from 'react';
2
+ export declare function getElementAtPath(node: ReactNode, elPath: string): null | ReactElement;
3
+ export declare function getExpectedElementAtPath(node: ReactNode, elPath: string): ReactElement;