Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lift state #54

Merged
merged 7 commits into from
Sep 3, 2021
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
64 changes: 9 additions & 55 deletions packages/ReactDagEditor/src/components/Graph/GraphStateStore.tsx
Original file line number Diff line number Diff line change
@@ -1,68 +1,22 @@
import * as React from "react";
import { ConnectingState } from "../../ConnectingState";
import { EMPTY_GAP, EMPTY_TRANSFORM_MATRIX, GraphConfigContext, IGraphReducer, ViewportContext } from "../../contexts";
import { GraphConfigContext, IDispatch, ViewportContext } from "../../contexts";
import { AlignmentLinesContext } from "../../contexts/AlignmentLinesContext";
import { GraphControllerContext } from "../../contexts/GraphControllerContext";
import { GraphStateContext, GraphValueContext } from "../../contexts/GraphStateContext";
import { GraphController } from "../../controllers/GraphController";
import { defaultFeatures, GraphFeatures } from "../../Features";
import { useConst } from "../../hooks/useConst";
import { useGraphReducer } from "../../hooks/useGraphReducer";
import { IGraphConfig } from "../../models/config/types";
import { IGap, ITransformMatrix } from "../../models/geometry";
import { GraphModel } from "../../models/GraphModel";
import type { GraphController } from "../../controllers/GraphController";
import type { IGraphState } from "../../models/state";

export interface IGraphStateStoreProps<NodeData = unknown, EdgeData = unknown, PortData = unknown, Action = never> {
/**
* the initial graph data model.
*/
data?: GraphModel<NodeData, EdgeData, PortData>;
defaultTransformMatrix?: ITransformMatrix;
middleware?: IGraphReducer<NodeData, EdgeData, PortData, Action>;
features?: ReadonlySet<GraphFeatures>;
canvasBoundaryPadding?: IGap;
graphConfig: IGraphConfig;
state: IGraphState<NodeData, EdgeData, PortData>;
dispatch: IDispatch<NodeData, EdgeData, PortData, Action>;
graphController: GraphController;
}

