Skip to content

feat: MoveCollection COMPASS-9434 #7060

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

Merged
merged 10 commits into from
Jul 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/compass-data-modeling/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@
"@mongodb-js/compass-app-stores": "^7.48.1",
"@mongodb-js/compass-components": "^1.40.0",
"@mongodb-js/compass-connections": "^1.62.1",
"@mongodb-js/compass-editor": "^0.42.0",
"@mongodb-js/compass-logging": "^1.7.4",
"@mongodb-js/compass-telemetry": "^1.10.2",
"@mongodb-js/compass-user-data": "^0.7.4",
Expand Down
191 changes: 35 additions & 156 deletions packages/compass-data-modeling/src/components/diagram-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { connect } from 'react-redux';
import type { MongoDBJSONSchema } from 'mongodb-schema';
import type { DataModelingState } from '../store/reducer';
import {
applyEdit,
applyInitialLayout,
moveCollection,
getCurrentDiagramFromState,
selectCurrentModel,
} from '../store/diagram';
Expand All @@ -23,11 +23,8 @@ import {
css,
spacing,
Button,
palette,
ErrorSummary,
useDarkMode,
} from '@mongodb-js/compass-components';
import { CodemirrorMultilineEditor } from '@mongodb-js/compass-editor';
import { cancelAnalysis, retryAnalysis } from '../store/analysis-process';
import {
Diagram,
Expand All @@ -36,8 +33,7 @@ import {
useDiagram,
applyLayout,
} from '@mongodb-js/diagramming';
import type { Edit, StaticModel } from '../services/data-model-storage';
import { UUID } from 'bson';
import type { StaticModel } from '../services/data-model-storage';
import DiagramEditorToolbar from './diagram-editor-toolbar';
import ExportDiagramModal from './export-diagram-modal';
import { useLogger } from '@mongodb-js/compass-logging/provider';
Expand Down Expand Up @@ -119,49 +115,23 @@ const modelPreviewStyles = css({
minHeight: 0,
});

const editorContainerStyles = css({
display: 'flex',
flexDirection: 'column',
gap: 8,
boxShadow: `0 0 0 2px ${palette.gray.light2}`,
});

const editorContainerApplyContainerStyles = css({
padding: spacing[200],
justifyContent: 'flex-end',
gap: spacing[200],
display: 'flex',
width: '100%',
alignItems: 'center',
});

const editorContainerPlaceholderButtonStyles = css({
paddingLeft: 8,
paddingRight: 8,
alignSelf: 'flex-start',
display: 'flex',
gap: spacing[200],
paddingTop: spacing[200],
});

const DiagramEditor: React.FunctionComponent<{
diagramLabel: string;
step: DataModelingState['step'];
model: StaticModel | null;
editErrors?: string[];
onRetryClick: () => void;
onCancelClick: () => void;
onApplyClick: (edit: Omit<Edit, 'id' | 'timestamp'>) => void;
onApplyInitialLayout: (positions: Record<string, [number, number]>) => void;
onMoveCollection: (ns: string, newPosition: [number, number]) => void;
}> = ({
diagramLabel,
step,
model,
editErrors,
onRetryClick,
onCancelClick,
onApplyClick,
onApplyInitialLayout,
onMoveCollection,
}) => {
const { log, mongoLogId } = useLogger('COMPASS-DATA-MODELING-DIAGRAM-EDITOR');
const isDarkMode = useDarkMode();
Expand All @@ -180,54 +150,6 @@ const DiagramEditor: React.FunctionComponent<{
[diagram]
);

const [applyInput, setApplyInput] = useState('{}');

const isEditValid = useMemo(() => {
try {
JSON.parse(applyInput);
return true;
} catch {
return false;
}
}, [applyInput]);

const applyPlaceholder =
(type: 'AddRelationship' | 'RemoveRelationship') => () => {
let placeholder = {};
switch (type) {
case 'AddRelationship':
placeholder = {
type: 'AddRelationship',
relationship: {
id: new UUID().toString(),
relationship: [
{
ns: 'db.sourceCollection',
cardinality: 1,
fields: ['field1'],
},
{
ns: 'db.targetCollection',
cardinality: 1,
fields: ['field2'],
},
],
isInferred: false,
},
};
break;
case 'RemoveRelationship':
placeholder = {
type: 'RemoveRelationship',
relationshipId: new UUID().toString(),
};
break;
default:
throw new Error(`Unknown placeholder ${type}`);
}
setApplyInput(JSON.stringify(placeholder, null, 2));
};

const edges = useMemo(() => {
return (model?.relationships ?? []).map((relationship): EdgeProps => {
const [source, target] = relationship.relationship;
Expand All @@ -241,31 +163,6 @@ const DiagramEditor: React.FunctionComponent<{
});
}, [model?.relationships]);

const applyInitialLayout = useCallback(async () => {
try {
const { nodes: positionedNodes } = await applyLayout(
nodes,
edges,
'LEFT_RIGHT'
);
onApplyInitialLayout(
Object.fromEntries(
positionedNodes.map((node) => [
node.id,
[node.position.x, node.position.y],
])
)
);
} catch (err) {
log.error(
mongoLogId(1_001_000_361),
'DiagramEditor',
'Error applying layout:',
err
);
}
}, [edges, log, mongoLogId, onApplyInitialLayout]);

const nodes = useMemo<NodeProps[]>(() => {
return (model?.collections ?? []).map(
(coll): NodeProps => ({
Expand All @@ -290,6 +187,31 @@ const DiagramEditor: React.FunctionComponent<{
);
}, [model?.collections]);

const applyInitialLayout = useCallback(async () => {
try {
const { nodes: positionedNodes } = await applyLayout(
nodes,
edges,
'LEFT_RIGHT'
);
onApplyInitialLayout(
Object.fromEntries(
positionedNodes.map((node) => [
node.id,
[node.position.x, node.position.y],
])
)
);
} catch (err) {
log.error(
mongoLogId(1_001_000_361),
'DiagramEditor',
'Error applying layout:',
err
);
}
}, [edges, log, nodes, mongoLogId, onApplyInitialLayout]);

useEffect(() => {
if (nodes.length === 0) return;
const isInitialState = nodes.some(
Expand All @@ -300,8 +222,10 @@ const DiagramEditor: React.FunctionComponent<{
return;
}
if (!areNodesReady) {
void diagram.fitView();
setAreNodesReady(true);
setTimeout(() => {
void diagram.fitView();
});
}
}, [areNodesReady, nodes, diagram, applyInitialLayout]);

Expand Down Expand Up @@ -357,56 +281,11 @@ const DiagramEditor: React.FunctionComponent<{
maxZoom: 1,
minZoom: 0.25,
}}
onEdgeClick={(evt, edge) => {
setApplyInput(
JSON.stringify(
{
type: 'RemoveRelationship',
relationshipId: edge.id,
},
null,
2
)
);
onNodeDragStop={(evt, node) => {
onMoveCollection(node.id, [node.position.x, node.position.y]);
}}
/>
</div>
<div className={editorContainerStyles} data-testid="apply-editor">
<div className={editorContainerPlaceholderButtonStyles}>
<Button
onClick={applyPlaceholder('AddRelationship')}
data-testid="placeholder-addrelationship-button"
>
Add relationship
</Button>
<Button
onClick={applyPlaceholder('RemoveRelationship')}
data-testid="placeholder-removerelationship-button"
>
Remove relationship
</Button>
</div>
<div>
<CodemirrorMultilineEditor
language="json"
text={applyInput}
onChangeText={setApplyInput}
maxLines={10}
></CodemirrorMultilineEditor>
</div>
<div className={editorContainerApplyContainerStyles}>
{editErrors && <ErrorSummary errors={editErrors} />}
<Button
onClick={() => {
onApplyClick(JSON.parse(applyInput));
}}
data-testid="apply-button"
disabled={!isEditValid}
>
Apply
</Button>
</div>
</div>
</div>
);
}
Expand Down Expand Up @@ -434,7 +313,7 @@ export default connect(
{
onRetryClick: retryAnalysis,
onCancelClick: cancelAnalysis,
onApplyClick: applyEdit,
onApplyInitialLayout: applyInitialLayout,
onMoveCollection: moveCollection,
}
)(DiagramEditor);
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ const EditSchemaVariants = z.discriminatedUnion('type', [
type: z.literal('RemoveRelationship'),
relationshipId: z.string().uuid(),
}),
z.object({
type: z.literal('MoveCollection'),
ns: z.string(),
newPosition: z.tuple([z.number(), z.number()]),
}),
]);

export const EditSchema = z.intersection(EditSchemaBase, EditSchemaVariants);
Expand Down
47 changes: 47 additions & 0 deletions packages/compass-data-modeling/src/store/diagram.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
applyEdit,
applyInitialLayout,
getCurrentDiagramFromState,
getCurrentModel,
openDiagram,
redoEdit,
undoEdit,
Expand Down Expand Up @@ -201,6 +202,7 @@ describe('Data Modeling store', function () {
],
isInferred: false,
};

store.dispatch(
applyEdit({
type: 'AddRelationship',
Expand All @@ -217,6 +219,9 @@ describe('Data Modeling store', function () {
type: 'AddRelationship',
relationship: newRelationship,
});

const currentModel = getCurrentModel(diagram);
expect(currentModel.relationships).to.have.length(2);
});

it('should not apply invalid AddRelationship edit', function () {
Expand All @@ -239,6 +244,48 @@ describe('Data Modeling store', function () {
const diagram = getCurrentDiagramFromState(store.getState());
expect(diagram.edits).to.deep.equal(loadedDiagram.edits);
});

it('should apply a valid MoveCollection edit', function () {
store.dispatch(openDiagram(loadedDiagram));

const edit: Omit<
Extract<Edit, { type: 'MoveCollection' }>,
'id' | 'timestamp'
> = {
type: 'MoveCollection',
ns: model.collections[0].ns,
newPosition: [100, 100],
};
store.dispatch(applyEdit(edit));

const state = store.getState();
const diagram = getCurrentDiagramFromState(state);
expect(state.diagram?.editErrors).to.be.undefined;
expect(diagram.edits).to.have.length(2);
expect(diagram.edits[0]).to.deep.equal(loadedDiagram.edits[0]);
expect(diagram.edits[1]).to.deep.include(edit);

const currentModel = getCurrentModel(diagram);
expect(currentModel.collections[0].displayPosition).to.deep.equal([
100, 100,
]);
});

it('should not apply invalid MoveCollection edit', function () {
store.dispatch(openDiagram(loadedDiagram));

const edit = {
type: 'MoveCollection',
ns: 'nonexistent.collection',
} as unknown as Edit;
store.dispatch(applyEdit(edit));

const editErrors = store.getState().diagram?.editErrors;
expect(editErrors).to.have.length(1);
expect(editErrors && editErrors[0]).to.equal("'newPosition' is required");
const diagram = getCurrentDiagramFromState(store.getState());
expect(diagram.edits).to.deep.equal(loadedDiagram.edits);
});
});

it('undo & redo', function () {
Expand Down
Loading
Loading