Skip to content
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^12.1.5",
"@testing-library/react-hooks": "^8.0.1",
"@testing-library/user-event": "^14.6.1",
"@types/d3-path": "^3",
"@types/jest": "30.0.0",
"@types/node": "22.15.29",
Expand Down
82 changes: 82 additions & 0 deletions src/components/buttons/diagram-icon-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { ButtonHTMLAttributes } from 'react';
import styled from '@emotion/styled';
import { spacing, transitionDuration } from '@leafygreen-ui/tokens';
import { palette } from '@leafygreen-ui/palette';

const StyledDiagramIconButton = styled.button`
background: none;
border: none;
outline: none;
padding: ${spacing[100]}px;
margin: 0;
margin-left: ${spacing[100]}px;
cursor: pointer;
color: inherit;
display: flex;
position: relative;
color: ${props => props.theme.node.fieldIconButton};

&::before {
content: '';
transition: ${transitionDuration.default}ms all ease-in-out;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
border-radius: 100%;
transform: scale(0.8);
}

&:active::before,
&:hover::before,
&:focus::before,
&[data-hover='true']::before,
&[data-focus='true']::before {
transform: scale(1);
}

&:active,
&:hover,
&[data-hover='true'],
&:focus-visible,
&[data-focus='true'] {
color: ${palette.black};

&::before {
background-color: ${props => props.theme.node.fieldIconButtonHoverBackground};
}
}

// Focus ring styles.
&::after {
position: absolute;
content: '';
pointer-events: none;
top: 3px;
right: 3px;
bottom: 3px;
left: 3px;
border-radius: ${spacing[100]}px;
box-shadow: 0 0 0 0 transparent;
transition: box-shadow 0.16s ease-in;
z-index: 1;
}
&:focus-visible {
&::after {
box-shadow: 0 0 0 3px ${palette.blue.light1} !important;
transition-timing-function: ease-out;
}
}
`;

// Use a custom button component instead of LeafyGreen's IconButton
// to allow us to have a smaller focus ring and icon size without overwriting internal styles.
export const DiagramIconButton = ({
children,
...props
}: ButtonHTMLAttributes<HTMLButtonElement> & {
children?: React.ReactNode;
}) => {
return <StyledDiagramIconButton {...props}>{children}</StyledDiagramIconButton>;
};
12 changes: 9 additions & 3 deletions src/components/canvas/canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { MarkerList } from '@/components/markers/marker-list';
import { ConnectionLine } from '@/components/line/connection-line';
import { convertToExternalNode, convertToExternalNodes, convertToInternalNodes } from '@/utilities/convert-nodes';
import { convertToExternalEdge, convertToExternalEdges, convertToInternalEdges } from '@/utilities/convert-edges';
import { FieldSelectionProvider } from '@/hooks/use-field-selection';
import { EditableDiagramInteractionsProvider } from '@/hooks/use-editable-diagram-interactions';