export function GraphStateStore<NodeData = unknown, EdgeData = unknown, PortData = unknown, Action = never>(
props: React.PropsWithChildren<IGraphStateStoreProps<NodeData, EdgeData, PortData, Action>>
): React.ReactElement {
const {
defaultTransformMatrix = EMPTY_TRANSFORM_MATRIX,
middleware,
features = defaultFeatures,
canvasBoundaryPadding = EMPTY_GAP,
graphConfig
} = props;

const [state, dispatch] = useGraphReducer(
{
data: props.data,
transformMatrix: defaultTransformMatrix,
graphConfig,
features,
canvasBoundaryPadding,
nodeMinVisibleSize: {
width: 5,
height: 5
},
nodeMaxVisibleSize: {
width: Infinity,
height: Infinity
}
},
middleware
);

const graphController = useConst(() => new GraphController(state, dispatch));
graphController.UNSAFE_latestState = state;
React.useLayoutEffect(() => {
graphController.state = state;
graphController.dispatch = dispatch;
// TODO: fix the next line after state is lifted and everything is merged into top level `ReactDagEditor`
// graphController.getGlobalEventTargetImpl = getGlobalEventTarget;
}, [dispatch, graphController, state]);

const { graphController, state, dispatch, children } = props;
const contextValue = React.useMemo(
() => ({
state,
Expand All @@ -72,14 +26,14 @@ export function GraphStateStore<NodeData = unknown, EdgeData = unknown, PortData
);

return (
<GraphConfigContext.Provider value={graphConfig}>
<GraphConfigContext.Provider value={state.settings.graphConfig}>
<GraphControllerContext.Provider value={graphController}>
<ConnectingState data={state.data.present} connectState={state.connectState}>
<GraphStateContext.Provider value={contextValue}>
<ViewportContext.Provider value={state.viewport}>
<GraphValueContext.Provider value={state.data.present}>
<AlignmentLinesContext.Provider value={state.alignmentLines}>
{props.children}
{children}
</AlignmentLinesContext.Provider>
</GraphValueContext.Provider>
</ViewportContext.Provider>
Expand Down
42 changes: 32 additions & 10 deletions packages/ReactDagEditor/src/components/ReactDagEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import * as React from "react";
import { ContextMenuConfig, ContextMenuConfigContext } from "../contexts";
import { ContextMenuConfig, ContextMenuConfigContext, IDispatch } from "../contexts";
import { GraphController } from "../controllers/GraphController";
import { useConst } from "../hooks/useConst";
import type { IGraphState } from "../models/state";
import { Debug } from "../utils/debug";
import { noop } from "../utils/noop";
import { ErrorBoundary } from "./ErrorBoundary/ErrorBoundary";
import { GraphStateStore } from "./Graph/GraphStateStore";
import { IThemeProviderProps, ThemeProvider } from "./ThemeProvider";

/**
* ReactDagEditor props
*/
export interface IReactDagEditorProps extends IThemeProviderProps {
export interface IReactDagEditorProps<NodeData = unknown, EdgeData = unknown, PortData = unknown, Action = never>
extends IThemeProviderProps {
/**
* Additional css styles to apply to the container element.
*/
Expand All @@ -17,6 +22,8 @@ export interface IReactDagEditorProps extends IThemeProviderProps {
* Additional css class to apply to the container element.
*/
className?: string;
state: IGraphState<NodeData, EdgeData, PortData>;
dispatch: IDispatch<NodeData, EdgeData, PortData, Action>;
/**
* Fired when there is invalid data or config. The invalid data or config will be ignored to avoid crashing your app.
*/
Expand Down Expand Up @@ -48,17 +55,32 @@ export const ReactDagEditor: React.FunctionComponent<IReactDagEditorProps> = pro

const handleError = props.handleError?.bind(null);

const { theme, setTheme } = props;
const { theme, setTheme, state, dispatch, getGlobalEventTarget } = props;

const graphController = useConst(() => new GraphController(state, dispatch));
graphController.UNSAFE_latestState = state;
React.useLayoutEffect(() => {
graphController.state = state;
graphController.dispatch = dispatch;
graphController.getGlobalEventTargetImpl = getGlobalEventTarget;
}, [dispatch, getGlobalEventTarget, graphController, state]);
React.useEffect(() => {
return () => {
graphController.dispatch = noop;
};
}, [graphController]);

return (
<ErrorBoundary renderOnError={handleError}>
<ContextMenuConfigContext.Provider value={useConst(() => new ContextMenuConfig())}>
<ThemeProvider theme={theme} setTheme={setTheme}>
<div style={props.style} className={props.className}>
{props.children}
</div>
</ThemeProvider>
</ContextMenuConfigContext.Provider>
<GraphStateStore state={state} dispatch={dispatch} graphController={graphController}>
<ContextMenuConfigContext.Provider value={useConst(() => new ContextMenuConfig())}>
<ThemeProvider theme={theme} setTheme={setTheme}>
<div style={props.style} className={props.className}>
{props.children}
</div>
</ThemeProvider>
</ContextMenuConfigContext.Provider>
</GraphStateStore>
</ErrorBoundary>
);
};
1 change: 0 additions & 1 deletion packages/ReactDagEditor/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,3 @@ export * from "./StaticGraph/StaticGraph";
export * from "./Graph/IGraphProps";
export * from "./RegisterComponent";
export { defaultGetPositionFromEvent } from "../controllers";
export * from "./Graph/GraphStateStore";
18 changes: 10 additions & 8 deletions packages/ReactDagEditor/src/contexts/GraphStateContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { GraphConfigBuilder } from "../models/config/GraphConfigBuilder";
import type { IEvent } from "../models/event";
import type { IGap, IRectSize, ITransformMatrix, IViewport } from "../models/geometry";
import { GraphModel } from "../models/GraphModel";
import { GraphBehavior, IGraphState } from "../models/state";
import { GraphBehavior, IGraphSettings, IGraphState } from "../models/state";
import { Debug } from "../utils/debug";
import { resetUndoStack } from "../utils/history";

Expand Down Expand Up @@ -35,14 +35,16 @@ export const DEFAULT_NODE_MAX_VISIBLE_SIZE: IRectSize = {
height: NODE_MAX_VISIBLE_LENGTH
};

export const DEFAULT_GRAPH_SETTINGS: IGraphSettings = {
features: defaultFeatures,
graphConfig: GraphConfigBuilder.default().build(),
canvasBoundaryPadding: EMPTY_GAP,
nodeMinVisibleSize: DEFAULT_NODE_MIN_VISIBLE_SIZE,
nodeMaxVisibleSize: DEFAULT_NODE_MAX_VISIBLE_SIZE
};

export const EMPTY_GRAPH_STATE: IGraphState = {
settings: {
features: defaultFeatures,
graphConfig: GraphConfigBuilder.default().build(),
canvasBoundaryPadding: EMPTY_GAP,
nodeMinVisibleSize: DEFAULT_NODE_MIN_VISIBLE_SIZE,
nodeMaxVisibleSize: DEFAULT_NODE_MAX_VISIBLE_SIZE
},
settings: DEFAULT_GRAPH_SETTINGS,
behavior: GraphBehavior.default,
data: resetUndoStack(GraphModel.empty()),
viewport: {
Expand Down
28 changes: 12 additions & 16 deletions packages/ReactDagEditor/src/hooks/useGraphReducer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import * as React from "react";
import { emptyDummyNodes } from "../components/dummyNodes";
import { emptySelectBoxPosition } from "../components/Graph/SelectBox";
import { EMPTY_TRANSFORM_MATRIX, IDispatch, IDispatchCallback, IGraphReactReducer, IGraphReducer } from "../contexts";
import {
DEFAULT_GRAPH_SETTINGS,
EMPTY_TRANSFORM_MATRIX,
IDispatch,
IDispatchCallback,
IGraphReactReducer,
IGraphReducer
} from "../contexts";
import { ITransformMatrix } from "../models/geometry";
import { GraphModel } from "../models/GraphModel";
import { GraphBehavior, IGraphSettings, IGraphState } from "../models/state";
Expand All @@ -20,7 +27,7 @@ import { batchedUpdates } from "../utils/batchedUpdates";
import { useConst } from "./useConst";

export interface IGraphReducerInitializerParams<NodeData = unknown, EdgeData = unknown, PortData = unknown>
extends IGraphSettings<NodeData, EdgeData, PortData> {
extends Partial<IGraphSettings<NodeData, EdgeData, PortData>> {
data?: GraphModel<NodeData, EdgeData, PortData>;
transformMatrix?: ITransformMatrix;
}
Expand Down Expand Up @@ -52,21 +59,10 @@ export function useGraphReducer<NodeData = unknown, EdgeData = unknown, PortData
const [state, dispatchImpl] = React.useReducer(
reducer,
params,
({
data,
transformMatrix,
features,
graphConfig,
canvasBoundaryPadding,
nodeMaxVisibleSize,
nodeMinVisibleSize
}) => ({
({ data, transformMatrix, ...settings }): IGraphState => ({
settings: {
features,
graphConfig,
canvasBoundaryPadding,
nodeMaxVisibleSize,
nodeMinVisibleSize
...DEFAULT_GRAPH_SETTINGS,
...settings
},
data: resetUndoStack(data ?? GraphModel.empty()),
viewport: {
Expand Down
19 changes: 12 additions & 7 deletions packages/ReactDagEditor/stories/components/FeaturesDemo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ import {
GraphModel,
intellild marked this conversation as resolved.
Show resolved Hide resolved
GraphNodeState,
GraphPortState,
GraphStateStore,
hasState,
ICanvasNode,
ICanvasPort,
IGetConnectableParams,
INodeConfig,
IPortConfig,
IPortDrawArgs,
ReactDagEditor
} from "../../src";
import { INodeConfig } from "../../src/models/config/types";
import { useGraphReducer } from "../../src/hooks/useGraphReducer";
import { sampleGraphData } from "../data/sample-graph-1";

/** How to customize a node by "shape" by data.nodes[].shape */
Expand Down Expand Up @@ -250,12 +250,17 @@ const graphConfig = GraphConfigBuilder.default()
.build();

export const FeaturesDemo: React.FC = () => {
const [state, dispatch] = useGraphReducer(
{
graphConfig,
data: GraphModel.fromJSON(sampleGraphData)
},
undefined
);

return (
<ReactDagEditor style={{ width: "900px", height: "600px" }}>
{/** where to initialize your data */}
<GraphStateStore data={GraphModel.fromJSON(sampleGraphData)} graphConfig={graphConfig}>
<Graph />
</GraphStateStore>
<ReactDagEditor style={{ width: "900px", height: "600px" }} state={state} dispatch={dispatch}>
<Graph />
</ReactDagEditor>
);
};
42 changes: 20 additions & 22 deletions packages/ReactDagEditor/test/TestComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
import * as React from "react";
import {
applyDefaultPortsPosition,
GraphModel,
ICanvasData,
IEvent,
IGraphConfig,
IGraphReducer,
IGraphStateStoreProps
} from "../src";
import { Graph, GraphStateStore, IGraphProps, ReactDagEditor } from "../src/components";
import { applyDefaultPortsPosition, GraphModel, ICanvasData, IEvent, IGraphConfig, IGraphReducer } from "../src";
import { Graph, IGraphProps, ReactDagEditor } from "../src/components";
import { GraphController } from "../src/controllers/GraphController";
import { useGraphController } from "../src/hooks/context";
import { IGraphReducerInitializerParams, useGraphReducer } from "../src/hooks/useGraphReducer";
import Sample0 from "../test/unit/__data__/sample0.json";
import { defaultConfig } from "./unit/__mocks__/mockContext";

Expand All @@ -27,7 +20,8 @@ export interface ITestComponentProps {
graphConfig?: IGraphConfig;
middleware?: IGraphReducer;
graphProps?: Partial<IGraphProps>;
stateProps?: Partial<IGraphStateStoreProps>;
stateProps?: Partial<IGraphReducerInitializerParams>;
graph?: boolean;
}

let events: string[];
Expand All @@ -46,8 +40,10 @@ export const GraphControllerRef = React.forwardRef<GraphController>((_, ref) =>
return null;
});

const defaultData = GraphModel.fromJSON(data);

export const TestComponent = (props: React.PropsWithChildren<ITestComponentProps>) => {
const { graphProps, stateProps, graphConfig } = props;
const { graphProps, stateProps, graphConfig = defaultConfig, middleware, graph = true, data = defaultData } = props;
const onEvent = React.useCallback(
(event: IEvent) => {
graphProps?.onEvent?.(event);
Expand All @@ -57,17 +53,19 @@ export const TestComponent = (props: React.PropsWithChildren<ITestComponentProps
[graphProps?.onEvent]
);

const [state, dispatch] = useGraphReducer(
{
...stateProps,
graphConfig,
data
},
middleware
);

return (
<ReactDagEditor>
<GraphStateStore
{...stateProps}
data={props.data ?? GraphModel.fromJSON(data)}
middleware={props.middleware}
graphConfig={graphConfig ?? defaultConfig}
>
<Graph {...graphProps} onEvent={onEvent} />
{props.children}
</GraphStateStore>
<ReactDagEditor state={state} dispatch={dispatch}>
{graph && <Graph {...graphProps} onEvent={onEvent} />}
{props.children}
</ReactDagEditor>
);
};