Merge pull request #3774 from xyflow/svelte-node-resizer

Svelte node resizer
This commit is contained in:
Moritz Klack
2024-01-09 16:52:06 +01:00
committed by GitHub
37 changed files with 6683 additions and 9288 deletions
@@ -0,0 +1,149 @@
import { useRef, useEffect, memo } from 'react';
import cc from 'classcat';
import { XYResizer, ResizeControlVariant, type XYResizerInstance, type XYResizerChange } from '@xyflow/system';
import { useStoreApi } from '../../hooks/useStore';
import { useNodeId } from '../../contexts/NodeIdContext';
import type { NodeChange, NodeDimensionChange, NodePositionChange } from '../../types';
import type { ResizeControlProps, ResizeControlLineProps } from './types';
function ResizeControl({
nodeId,
position,
variant = ResizeControlVariant.Handle,
className,
style = {},
children,
color,
minWidth = 10,
minHeight = 10,
maxWidth = Number.MAX_VALUE,
maxHeight = Number.MAX_VALUE,
keepAspectRatio = false,
shouldResize,
onResizeStart,
onResize,
onResizeEnd,
}: ResizeControlProps) {
const contextNodeId = useNodeId();
const id = typeof nodeId === 'string' ? nodeId : contextNodeId;
const store = useStoreApi();
const resizeControlRef = useRef<HTMLDivElement>(null);
const defaultPosition = variant === ResizeControlVariant.Line ? 'right' : 'bottom-right';
const controlPosition = position ?? defaultPosition;
const resizer = useRef<XYResizerInstance | null>(null);
useEffect(() => {
if (!resizeControlRef.current || !id) {
return;
}
if (!resizer.current) {
resizer.current = XYResizer({
domNode: resizeControlRef.current,
nodeId: id,
getStoreItems: () => {
const { nodeLookup, transform, snapGrid, snapToGrid } = store.getState();
return {
nodeLookup,
transform,
snapGrid,
snapToGrid,
};
},
onChange: (change: XYResizerChange) => {
const { triggerNodeChanges } = store.getState();
const changes: NodeChange[] = [];
if (change.isXPosChange || change.isYPosChange) {
const positionChange: NodePositionChange = {
id,
type: 'position',
position: {
x: change.x,
y: change.y,
},
};
changes.push(positionChange);
}
if (change.isWidthChange || change.isHeightChange) {
const dimensionChange: NodeDimensionChange = {
id,
type: 'dimensions',
resizing: true,
dimensions: {
width: change.width,
height: change.height,
},
};
changes.push(dimensionChange);
}
triggerNodeChanges(changes);
},
onEnd: () => {
const dimensionChange: NodeDimensionChange = {
id: id,
type: 'dimensions',
resizing: false,
};
store.getState().triggerNodeChanges([dimensionChange]);
},
});
}
resizer.current.update({
controlPosition,
boundaries: {
minWidth,
minHeight,
maxWidth,
maxHeight,
},
keepAspectRatio,
onResizeStart,
onResize,
onResizeEnd,
shouldResize,
});
return () => {
resizer.current?.destroy();
};
}, [
controlPosition,
minWidth,
minHeight,
maxWidth,
maxHeight,
keepAspectRatio,
onResizeStart,
onResize,
onResizeEnd,
shouldResize,
]);
const positionClassNames = controlPosition.split('-');
const colorStyleProp = variant === ResizeControlVariant.Line ? 'borderColor' : 'backgroundColor';
const controlStyle = color ? { ...style, [colorStyleProp]: color } : style;
return (
<div
className={cc(['react-flow__resize-control', 'nodrag', ...positionClassNames, variant, className])}
ref={resizeControlRef}
style={controlStyle}
>
{children}
</div>
);
}
export function ResizeControlLine(props: ResizeControlLineProps) {
return <ResizeControl {...props} variant={ResizeControlVariant.Line} />;
}
export const NodeResizeControl = memo(ResizeControl);
@@ -1,10 +1,9 @@
import ResizeControl from './ResizeControl';
import { ControlPosition, NodeResizerProps, ResizeControlVariant, ControlLinePosition } from './types';
import { ResizeControlVariant, XY_RESIZER_HANDLE_POSITIONS, XY_RESIZER_LINE_POSITIONS } from '@xyflow/system';
const handleControls: ControlPosition[] = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
const lineControls: ControlLinePosition[] = ['top', 'right', 'bottom', 'left'];
import { NodeResizeControl } from './NodeResizeControl';
import type { NodeResizerProps } from './types';
export default function NodeResizer({
export function NodeResizer({
nodeId,
isVisible = true,
handleClassName,
@@ -28,13 +27,13 @@ export default function NodeResizer({
return (
<>
{lineControls.map((c) => (
<ResizeControl
key={c}
{XY_RESIZER_LINE_POSITIONS.map((position) => (
<NodeResizeControl
key={position}
className={lineClassName}
style={lineStyle}
nodeId={nodeId}
position={c}
position={position}
variant={ResizeControlVariant.Line}
color={color}
minWidth={minWidth}
@@ -48,13 +47,13 @@ export default function NodeResizer({
onResizeEnd={onResizeEnd}
/>
))}
{handleControls.map((c) => (
<ResizeControl
key={c}
{XY_RESIZER_HANDLE_POSITIONS.map((position) => (
<NodeResizeControl
key={position}
className={handleClassName}
style={handleStyle}
nodeId={nodeId}
position={c}
position={position}
color={color}
minWidth={minWidth}
minHeight={minHeight}
@@ -1,256 +0,0 @@
import { useRef, useEffect, memo } from 'react';
import cc from 'classcat';
import { drag } from 'd3-drag';
import { select } from 'd3-selection';
import { getPointerPosition, clamp } from '@xyflow/system';
import { useStoreApi } from '../../hooks/useStore';
import { useNodeId } from '../../contexts/NodeIdContext';
import type { NodeChange, NodeDimensionChange, NodePositionChange } from '../../types';
import {
type ResizeDragEvent,
type ResizeControlProps,
type ResizeControlLineProps,
ResizeControlVariant,
} from './types';
import { getDirection } from './utils';
const initPrevValues = { width: 0, height: 0, x: 0, y: 0 };
const initStartValues = {
...initPrevValues,
pointerX: 0,
pointerY: 0,
aspectRatio: 1,
};
function ResizeControl({
nodeId,
position,
variant = ResizeControlVariant.Handle,
className,
style = {},
children,
color,
minWidth = 10,
minHeight = 10,
maxWidth = Number.MAX_VALUE,
maxHeight = Number.MAX_VALUE,
keepAspectRatio = false,
shouldResize,
onResizeStart,
onResize,
onResizeEnd,
}: ResizeControlProps) {
const contextNodeId = useNodeId();
const id = typeof nodeId === 'string' ? nodeId : contextNodeId;
const store = useStoreApi();
const resizeControlRef = useRef<HTMLDivElement>(null);
const startValues = useRef<typeof initStartValues>(initStartValues);
const prevValues = useRef<typeof initPrevValues>(initPrevValues);
const defaultPosition = variant === ResizeControlVariant.Line ? 'right' : 'bottom-right';
const controlPosition = position ?? defaultPosition;
useEffect(() => {
if (!resizeControlRef.current || !id) {
return;
}
const selection = select(resizeControlRef.current);
const enableX = controlPosition.includes('right') || controlPosition.includes('left');
const enableY = controlPosition.includes('bottom') || controlPosition.includes('top');
const invertX = controlPosition.includes('left');
const invertY = controlPosition.includes('top');
const dragHandler = drag<HTMLDivElement, unknown>()
.on('start', (event: ResizeDragEvent) => {
const { nodeLookup, transform, snapGrid, snapToGrid } = store.getState();
const node = nodeLookup.get(id);
const { xSnapped, ySnapped } = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
prevValues.current = {
width: node?.computed?.width ?? 0,
height: node?.computed?.height ?? 0,
x: node?.position.x ?? 0,
y: node?.position.y ?? 0,
};
startValues.current = {
...prevValues.current,
pointerX: xSnapped,
pointerY: ySnapped,
aspectRatio: prevValues.current.width / prevValues.current.height,
};
onResizeStart?.(event, { ...prevValues.current });
})
.on('drag', (event: ResizeDragEvent) => {
const { nodeLookup, transform, snapGrid, snapToGrid, triggerNodeChanges } = store.getState();
const { xSnapped, ySnapped } = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
const node = nodeLookup.get(id);
if (node) {
const changes: NodeChange[] = [];
const {
pointerX: startX,
pointerY: startY,
width: startWidth,
height: startHeight,
x: startNodeX,
y: startNodeY,
aspectRatio,
} = startValues.current;
const { x: prevX, y: prevY, width: prevWidth, height: prevHeight } = prevValues.current;
const distX = Math.floor(enableX ? xSnapped - startX : 0);
const distY = Math.floor(enableY ? ySnapped - startY : 0);
let width = clamp(startWidth + (invertX ? -distX : distX), minWidth, maxWidth);
let height = clamp(startHeight + (invertY ? -distY : distY), minHeight, maxHeight);
if (keepAspectRatio) {
const nextAspectRatio = width / height;
const isDiagonal = enableX && enableY;
const isHorizontal = enableX && !enableY;
const isVertical = enableY && !enableX;
width = (nextAspectRatio <= aspectRatio && isDiagonal) || isVertical ? height * aspectRatio : width;
height = (nextAspectRatio > aspectRatio && isDiagonal) || isHorizontal ? width / aspectRatio : height;
if (width >= maxWidth) {
width = maxWidth;
height = maxWidth / aspectRatio;
} else if (width <= minWidth) {
width = minWidth;
height = minWidth / aspectRatio;
}
if (height >= maxHeight) {
height = maxHeight;
width = maxHeight * aspectRatio;
} else if (height <= minHeight) {
height = minHeight;
width = minHeight * aspectRatio;
}
}
const isWidthChange = width !== prevWidth;
const isHeightChange = height !== prevHeight;
if (invertX || invertY) {
const x = invertX ? startNodeX - (width - startWidth) : startNodeX;
const y = invertY ? startNodeY - (height - startHeight) : startNodeY;
// only transform the node if the width or height changes
const isXPosChange = x !== prevX && isWidthChange;
const isYPosChange = y !== prevY && isHeightChange;
if (isXPosChange || isYPosChange) {
const positionChange: NodePositionChange = {
id: node.id,
type: 'position',
position: {
x: isXPosChange ? x : prevX,
y: isYPosChange ? y : prevY,
},
};
changes.push(positionChange);
prevValues.current.x = positionChange.position!.x;
prevValues.current.y = positionChange.position!.y;
}
}
if (isWidthChange || isHeightChange) {
const dimensionChange: NodeDimensionChange = {
id: id,
type: 'dimensions',
updateStyle: true,
resizing: true,
dimensions: {
width: width,
height: height,
},
};
changes.push(dimensionChange);
prevValues.current.width = width;
prevValues.current.height = height;
}
if (changes.length === 0) {
return;
}
const direction = getDirection({
width: prevValues.current.width,
prevWidth,
height: prevValues.current.height,
prevHeight,
invertX,
invertY,
});
const nextValues = { ...prevValues.current, direction };
const callResize = shouldResize?.(event, nextValues);
if (callResize === false) {
return;
}
onResize?.(event, nextValues);
triggerNodeChanges(changes);
}
})
.on('end', (event: ResizeDragEvent) => {
const dimensionChange: NodeDimensionChange = {
id: id,
type: 'dimensions',
resizing: false,
};
onResizeEnd?.(event, { ...prevValues.current });
store.getState().triggerNodeChanges([dimensionChange]);
});
selection.call(dragHandler);
return () => {
selection.on('.drag', null);
};
}, [
id,
controlPosition,
minWidth,
minHeight,
maxWidth,
maxHeight,
keepAspectRatio,
onResizeStart,
onResize,
onResizeEnd,
]);
const positionClassNames = controlPosition.split('-');
const colorStyleProp = variant === ResizeControlVariant.Line ? 'borderColor' : 'backgroundColor';
const controlStyle = color ? { ...style, [colorStyleProp]: color } : style;
return (
<div
className={cc(['react-flow__resize-control', 'nodrag', ...positionClassNames, variant, className])}
ref={resizeControlRef}
style={controlStyle}
>
{children}
</div>
);
}
export function ResizeControlLine(props: ResizeControlLineProps) {
return <ResizeControl {...props} variant={ResizeControlVariant.Line} />;
}
export default memo(ResizeControl);
@@ -1,4 +1,4 @@
export { default as NodeResizer } from './NodeResizer';
export { default as NodeResizeControl } from './ResizeControl';
export { NodeResizer } from './NodeResizer';
export { NodeResizeControl } from './NodeResizeControl';
export * from './types';
@@ -1,23 +1,13 @@
import type { CSSProperties, ReactNode } from 'react';
import type { D3DragEvent, SubjectPosition } from 'd3-drag';
export type ResizeParams = {
x: number;
y: number;
width: number;
height: number;
};
export type ResizeParamsWithDirection = ResizeParams & {
direction: number[];
};
type OnResizeHandler<Params = ResizeParams, Result = void> = (event: ResizeDragEvent, params: Params) => Result;
export type ShouldResize = OnResizeHandler<ResizeParamsWithDirection, boolean>;
export type OnResizeStart = OnResizeHandler;
export type OnResize = OnResizeHandler<ResizeParamsWithDirection>;
export type OnResizeEnd = OnResizeHandler;
import type {
ControlPosition,
ControlLinePosition,
ResizeControlVariant,
ShouldResize,
OnResizeStart,
OnResize,
OnResizeEnd,
} from '@xyflow/system';
export type NodeResizerProps = {
nodeId?: string;
@@ -38,15 +28,6 @@ export type NodeResizerProps = {
onResizeEnd?: OnResizeEnd;
};
export type ControlLinePosition = 'top' | 'bottom' | 'left' | 'right';
export type ControlPosition = ControlLinePosition | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
export enum ResizeControlVariant {
Line = 'line',
Handle = 'handle',
}
export type ResizeControlProps = Pick<
NodeResizerProps,
| 'nodeId'
@@ -71,5 +52,3 @@ export type ResizeControlProps = Pick<
export type ResizeControlLineProps = ResizeControlProps & {
position?: ControlLinePosition;
};
export type ResizeDragEvent = D3DragEvent<HTMLDivElement, null, SubjectPosition>;
@@ -1,26 +0,0 @@
type GetDirectionParams = {
width: number;
prevWidth: number;
height: number;
prevHeight: number;
invertX: boolean;
invertY: boolean;
};
// returns an array of two numbers (0, 1 or -1) representing the direction of the resize
// 0 = no change, 1 = increase, -1 = decrease
export function getDirection({ width, prevWidth, height, prevHeight, invertX, invertY }: GetDirectionParams) {
const deltaWidth = width - prevWidth;
const deltaHeight = height - prevHeight;
const direction = [deltaWidth > 0 ? 1 : deltaWidth < 0 ? -1 : 0, deltaHeight > 0 ? 1 : deltaHeight < 0 ? -1 : 0];
if (deltaWidth && invertX) {
direction[0] = direction[0] * -1;
}
if (deltaHeight && invertY) {
direction[1] = direction[1] * -1;
}
return direction;
}
@@ -219,9 +219,9 @@ export function NodeWrapper({
transform: `translate(${positionAbsoluteOrigin.x}px,${positionAbsoluteOrigin.y}px)`,
pointerEvents: hasPointerEvents ? 'all' : 'none',
visibility: initialized ? 'visible' : 'hidden',
width,
height,
...node.style,
width: width ?? node.style?.width,
height: height ?? node.style?.height,
}}
data-id={id}
data-testid={`rf__node-${id}`}
+7
View File
@@ -81,6 +81,13 @@ export {
type ColorModeClass,
type HandleType,
type OnBeforeDelete,
type ShouldResize,
type OnResizeStart,
type OnResize,
type OnResizeEnd,
type ControlPosition,
type ControlLinePosition,
type ResizeControlVariant,
} from '@xyflow/system';
// system utils
-1
View File
@@ -7,7 +7,6 @@ export type NodeDimensionChange = {
id: string;
type: 'dimensions';
dimensions?: Dimensions;
updateStyle?: boolean;
resizing?: boolean;
};
+5 -3
View File
@@ -121,10 +121,12 @@ function applyChanges(changes: any[], elements: any[]): any[] {
}
updateItem.computed.width = currentChange.dimensions.width;
updateItem.computed.height = currentChange.dimensions.height;
}
if (typeof currentChange.updateStyle !== 'undefined') {
updateItem.style = { ...(updateItem.style || {}), ...currentChange.dimensions };
// this is needed for the node resizer to work
if (currentChange.resizing) {
updateItem.width = currentChange.dimensions.width;
updateItem.height = currentChange.dimensions.height;
}
}
if (typeof currentChange.resizing === 'boolean') {