const MAX_ZOOM = 3;
const MIN_ZOOM = 0.1;
Expand Down Expand Up @@ -57,6 +57,8 @@ export const Canvas = ({
edges: externalEdges,
onConnect,
id,
onAddFieldToNodeClick,
onAddFieldToObjectFieldClick,
onFieldClick,
onNodeContextMenu,
onNodeDrag,
Expand Down Expand Up @@ -141,7 +143,11 @@ export const Canvas = ({
);

return (
<FieldSelectionProvider onFieldClick={onFieldClick}>
<EditableDiagramInteractionsProvider
onFieldClick={onFieldClick}
onAddFieldToNodeClick={onAddFieldToNodeClick}
onAddFieldToObjectFieldClick={onAddFieldToObjectFieldClick}
>
<ReactFlowWrapper>
<ReactFlow
id={id}
Expand Down Expand Up @@ -177,6 +183,6 @@ export const Canvas = ({
<MiniMap />
</ReactFlow>
</ReactFlowWrapper>
</FieldSelectionProvider>
</EditableDiagramInteractionsProvider>
);
};
6 changes: 3 additions & 3 deletions src/components/diagram.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { EMPLOYEE_TERRITORIES_NODE, EMPLOYEES_NODE, ORDERS_NODE } from '@/mocks/
import { EMPLOYEES_TO_EMPLOYEES_EDGE, ORDERS_TO_EMPLOYEES_EDGE } from '@/mocks/datasets/edges';
import { DiagramStressTestDecorator } from '@/mocks/decorators/diagram-stress-test.decorator';
import { DiagramConnectableDecorator } from '@/mocks/decorators/diagram-connectable.decorator';
import { DiagramSelectableFieldsDecorator } from '@/mocks/decorators/diagram-selectable-fields.decorator';
import { DiagramEditableInteractionsDecorator } from '@/mocks/decorators/diagram-editable-interactions.decorator';

const diagram: Meta<typeof Diagram> = {
title: 'Diagram',
Expand Down Expand Up @@ -51,8 +51,8 @@ function idFromDepthAccumulator(name: string, depth?: number) {
lastDepth = depth ?? 0;
return [...idAccumulator];
}
export const DiagramWithSelectableFields: Story = {
decorators: [DiagramSelectableFieldsDecorator],
export const DiagramWithEditInteractions: Story = {
decorators: [DiagramEditableInteractionsDecorator],
args: {
title: 'MongoDB Diagram',
isDarkMode: true,
Expand Down
5 changes: 3 additions & 2 deletions src/components/field/field-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { Field } from '@/components/field/field';
import { NodeField, NodeType } from '@/types';
import { DEFAULT_PREVIEW_GROUP_AREA, getPreviewGroupArea, getPreviewId } from '@/utilities/get-preview-group-area';
import { DEFAULT_FIELD_PADDING } from '@/utilities/constants';
import { useFieldSelection } from '@/hooks/use-field-selection';
import { getSelectedFieldGroupHeight, getSelectedId } from '@/utilities/get-selected-field-group-height';
import { useEditableDiagramInteractions } from '@/hooks/use-editable-diagram-interactions';

const NodeFieldWrapper = styled.div`
padding: ${DEFAULT_FIELD_PADDING}px ${spacing[400]}px;
Expand All @@ -22,7 +22,8 @@ interface Props {
}

export const FieldList = ({ fields, nodeId, nodeType, isHovering }: Props) => {
const { enabled: isFieldSelectionEnabled } = useFieldSelection();
const { onClickField } = useEditableDiagramInteractions();
const isFieldSelectionEnabled = !!onClickField;

const spacing = Math.max(0, ...fields.map(field => field.glyphs?.length || 0));
const previewGroupArea = useMemo(() => getPreviewGroupArea(fields), [fields]);
Expand Down
61 changes: 61 additions & 0 deletions src/components/field/field-type-content.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { useMemo } from 'react';
import styled from '@emotion/styled';

import { useEditableDiagramInteractions } from '@/hooks/use-editable-diagram-interactions';
import { PlusWithSquare } from '@/components/icons/plus-with-square';
import { DiagramIconButton } from '@/components/buttons/diagram-icon-button';

const ObjectTypeContainer = styled.div`
display: flex;
justify-content: flex-end;
align-items: center;
line-height: 20px;
`;

export const FieldTypeContent = ({
type,
nodeId,
id,
}: {
id: string | string[];
nodeId: string;
type: React.ReactNode;
}) => {
const { onClickAddFieldToObjectField: _onClickAddFieldToObjectField } = useEditableDiagramInteractions();

const onClickAddFieldToObject = useMemo(
() =>
_onClickAddFieldToObjectField
? (event: React.MouseEvent<HTMLButtonElement>) => {
// Don't click on the field element.
event.stopPropagation();
_onClickAddFieldToObjectField(event, nodeId, Array.isArray(id) ? id : [id]);
}
: undefined,
[_onClickAddFieldToObjectField, nodeId, id],
);

if (type === 'object') {
return (
<ObjectTypeContainer>
{'{}'}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't depend on the callback existence

{onClickAddFieldToObject && (
<DiagramIconButton
data-testid={`object-field-type-${nodeId}-${typeof id === 'string' ? id : id.join('.')}`}
onClick={onClickAddFieldToObject}
aria-label="Add new field"
title="Add Field"
>
<PlusWithSquare />
</DiagramIconButton>
)}
</ObjectTypeContainer>
);
}

if (type === 'array') {
return '[]';
}

return <>{type}</>;
};
66 changes: 63 additions & 3 deletions src/components/field/field.test.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,31 @@
import { palette } from '@leafygreen-ui/palette';
import { ComponentProps } from 'react';
import { userEvent } from '@testing-library/user-event';

import { render, screen } from '@/mocks/testing-utils';
import { Field as FieldComponent } from '@/components/field/field';
import { DEFAULT_PREVIEW_GROUP_AREA } from '@/utilities/get-preview-group-area';
import { FieldSelectionProvider } from '@/hooks/use-field-selection';
import { EditableDiagramInteractionsProvider } from '@/hooks/use-editable-diagram-interactions';

const Field = (props: React.ComponentProps<typeof FieldComponent>) => (
<FieldSelectionProvider>
<EditableDiagramInteractionsProvider>
<FieldComponent {...props} />
</FieldSelectionProvider>
</EditableDiagramInteractionsProvider>
);

const FieldWithEditableInteractions = ({
onAddFieldToObjectFieldClick,
...fieldProps
}: React.ComponentProps<typeof FieldComponent> & {
onAddFieldToObjectFieldClick?: () => void;
}) => {
return (
<EditableDiagramInteractionsProvider onAddFieldToObjectFieldClick={onAddFieldToObjectFieldClick}>
<FieldComponent {...fieldProps} />
</EditableDiagramInteractionsProvider>
);
};

describe('field', () => {
const DEFAULT_PROPS: ComponentProps<typeof Field> = {
nodeType: 'collection',
Expand All @@ -30,6 +44,52 @@ describe('field', () => {
expect(screen.getByRole('img', { name: 'Key Icon' })).toBeInTheDocument();
expect(screen.getByRole('img', { name: 'Link Icon' })).toBeInTheDocument();
});
it('Should not have a button to add a field on an object type', () => {
render(<Field {...DEFAULT_PROPS} type={'object'} id={['ordersId']} />);
expect(screen.getByText('ordersId')).toBeInTheDocument();
expect(screen.getByText('{}')).toBeInTheDocument();
const button = screen.queryByRole('button');
expect(button).not.toBeInTheDocument();
});
describe('With editable interactions supplied', () => {
it('Should have a button to add a field on an object type', async () => {
const onAddFieldToObjectFieldClickMock = vi.fn();

render(
<FieldWithEditableInteractions
{...DEFAULT_PROPS}
type={'object'}
id={['ordersId']}
onAddFieldToObjectFieldClick={onAddFieldToObjectFieldClickMock}
/>,
);
expect(screen.getByText('ordersId')).toBeInTheDocument();
expect(screen.getByText('{}')).toBeInTheDocument();
const button = screen.getByRole('button');
expect(button).toBeInTheDocument();
expect(button).toHaveAttribute('data-testid', 'object-field-type-pineapple-ordersId');
expect(button).toHaveAttribute('title', 'Add Field');
expect(onAddFieldToObjectFieldClickMock).not.toHaveBeenCalled();
await userEvent.click(button);
expect(onAddFieldToObjectFieldClickMock).toHaveBeenCalled();
});

it('Should not have a button to add a field with non-object types', () => {
render(<FieldWithEditableInteractions {...DEFAULT_PROPS} id={['ordersId']} />);
expect(screen.getByText('ordersId')).toBeInTheDocument();
expect(screen.getByText('objectId')).toBeInTheDocument();
const button = screen.queryByRole('button');
expect(button).not.toBeInTheDocument();
});
});
describe('With specific types', () => {
it('shows [] with "array"', () => {
render(<Field {...DEFAULT_PROPS} type="array" />);
expect(screen.getByText('[]')).toBeInTheDocument();
expect(screen.queryByText('array')).not.toBeInTheDocument();
});
});

describe('With glyphs', () => {
it('With disabled', () => {
render(<Field {...DEFAULT_PROPS} variant={'disabled'} />);
Expand Down
20 changes: 11 additions & 9 deletions src/components/field/field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import { palette } from '@leafygreen-ui/palette';
import Icon from '@leafygreen-ui/icon';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';
import { useTheme } from '@emotion/react';
import { MouseEvent as ReactMouseEvent, useMemo } from 'react';
import { useMemo } from 'react';

import { animatedBlueBorder, ellipsisTruncation } from '@/styles/styles';
import { DEFAULT_DEPTH_SPACING, DEFAULT_FIELD_HEIGHT } from '@/utilities/constants';
import { FieldDepth } from '@/components/field/field-depth';
import { FieldTypeContent } from '@/components/field/field-type-content';
import { NodeField, NodeGlyph, NodeType } from '@/types';
import { PreviewGroupArea } from '@/utilities/get-preview-group-area';
import { useFieldSelection } from '@/hooks/use-field-selection';
import { useEditableDiagramInteractions } from '@/hooks/use-editable-diagram-interactions';

const FIELD_BORDER_ANIMATED_PADDING = spacing[100];
const FIELD_GLYPH_SPACING = spacing[400];
Expand Down Expand Up @@ -145,15 +146,14 @@ export const Field = ({
selectedGroupHeight = 0,
previewGroupArea,
glyphSize = LGSpacing[300],
renderName,
spacing = 0,
selectable = false,
selected = false,
variant,
}: Props) => {
const { theme } = useDarkMode();

const { fieldProps } = useFieldSelection();
const { onClickField } = useEditableDiagramInteractions();

const internalTheme = useTheme();

Expand All @@ -167,14 +167,14 @@ export const Field = ({
* Create the field selection props when the field is selectable.
*/
const fieldSelectionProps = useMemo(() => {
return selectable && fieldProps
return selectable && !!onClickField
? {
'data-testid': `selectable-field-${nodeId}-${typeof id === 'string' ? id : id.join('.')}`,
selectable: true,
onClick: (event: ReactMouseEvent) => fieldProps.onClick(event, { id, nodeId }),
onClick: (event: React.MouseEvent) => onClickField(event, { id, nodeId }),
}
: undefined;
}, [fieldProps, selectable, id, nodeId]);
}, [onClickField, selectable, id, nodeId]);

const getTextColor = () => {
if (isDisabled) {
Expand Down Expand Up @@ -215,9 +215,11 @@ export const Field = ({
<>
<FieldName>
<FieldDepth depth={depth} />
<InnerFieldName>{renderName || name}</InnerFieldName>
<InnerFieldName>{name}</InnerFieldName>
</FieldName>
<FieldType color={getSecondaryTextColor()}>{type}</FieldType>
<FieldType color={getSecondaryTextColor()}>
<FieldTypeContent type={type} nodeId={nodeId} id={id} />
</FieldType>
</>
);

Expand Down
Loading