Add state management, undo / redo capabilities and component API - #324
Add state management, undo / redo capabilities and component API #324handreyrc wants to merge 8 commits into
Conversation
✅ Deploy Preview for openworkflow-editor ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
There was a problem hiding this comment.
Pull request overview
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Adds editor state/history management to support undo/redo (including viewport + selection restore) and exposes a new imperative API on the editor ref for integration/testing.
Changes:
- Introduces generic
useHistoryand workflow-specificuseWorkflowHistoryhooks, plus structural equality comparison to avoid redundant history entries. - Refactors
Diagramand store context provider to seed/history-track models and restore viewport/selection during undo/redo. - Adds Storybook feature story + tests for history behavior and ref API; adds
fast-equalsdependency.
Reviewed changes
Copilot reviewed 18 out of 20 changed files in this pull request and generated 10 comments.
Show a summary per file
| File | Description |
|---|---|
| pnpm-workspace.yaml | Adds fast-equals to the workspace catalog. |
| packages/open-workflow-diagram-editor/package.json | Adds fast-equals dependency for structural comparisons. |
| packages/open-workflow-diagram-editor/src/core/hooks/structuralEqual.ts | Implements constructor-agnostic deep structural equality with circular handling. |
| packages/open-workflow-diagram-editor/src/react-flow/hooks/useHistory.ts | Adds generic past/present/future history reducer + hook with stack cap. |
| packages/open-workflow-diagram-editor/src/react-flow/hooks/useWorkflowHistory.ts | Adds workflow-aware history snapshots (model/viewport/selection) + undo/redo behavior. |
| packages/open-workflow-diagram-editor/src/store/DiagramEditorContext.tsx | Extends context type with history + content-format APIs. |
| packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx | Seeds history from content, exposes imperative API, and wires history into context. |
| packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx | Gates ReactFlow mount until first layout, submits snapshots, and restores viewport on undo/redo. |
| packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx | Refactors editor shell + docs and attempts to expose imperative API via context provider. |
| packages/open-workflow-diagram-editor/src/styles.css | Removes stray trailing whitespace. |
| packages/open-workflow-diagram-editor/stories/features/UndoRedoEditor.tsx | Adds a Storybook wrapper with undo/redo toolbar + window-exposed ref. |
| packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx | Adds Storybook docs + interactive story for undo/redo and ref API. |
| packages/open-workflow-diagram-editor/tests/react-flow/hooks/useHistory.test.ts | Adds unit tests for generic history reducer/hook behavior. |
| packages/open-workflow-diagram-editor/tests/react-flow/hooks/useWorkflowHistory.test.ts | Adds tests for workflow history snapshots, equality behavior, and viewport restore. |
| packages/open-workflow-diagram-editor/tests/core/hooks/structuralEqual.test.ts | Adds comprehensive tests for structural equality across class/plain + circular refs. |
| packages/open-workflow-diagram-editor/tests/react-flow/diagram/Diagram.test.tsx | Updates tests to wait for delayed ReactFlow mount after layout gating. |
| packages/open-workflow-diagram-editor/tests/store/DiagramEditorContextProvider.test.tsx | Updates expected render cycles due to history seeding effect. |
| packages/open-workflow-diagram-editor/tests/diagram-editor/DiagramEditor.test.tsx | Expands tests for ref API (undo/redo/getContent/setContent) and async canvas-dependent UI. |
| .changeset/state-management.md | Publishes a minor version bump describing new state/history + API. |
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| // setIsReadOnly is intentionally inoperative: isReadOnly is driven by | ||
| // props, not internal state, so there is no local setter to dispatch to. | ||
| setIsReadOnly: () => {}, |
There was a problem hiding this comment.
Fixed! I opted for removing setIsReadOnly from DiagramEditorContextType.
@lornakelly @fantonangeli @kumaradityaraj, lets be careful with this one. I couldn't find any side effect but it is good to double check it.
There was a problem hiding this comment.
@handreyrc opening the preview and settings isReadOnly to false, I could not move the nodes in the diagram. Am I missing somenthing?
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 19 out of 21 changed files in this pull request and generated no new comments.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (8)
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:51
- The comment says the content format is fixed at mount time, but
setContent()can updatecontentFormat.current. This is misleading documentation and makes it harder to reason aboutgetContent()behavior.
// Detect the serialization format once from the initial content prop.
// JSON content starts with `{` (after trimming); everything else is YAML.
// We use a ref so the format is fixed at mount time and never flips mid-session
// (an undo/redo should round-trip back in the same format the host provided).
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:89
- Undo/redo changes the
modelfrom history, buterrorsare currently tied toprops.content. Derivingerrorsfrom the currentmodelkeeps validation/error-highlighting consistent across undo/redo snapshots, while still using parse errors when no model is available.
// parseWorkflow drives both errors and the external-content model source.
// errors are never part of a snapshot — always recomputed from current content.
const { model: parsedModel, errors } = React.useMemo(
() => parseWorkflow(props.content),
[props.content],
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:131
- If
applyAutoLayoutthrows on the initial render,layoutReadystaysfalseand the ReactFlow canvas never mounts, leaving the editor blank. Consider falling back to rendering the un-laid-out graph (or at least settinglayoutReadyto true) on non-abort errors.
.catch((error) => {
if (error.name === "AbortError") {
return;
}
console.error("Failed to apply auto-layout:", error);
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:86
- This prop doc says the serialization format is preserved for the lifetime of the component, but the ref API docs (and tests) indicate the format can change after a successful
setContent()call. Please align the documentation with the actual behavior.
* The serialisation format is auto-detected on first load and preserved for
* the lifetime of the component — see `getContent()` on `DiagramEditorRef`.
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:183
DiagramEditorcomputes a fallbacklocale(and uses it for<I18nProvider>and thelangattribute), butDiagramEditorBodypasses the rawprops.localedown intoDiagramEditorContextProvider. Iflocaleis omitted at runtime, the context provider can receiveundefinedand diverge from the I18n provider.
props={props}
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:19
- Undo/redo changes the
modelfrom history, buterrorsare derived fromparseWorkflow(props.content)and therefore won’t match the restored snapshot. This can make error highlighting inconsistent after undo/redo or after imperativesetContent()(which doesn’t changeprops.content).
This issue also appears on line 85 of the same file.
import { buildFlatGraph, getTaskReferences, parseWorkflow } from "../core";
packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx:101
- The Storybook docs state that
getContent()format is fixed at mount time, but the implementation/tests describe format switching after a successfulsetContent()call. This section is internally inconsistent (it later says the format becomes the new format) — please make the docs unambiguous.
Serialises the current model back to the **same format the editor received
on first load**: if the initial \`content\` prop was JSON it returns JSON; if
it was YAML it returns YAML. The format is fixed at mount time and preserved
for the lifetime of the component, so undo/redo always round-trips in the
original format. Returns \`""\` when no valid model has been loaded yet.
packages/open-workflow-diagram-editor/tests/test-utils/render-helpers.tsx:45
DiagramEditorContextTypenow requirescontentFormatand the history API members, but the test mock context value doesn’t provide them. This should be a type error and may also cause runtime issues in tests that rely on these fields.
edges: [],
taskReferences: new Set(),
selectedNodeId: null,
setLocale: noop,
setEdges: noop,
setNodes: noop,
|
Thanks for PR @handreyrc, looks really good, have just tested the story so far but noticed a couple of things:
Screen.Recording.2026-08-12.at.10.46.38.mov |
fantonangeli
left a comment
There was a problem hiding this comment.
I left a small comment which you can consider
| export type HistoryState<T> = { | ||
| /** Past snapshots, oldest first. Length is capped at HISTORY_STACK_SIZE. */ | ||
| past: T[]; | ||
| /** The current snapshot. Null when the history has not been initialised yet. */ | ||
| present: T | null; | ||
| /** Future snapshots available for redo. Index 0 is the most recently undone entry. */ | ||
| future: T[]; | ||
| }; |
There was a problem hiding this comment.
The current history implementation uses three separate arrays (past, present, future) which works correctly. However, I wanted to share an alternative pattern that might simplify the code:
type HistoryState<T> = {
history: T[];
presentIndex: number;
};This way future is simply presentIndex+1.
Wdyt?
There was a problem hiding this comment.
Sure, if we can make it simpler why not?!
I changed the implementation following your recommendation.
Thanks!
| // setIsReadOnly is intentionally inoperative: isReadOnly is driven by | ||
| // props, not internal state, so there is no local setter to dispatch to. | ||
| setIsReadOnly: () => {}, |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 18 out of 20 changed files in this pull request and generated 1 comment.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (3)
packages/open-workflow-diagram-editor/src/core/hooks/structuralEqual.ts:81
innerEqualsdoesn’t short-circuit when comparing the same reference (e.g.a === b). In this PR the history pipeline callsstructuralEqual(present.model, model)frequently with identical object references, so missing this fast-path can turn routine viewport/selection updates into expensive deep traversals.
): boolean {
if (isObjectLike(a) && isObjectLike(b)) {
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:221
- Viewport pan/zoom changes don’t appear to be persisted into the current history snapshot:
submitModel(...)is only called after layout cycles (and indirectly on selection changes via the effect deps), but there is no subscription to viewport changes. That means if a user pans/zooms and then later triggers an undo/redo, the restored viewport can be stale (typically the last fitView/restored value, not where the user was looking). Hook into React Flow viewport updates (e.g. a viewport/move end callback or store subscription) and callsubmitModel(model, viewport, selectedNodeId)souseWorkflowHistorycan update the present snapshot without pushing a new entry.
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onSelectionChange={onSelectionChange}
onlyRenderVisibleElements={true}
zoomOnDoubleClick={false}
elementsSelectable={true}
panOnScroll={true}
panOnDrag={false}
zoomOnScroll={false}
preventScrolling={true}
selectionOnDrag={true}
fitView
fitViewOptions={{ ...FIT_VIEW_OPTIONS, duration: 0 }}
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:51
- The comment says
contentFormatis fixed at mount time and “never flips mid-session”, butsetContent()later updatescontentFormat.current(andcontentFormatVersionexists specifically to re-render when it changes). This is misleading documentation and makes it harder to reason about the ref API contract.
// Detect the serialization format once from the initial content prop.
// JSON content starts with `{` (after trimming); everything else is YAML.
// We use a ref so the format is fixed at mount time and never flips mid-session
// (an undo/redo should round-trip back in the same format the host provided).
5aa160c to
0a70df4
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 18 out of 20 changed files in this pull request and generated 1 comment.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (1)
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:119
- DiagramEditorContent renders ParsingErrorPage whenever model is null. Since DiagramEditorContextProvider seeds history in a useEffect, valid content briefly produces model=null on the initial render, causing an incorrect error page flicker. Gate the error page on the presence of actual parse errors (or render a neutral placeholder) until the initial parse/seed completes.
const { model } = useDiagramEditorContext();
return model === null ? (
<ParsingErrorPage />
) : (
<Diagram divRef={diagramDivRef} colorMode={colorMode} />
);
The toolbar does not make sense in all contexts the component can be used, however, we need it to showcase how to consume the API so it was completely moved to the "Undo Redo" story and is not part of the editor component anymore. Thanks for reviewing this PR! |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 19 out of 21 changed files in this pull request and generated no new comments.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (2)
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:121
- Selection preservation during layout rebuild only stamps
selected: trueonto the selected node. If the selected element is an edge, the rebuilt edge list will not mark it selected, so React Flow will drop the edge selection and z-index won’t reflect the selection.
const stampedNodes = selectedId
? nodes.map((n) => (n.id === selectedId ? { ...n, selected: true } : n))
: nodes;
setNodes(stampedNodes);
setEdges(applyEdgeZIndex(edges));
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:99
- onSelectionChange only considers selected nodes and ignores selected edges, so selecting an edge clears selectedNodeId. This prevents edge selection from being preserved across content reloads and undo/redo snapshots (which expect node/edge IDs).
This issue also appears on line 117 of the same file.
const onSelectionChange = React.useCallback<RF.OnSelectionChangeFunc>(
({ nodes: selectedNodes }) => setSelectedNodeId(selectedNodes[0]?.id ?? null),
[setSelectedNodeId],
);
|
@fantonangeli @lornakelly @kumaradityaraj , This PR is ready for reviewing again. Thanks |
fantonangeli
left a comment
There was a problem hiding this comment.
LGTM, thanks a lot @handreyrc
|
|
||
| const getContent = React.useCallback(() => { | ||
| if (!model) return ""; | ||
| const plain = JSON.parse(JSON.stringify(model)) as Record<string, unknown>; |
There was a problem hiding this comment.
Wondering can we use the sdk serialize here instead? So we dont get anything that diverges?
There was a problem hiding this comment.
The code was changed to use the SDK for seralization.
However, there is a bug in the SDK, the serialization to YAML is broken.
The workflow.serialize("yaml") fails because normalize() returns a Workflow class instance and js-yaml rejects non-plain objects.
For now a temporary workaround was implemented and a TODO added to update the code once the SDK is Fixed.
| return; | ||
| } | ||
| // Handle other auto-layout errors to prevent unhandled promise rejections | ||
| console.error("Failed to apply auto-layout:", error); |
There was a problem hiding this comment.
Should we display error page here instead of just a console error?
There was a problem hiding this comment.
| @@ -0,0 +1,176 @@ | |||
| /* | |||
| * Copyright 2021-Present The Open Workflow Specification Authors | |||
There was a problem hiding this comment.
dont think this should be in a hooks directory? Just in core folder instead?
There was a problem hiding this comment.
|
@handreyrc I found a bug with the zoom:
Testing this with the last PR merged on Screencast.From.2026-08-13.12-35-13.mp4 |
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 24 changed files in this pull request and generated 1 comment.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (12)
packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx:1
- The story docs contradict themselves: one section states the format is fixed at mount time, while another states
setContent()updates the format for futuregetContent()calls. Align the docs with the implemented behavior (and keep it consistent with theDiagramEditorRefdocstring).
/*
packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx:1
- The story docs contradict themselves: one section states the format is fixed at mount time, while another states
setContent()updates the format for futuregetContent()calls. Align the docs with the implemented behavior (and keep it consistent with theDiagramEditorRefdocstring).
/*
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:70
layoutErroris latched permanently: once set, the component returns<ErrorPage />and never attempts layout again, even if subsequent model changes would succeed. ResetlayoutErrorto null at the start of the layout effect (or whenmodel/errorschange) so recovery is possible without a full remount.
const [layoutError, setLayoutError] = React.useState<Error | null>(null);
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:188
layoutErroris latched permanently: once set, the component returns<ErrorPage />and never attempts layout again, even if subsequent model changes would succeed. ResetlayoutErrorto null at the start of the layout effect (or whenmodel/errorschange) so recovery is possible without a full remount.
.catch((error) => {
if (error.name === "AbortError") {
return;
}
setLayoutError(error instanceof Error ? error : new Error(String(error)));
});
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:140
selectedNodeIdcan represent either a node or an edge (e.g.resolveSelectedIdchecks both), but the selection preservation here only stampsselected: trueon nodes. If an edge is selected, it will be lost when edges are replaced, andapplyEdgeZIndexwill never seeedge.selected. Preserve selection for edges too (e.g., stampselected: trueon the matching edge before applying zIndex).
// Preserve selection: stamp selected:true on the node that matches
// selectedNodeId so React Flow does not clear it when nodes are replaced.
const selectedId = selectedNodeIdRef.current;
const stampedNodes = selectedId
? nodes.map((n) => (n.id === selectedId ? { ...n, selected: true } : n))
: nodes;
setNodes(stampedNodes);
setEdges(applyEdgeZIndex(edges));
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:150
- The component computes a resolved
locale(withdetectLocale(...)fallback) and uses it for the rootlang, but passesprops.localeintoDiagramEditorContextProvider. If a JS consumer omits the prop (or passes undefined), the provider can receive an invalid locale while the root uses the fallback. Pass the resolvedlocalevariable into the provider to keep behavior consistent.
<DiagramEditorContextProvider
ref={editorRef}
content={props.content}
isReadOnly={props.isReadOnly}
locale={props.locale}
>
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:169
- The component computes a resolved
locale(withdetectLocale(...)fallback) and uses it for the rootlang, but passesprops.localeintoDiagramEditorContextProvider. If a JS consumer omits the prop (or passes undefined), the provider can receive an invalid locale while the root uses the fallback. Pass the resolvedlocalevariable into the provider to keep behavior consistent.
const locale = React.useMemo(() => {
const supportedLocales = Object.keys(dictionaries);
return props.locale ?? detectLocale(supportedLocales);
}, [props.locale]);
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:52
- The comment says the content format is fixed at mount time and never flips, but
setContentexplicitly updatescontentFormat.current. Please update the comment (and any related docs) to reflect the actual behavior: either (a) format is fixed for the session, or (b) format tracks the most recently successfully loaded content.
// Detect the serialization format once from the initial content prop.
// JSON content starts with `{` (after trimming); everything else is YAML.
// We use a ref so the format is fixed at mount time and never flips mid-session
// (an undo/redo should round-trip back in the same format the host provided).
const contentFormat = React.useRef<ContentFormat>(
props.content.trimStart().startsWith("{") ? "json" : "yaml",
);
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:146
- The comment says the content format is fixed at mount time and never flips, but
setContentexplicitly updatescontentFormat.current. Please update the comment (and any related docs) to reflect the actual behavior: either (a) format is fixed for the session, or (b) format tracks the most recently successfully loaded content.
const newFormat: ContentFormat = content.trimStart().startsWith("{") ? "json" : "yaml";
if (newFormat !== contentFormat.current) {
contentFormat.current = newFormat;
setContentFormatVersion((v) => v + 1);
}
packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx:191
navigator.clipboard.writeText(...)can reject (permissions/HTTP context), which will currently create an unhandled promise rejection in Storybook. Add a.catch(...)handler (and ideally surface a message/state) to keep the story stable.
const copyToClipboard = () => {
navigator.clipboard.writeText(getContentText).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
});
};
packages/open-workflow-diagram-editor/tests/store/DiagramEditorContextProvider.test.tsx:82
- Asserting exact render counts is brittle across React versions, StrictMode settings, and internal refactors (especially with effects and concurrent rendering). Prefer asserting observable behavior (e.g., context values, errors, history state) rather than the number of renders.
// Two rendering cycles are expected:
// 1- initial render, 2- useEffect seeding history from parsedModel
expect(renderCount).toHaveTextContent(/2/i);
packages/open-workflow-diagram-editor/tests/react-flow/diagram/Diagram.test.tsx:350
- This timing-based wait is likely to be flaky in CI and slows the suite. Prefer fake timers (
vi.useFakeTimers()+ advancing timers) or waiting on a deterministic condition viawaitForrather than sleeping for a fixed duration.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
a239de8 to
99d29d8
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 24 changed files in this pull request and generated no new comments.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (7)
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:55
contentFormatis updated insetContent(...), but not whenprops.contentchanges. This makesgetContent()potentially serialize in the wrong format after an externalcontentprop update (and contradicts theDiagramEditorRefdoc/comment that format tracks the latest successfully loaded content). UpdatecontentFormatinside theprops.contenteffect as well (only when parsing succeeded) so the format stays consistent regardless of whether content changes come from props or the imperative API.
const [contentFormat, setContentFormat] = React.useState<ContentFormat>(
props.content.trimStart().startsWith("{") ? "json" : "yaml",
);
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:102
contentFormatis updated insetContent(...), but not whenprops.contentchanges. This makesgetContent()potentially serialize in the wrong format after an externalcontentprop update (and contradicts theDiagramEditorRefdoc/comment that format tracks the latest successfully loaded content). UpdatecontentFormatinside theprops.contenteffect as well (only when parsing succeeded) so the format stays consistent regardless of whether content changes come from props or the imperative API.
React.useEffect(() => {
const { model: parsedModel, errors: parsedErrors } = parseWorkflow(props.content);
setErrors(parsedErrors);
if (parsedModel === null) {
// Null model is never stored in history.
return;
}
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:140
- Selection preservation is only applied to nodes. If
selectedNodeIdpoints to an edge (your provider explicitly allows this viaresolveSelectedId), React Flow can still clear edge selection when edges are replaced, andapplyEdgeZIndexwon’t elevate the selected edge becauseedge.selectedis never stamped. Consider stampingselected: trueon the matching edge as well (and then applying zIndex) so edge selections survive re-layout consistently.
// Preserve selection: stamp selected:true on the node that matches
// selectedNodeId so React Flow does not clear it when nodes are replaced.
const selectedId = selectedNodeIdRef.current;
const stampedNodes = selectedId
? nodes.map((n) => (n.id === selectedId ? { ...n, selected: true } : n))
: nodes;
setNodes(stampedNodes);
setEdges(applyEdgeZIndex(edges));
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:150
DiagramEditorcomputes a resolvedlocale(withdetectLocale) for<I18nProvider>and the rootlangattribute, but passes the rawprops.localeintoDiagramEditorContextProvider. This can desyncuseI18n()(resolved locale) fromuseDiagramEditorContext().locale(raw locale). Pass the resolvedlocalevariable into the context provider to keep the UI language and context locale consistent.
<DiagramEditorContextProvider
ref={editorRef}
content={props.content}
isReadOnly={props.isReadOnly}
locale={props.locale}
>
packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx:269
- The modals are missing dialog semantics: the container uses
role="none"and there’s norole="dialog",aria-modal="true", or labeling viaaria-labelledby. Even for Storybook-only UI, adding proper dialog roles/labels improves keyboard + screen-reader behavior and avoids regressions if this pattern is copied into product code.
{getContentOpen && (
<div style={overlayStyle} onMouseDown={() => setGetContentOpen(false)} role="presentation">
<div style={dialogStyle} onMouseDown={(e) => e.stopPropagation()} role="none">
<div style={dialogHeaderStyle}>Get Content</div>
<textarea
style={{ ...textareaStyle, cursor: "default", userSelect: "text" }}
value={getContentText}
readOnly
spellCheck={false}
/>
packages/open-workflow-diagram-editor/tests/store/DiagramEditorContextProvider.test.tsx:82
- These assertions depend on an exact render count, which is an implementation detail and tends to become brittle across React/testing-library upgrades and minor refactors (especially around effects). Prefer asserting on observable state/output changes (e.g., that
model/errorsare correct after seeding) rather than the number of render cycles.
// Two rendering cycles are expected:
// 1- initial render, 2- useEffect seeding history from parsedModel
expect(renderCount).toHaveTextContent(/2/i);
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:154
- The post-layout
setTimeout(..., 0)isn’t cleared in the effect cleanup. While theisActiveguard prevents state updates, the queued task can still run after unmount and call intoreactFlowInstance. Track the timeout id and clear it in the cleanup to avoid stray calls and make the lifecycle more robust under rapid content changes/unmounts.
// Post-layout viewport work runs in a zero-delay timeout so React Flow has
// processed the new nodes before we read or set the viewport.
setTimeout(() => {
if (!isActive) return;
const pendingRestore = pendingViewportRestoreRef.current;
if (pendingRestore) {
// Undo/redo — restore saved viewport instead of fitting.
reactFlowInstance.setViewport(pendingRestore);
clearPendingViewportRestoreRef.current();
Signed-off-by: handreyrc <handrey.cunha@gmail.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 24 changed files in this pull request and generated no new comments.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (7)
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:137
- Selection stamping during layout only marks nodes as selected. If the current selection is an edge ID, React Flow will drop the edge selection when edges are replaced, and applyEdgeZIndex() will never treat the selected edge as selected. Stamp the selected edge too before applying z-index.
// Preserve selection: stamp selected:true on the node that matches
// selectedNodeId so React Flow does not clear it when nodes are replaced.
const selectedId = selectedNodeIdRef.current;
const stampedNodes = selectedId
? nodes.map((n) => (n.id === selectedId ? { ...n, selected: true } : n))
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:102
- When props.content becomes unparseable after a valid model was loaded, this effect returns early and leaves the previous model in history as the rendered model. That means the editor can show a diagram that no longer matches the content prop, and the ParsingErrorPage will never appear for subsequent parse failures. Consider resetting history/present to null (or providing a reset action in useWorkflowHistory/useHistory) when parsedModel is null.
React.useEffect(() => {
const { model: parsedModel, errors: parsedErrors } = parseWorkflow(props.content);
setErrors(parsedErrors);
if (parsedModel === null) {
// Content is unparseable — reset history to null so downstream consumers
// (e.g. DiagramEditorContent) see model === null and render the error page
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:115
- onSelectionChange only considers selected nodes, so selecting an edge will clear selection (selectedNodeId becomes null) and edge selection cannot be preserved/restored (undo/redo, content reload). Include selected edges when computing the selected ID.
This issue also appears on line 133 of the same file.
const onSelectionChange = React.useCallback<RF.OnSelectionChangeFunc>(
({ nodes: selectedNodes }) => setSelectedNodeId(selectedNodes[0]?.id ?? null),
[setSelectedNodeId],
);
packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx:588
- The story docs claim getContent()'s format is fixed at mount time, but later in the same docs setContent() is described as switching the format (and the implementation/tests also switch formats). Update this section to avoid contradicting the behavior.
Serialises the current model back to the **same format the editor received
on first load**: if the initial \`content\` prop was JSON it returns JSON; if
it was YAML it returns YAML. The format is fixed at mount time and preserved
for the lifetime of the component, so undo/redo always round-trips in the
original format. Returns \`""\` when no valid model has been loaded yet.
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:124
- Once layoutError is set, the component permanently renders the ErrorPage even if a later model/errors change would allow layout to succeed, because layoutError is never cleared. Clear layoutError when starting a new layout attempt (or on success).
React.useEffect(() => {
let isActive = true;
let abortController: AbortController | null = null;
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:111
- contentFormat is initialised from the initial content prop and updated by setContent(), but it is not updated when the external content prop changes. If the host swaps YAML↔JSON via props, getContent() will serialize using a stale format.
// In read-only mode the placeholder viewport is acceptable since fitView always runs.
React.useEffect(() => {
const { model: parsedModel, errors: parsedErrors } = parseWorkflow(props.content);
setErrors(parsedErrors);
if (parsedModel === null) {
// Content is unparseable — reset history to null so downstream consumers
// (e.g. DiagramEditorContent) see model === null and render the error page
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:86
- The content prop doc says the serialization format is preserved for the lifetime of the component, but the implementation explicitly allows the format to change after a successful setContent() call. Align this comment with the actual contract (format follows the latest successfully loaded content and is preserved across undo/redo).
* Updating this prop (e.g. from an addon panel) re-parses the workflow and,
* in edit mode, pushes a new history entry if the model changed structurally.
* The serialisation format is auto-detected on first load and preserved for
* the lifetime of the component — see `getContent()` on `DiagramEditorRef`.
Good catch! It is fixed. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 24 changed files in this pull request and generated no new comments.
Files not reviewed (1)
- pnpm-lock.yaml: Generated file
Suppressed comments (6)
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:137
- Selection preservation during layout only stamps
selected: trueonto nodes. If the current selection is an edge (or if edge selection is later supported), replacing theedgesarray after auto-layout can clear the selection in React Flow. Stamp the selection onto edges as well before setting them into state.
// Preserve selection: stamp selected:true on the node that matches
// selectedNodeId so React Flow does not clear it when nodes are replaced.
const selectedId = selectedNodeIdRef.current;
const stampedNodes = selectedId
? nodes.map((n) => (n.id === selectedId ? { ...n, selected: true } : n))
packages/open-workflow-diagram-editor/stories/features/UndoRedo.stories.tsx:588
- The docs for
getContent()are internally inconsistent: they say the serialization format is fixed at mount time, but thesetContent()section below says the format is auto-detected from the supplied string and becomes the new format. This should match the actual API behavior (format follows the most recently successfully loaded content).
Serialises the current model back to the **same format the editor received
on first load**: if the initial \`content\` prop was JSON it returns JSON; if
it was YAML it returns YAML. The format is fixed at mount time and preserved
for the lifetime of the component, so undo/redo always round-trips in the
original format. Returns \`""\` when no valid model has been loaded yet.
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:115
onSelectionChangeonly tracks selected nodes and ignores selected edges, but the rest of the codebase (history snapshot + docs) treatsselectedNodeIdas a node-or-edge selection. This causes edge selection to be dropped and prevents undo/redo from restoring edge selection.
This issue also appears on line 133 of the same file.
const onSelectionChange = React.useCallback<RF.OnSelectionChangeFunc>(
({ nodes: selectedNodes }) => setSelectedNodeId(selectedNodes[0]?.id ?? null),
[setSelectedNodeId],
);
packages/open-workflow-diagram-editor/src/react-flow/diagram/Diagram.tsx:124
- Once
layoutErroris set, it is never cleared, so the component will keep rendering the auto-layout error page even if subsequent model/content updates would succeed. Clearing the error at the start of the layout effect allows recovery when content changes.
React.useEffect(() => {
let isActive = true;
let abortController: AbortController | null = null;
packages/open-workflow-diagram-editor/src/diagram-editor/DiagramEditor.tsx:185
DiagramEditorcomputes a normalized/fallbacklocalefor thelangattribute andI18nProvider, but it passes the rawprops.localeintoDiagramEditorContextProvider. This can lead to the context/store using a different locale than the i18n provider (and breaks the fallback whenprops.localeis missing/unsupported at runtime). Pass the normalizedlocalethrough instead.
<DiagramEditorBody
diagramDivRef={diagramDivRef}
resolvedColorMode={resolvedColorMode}
props={props}
editorRef={ref}
packages/open-workflow-diagram-editor/src/store/DiagramEditorContextProvider.tsx:100
- When the external
contentprop changes between YAML and JSON,contentFormatis not updated (it’s only updated bysetContent). This can makegetContent()serialize in the wrong format after a host-driven content reload, which conflicts with the contract that format follows the last successfully loaded content and is preserved across undo/redo.
React.useEffect(() => {
const { model: parsedModel, errors: parsedErrors } = parseWorkflow(props.content);
setErrors(parsedErrors);
if (parsedModel === null) {
|
@lornakelly @fantonangeli @kumaradityaraj, This PR is ready for reviewing again. Thanks |
Closes #318
Summary
This PR adds state management as the model changes, undo/redo capabilities by handling a stack of states, and implements an API to expose those features.
Changes
getContent,setContent,undo,redo,canUndo,canRedo, andcolorMode, so it is possible to interact with the editor component by exposing the editor'srefand calling those functions from the browser console, making it easier to integrate with external components.DiagramEditor, store, diagram error handling, and I18n were refactored and optimized to accommodate state management and the changes in thecontextProvider.fast-equalslibrary to detect structural changes between the current model and the new model.