Merge branch 'next' into fix-svelte-reset

This commit is contained in:
Moritz Klack
2024-02-29 19:48:19 +01:00
committed by GitHub
21 changed files with 201 additions and 132 deletions
@@ -50,7 +50,9 @@ const initialNodes: Node[] = [
maxHeight: 200, maxHeight: 200,
}, },
position: { x: 0, y: 60 }, position: { x: 0, y: 60 },
style: { ...nodeStyle, width: 100, height: 80 }, width: 100,
height: 80,
style: { ...nodeStyle },
}, },
{ {
id: '1b', id: '1b',
@@ -64,9 +66,9 @@ const initialNodes: Node[] = [
maxHeight: 400, maxHeight: 400,
}, },
position: { x: 250, y: 0 }, position: { x: 250, y: 0 },
width: 174,
height: 123,
style: { style: {
width: 174,
height: 123,
...nodeStyle, ...nodeStyle,
}, },
}, },
@@ -75,7 +77,9 @@ const initialNodes: Node[] = [
type: 'customResizer', type: 'customResizer',
data: { label: 'custom resize icon' }, data: { label: 'custom resize icon' },
position: { x: 0, y: 200 }, position: { x: 0, y: 200 },
style: { width: 100, height: 60, ...nodeStyle }, width: 100,
height: 60,
style: { ...nodeStyle },
}, },
{ {
id: '3', id: '3',
@@ -94,7 +98,8 @@ const initialNodes: Node[] = [
keepAspectRatio: true, keepAspectRatio: true,
}, },
position: { x: 400, y: 200 }, position: { x: 400, y: 200 },
style: { ...nodeStyle, height: 50 }, height: 50,
style: { ...nodeStyle },
}, },
{ {
id: '4', id: '4',
@@ -121,7 +126,9 @@ const initialNodes: Node[] = [
type: 'defaultResizer', type: 'defaultResizer',
data: { label: 'Parent', keepAspectRatio: true }, data: { label: 'Parent', keepAspectRatio: true },
position: { x: 700, y: 0 }, position: { x: 700, y: 0 },
style: { ...nodeStyle, width: 300, height: 400 }, width: 300,
height: 400,
style: { ...nodeStyle },
}, },
{ {
id: '5a', id: '5a',
@@ -132,7 +139,9 @@ const initialNodes: Node[] = [
position: { x: 50, y: 50 }, position: { x: 50, y: 50 },
parentNode: '5', parentNode: '5',
extent: 'parent', extent: 'parent',
style: { ...nodeStyle, width: 50, height: 100 }, width: 50,
height: 100,
style: { ...nodeStyle },
}, },
{ {
id: '5b', id: '5b',
@@ -1,7 +1,7 @@
import { useCallback } from 'react'; import { useCallback } from 'react';
import { ReactFlow, Node, Edge, useNodesState, useEdgesState, Position, Connection, addEdge } from '@xyflow/react'; import { ReactFlow, Node, Edge, useNodesState, useEdgesState, Position, Connection, addEdge } from '@xyflow/react';
import styles from './touch-device.module.css'; import './touch-device.css';
const initialNodes: Node[] = [ const initialNodes: Node[] = [
{ {
@@ -42,7 +42,7 @@ const TouchDeviceFlow = () => {
onConnectEnd={onConnectEnd} onConnectEnd={onConnectEnd}
onClickConnectStart={onClickConnectStart} onClickConnectStart={onClickConnectStart}
onClickConnectEnd={onClickConnectEnd} onClickConnectEnd={onClickConnectEnd}
className={styles.flow} className="touch-flow"
/> />
); );
}; };
@@ -0,0 +1,27 @@
.react-flow.touch-flow .react-flow__handle {
width: 20px;
height: 20px;
border-radius: 3px;
background-color: #9f7aea;
}
.touch-flow .react-flow__handle-right {
--translate: translate(50%, -50%);
}
.touch-flow .react-flow__handle-left {
--translate: translate(-50%, -50%);
}
@keyframes bounce {
0% {
transform: var(--translate) scale(1);
}
50% {
transform: var(--translate) scale(1.1);
}
}
.react-flow.touch-flow .react-flow__handle.clickconnecting {
animation: bounce 1600ms infinite ease-in;
}
@@ -1,19 +0,0 @@
.flow :global .react-flow__handle {
width: 20px;
height: 20px;
border-radius: 3px;
background-color: #9f7aea;
}
.flow :global .react-flow__handle.connecting {
animation: bounce 1600ms infinite ease-out;
}
@keyframes bounce {
0% {
transform: translate(0, -50%) scale(1);
}
50% {
transform: translate(0, -50%) scale(1.1);
}
}
@@ -24,10 +24,14 @@
background: #fff; background: #fff;
} }
.validationflow :global .connecting { .validationflow :global .connectingto {
background: #ff6060; background: #ff6060;
} }
.validationflow :global .react-flow__node-custominput .connectingfrom {
background: #55dd99;
}
.validationflow :global .valid { .validationflow :global .valid {
background: #55dd99; background: #55dd99;
} }
@@ -111,9 +111,10 @@
{ {
id: '5a', id: '5a',
type: 'defaultResizer', type: 'defaultResizer',
data: { label: 'Child' }, data: { label: 'Child with extent parent' },
position: { x: 50, y: 50 }, position: { x: 50, y: 50 },
parentNode: '5', parentNode: '5',
extent: 'parent',
style: nodeStyle style: nodeStyle
}, },
{ {
@@ -137,6 +138,7 @@
maxZoom={5} maxZoom={5}
snapGrid={snapToGrid ? [10, 10] : undefined} snapGrid={snapToGrid ? [10, 10] : undefined}
fitView fitView
nodeOrigin={[0.5, 0.5]}
> >
<Controls /> <Controls />
<Panel position="bottom-right"> <Panel position="bottom-right">
@@ -1,7 +1,11 @@
.svelte-flow__handle.connecting { .svelte-flow__handle.connectingto {
background: #ff6060; background: #ff6060;
} }
.svelte-flow__handle.connectingfrom {
background: #55dd99;
}
.svelte-flow__handle.valid { .svelte-flow__handle.valid {
background: #55dd99; background: #55dd99;
} }
+2
View File
@@ -5,6 +5,7 @@
## ⚠️ Breaking changes ## ⚠️ Breaking changes
- `useNodesData` not only returns data objects but also the type and the id of the node - `useNodesData` not only returns data objects but also the type and the id of the node
- status class names for Handle components are slightly different. It's now "connectingfrom" and "connectingto" instead of "connecting"
## Patch changes ## Patch changes
@@ -12,6 +13,7 @@
- `disableKeyboardA11y` now also disables Enter and Escape for selecting/deselecting nodes and edges - `disableKeyboardA11y` now also disables Enter and Escape for selecting/deselecting nodes and edges
- fix bug where users couldn't drag a node after toggle nodes `hidden` attribute - fix bug where users couldn't drag a node after toggle nodes `hidden` attribute
- add `initialWidth` and `initialHeight` node attributes for specifying initial dimensions for ssr - add `initialWidth` and `initialHeight` node attributes for specifying initial dimensions for ssr
- fix `NodeResizer` when used in combination with `nodeOrigin`
## 12.0.0-next.9 ## 12.0.0-next.9
@@ -50,12 +50,13 @@ function ResizeControl({
domNode: resizeControlRef.current, domNode: resizeControlRef.current,
nodeId: id, nodeId: id,
getStoreItems: () => { getStoreItems: () => {
const { nodeLookup, transform, snapGrid, snapToGrid } = store.getState(); const { nodeLookup, transform, snapGrid, snapToGrid, nodeOrigin } = store.getState();
return { return {
nodeLookup, nodeLookup,
transform, transform,
snapGrid, snapGrid,
snapToGrid, snapToGrid,
nodeOrigin,
}; };
}, },
onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => { onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => {
+27 -7
View File
@@ -16,6 +16,7 @@ import {
type HandleProps, type HandleProps,
type Connection, type Connection,
type HandleType, type HandleType,
ConnectionMode,
} from '@xyflow/system'; } from '@xyflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore'; import { useStore, useStoreApi } from '../../hooks/useStore';
@@ -36,14 +37,24 @@ const connectingSelector =
connectionStartHandle: startHandle, connectionStartHandle: startHandle,
connectionEndHandle: endHandle, connectionEndHandle: endHandle,
connectionClickStartHandle: clickHandle, connectionClickStartHandle: clickHandle,
connectionMode,
connectionStatus,
} = state; } = state;
const connectingTo = endHandle?.nodeId === nodeId && endHandle?.handleId === handleId && endHandle?.type === type;
return { return {
connecting: connectingFrom:
(startHandle?.nodeId === nodeId && startHandle?.handleId === handleId && startHandle?.type === type) || startHandle?.nodeId === nodeId && startHandle?.handleId === handleId && startHandle?.type === type,
(endHandle?.nodeId === nodeId && endHandle?.handleId === handleId && endHandle?.type === type), connectingTo,
clickConnecting: clickConnecting:
clickHandle?.nodeId === nodeId && clickHandle?.handleId === handleId && clickHandle?.type === type, clickHandle?.nodeId === nodeId && clickHandle?.handleId === handleId && clickHandle?.type === type,
isPossibleEndHandle:
connectionMode === ConnectionMode.Strict
? startHandle?.type !== type
: nodeId !== startHandle?.nodeId || handleId !== startHandle?.handleId,
connectionInProcess: !!startHandle,
valid: connectingTo && connectionStatus === 'valid',
}; };
}; };
@@ -71,7 +82,10 @@ const HandleComponent = forwardRef<HTMLDivElement, HandleComponentProps>(
const store = useStoreApi(); const store = useStoreApi();
const nodeId = useNodeId(); const nodeId = useNodeId();
const { connectOnClick, noPanClassName, rfId } = useStore(selector, shallow); const { connectOnClick, noPanClassName, rfId } = useStore(selector, shallow);
const { connecting, clickConnecting } = useStore(connectingSelector(nodeId, handleId, type), shallow); const { connectingFrom, connectingTo, clickConnecting, isPossibleEndHandle, connectionInProcess, valid } = useStore(
connectingSelector(nodeId, handleId, type),
shallow
);
if (!nodeId) { if (!nodeId) {
store.getState().onError?.('010', errorMessages['error010']()); store.getState().onError?.('010', errorMessages['error010']());
@@ -201,10 +215,16 @@ const HandleComponent = forwardRef<HTMLDivElement, HandleComponentProps>(
connectable: isConnectable, connectable: isConnectable,
connectablestart: isConnectableStart, connectablestart: isConnectableStart,
connectableend: isConnectableEnd, connectableend: isConnectableEnd,
connecting: clickConnecting, clickconnecting: clickConnecting,
// this class is used to style the handle when the user is connecting connectingfrom: connectingFrom,
connectingto: connectingTo,
valid,
// shows where you can start a connection from
// and where you can end it while connecting
connectionindicator: connectionindicator:
isConnectable && ((isConnectableStart && !connecting) || (isConnectableEnd && connecting)), isConnectable &&
(!connectionInProcess || isPossibleEndHandle) &&
(connectionInProcess ? isConnectableEnd : isConnectableStart),
}, },
])} ])}
onMouseDown={onPointerDown} onMouseDown={onPointerDown}
+16 -18
View File
@@ -31,24 +31,22 @@ export function useDrag({
const xyDrag = useRef<XYDragInstance>(); const xyDrag = useRef<XYDragInstance>();
useEffect(() => { useEffect(() => {
if (nodeRef?.current) { xyDrag.current = XYDrag({
xyDrag.current = XYDrag({ getStoreItems: () => store.getState(),
getStoreItems: () => store.getState(), onNodeMouseDown: (id: string) => {
onNodeMouseDown: (id: string) => { handleNodeClick({
handleNodeClick({ id,
id, store,
store, nodeRef,
nodeRef, });
}); },
}, onDragStart: () => {
onDragStart: () => { setDragging(true);
setDragging(true); },
}, onDragStop: () => {
onDragStop: () => { setDragging(false);
setDragging(false); },
}, });
});
}
}, []); }, []);
useEffect(() => { useEffect(() => {
+2 -4
View File
@@ -303,13 +303,11 @@ const createRFStore = ({
connectionEndHandle: null, connectionEndHandle: null,
}), }),
updateConnection: (params) => { updateConnection: (params) => {
const { connectionStatus, connectionStartHandle, connectionEndHandle, connectionPosition } = get(); const { connectionPosition } = get();
const currentConnection = { const currentConnection = {
...params,
connectionPosition: params.connectionPosition ?? connectionPosition, connectionPosition: params.connectionPosition ?? connectionPosition,
connectionStatus: params.connectionStatus ?? connectionStatus,
connectionStartHandle: params.connectionStartHandle ?? connectionStartHandle,
connectionEndHandle: params.connectionEndHandle ?? connectionEndHandle,
}; };
set(currentConnection); set(currentConnection);
+2
View File
@@ -5,12 +5,14 @@
## ⚠️ Breaking changes ## ⚠️ Breaking changes
- `useNodesData` not only returns data objects but also the type and the id of the node - `useNodesData` not only returns data objects but also the type and the id of the node
- status class names for Handle components are slightly different. It's now "connectingfrom" and "connectingto" instead of "connecting"
## Patch changes ## Patch changes
- better cursor defaults for the pane, nodes and edges - better cursor defaults for the pane, nodes and edges
- add `initialWidth` and `initialHeight` node attributes for specifying initial dimensions for ssr - add `initialWidth` and `initialHeight` node attributes for specifying initial dimensions for ssr
- always re-measure nodes when new nodes get passed - always re-measure nodes when new nodes get passed
- fix `NodeResizer` when used in combination with `nodeOrigin`
## 0.0.36 ## 0.0.36
@@ -56,7 +56,8 @@
onconnect: onConnectAction, onconnect: onConnectAction,
onconnectstart: onConnectStartAction, onconnectstart: onConnectStartAction,
onconnectend: onConnectEndAction, onconnectend: onConnectEndAction,
flowId flowId,
connection
} = store; } = store;
function onPointerDown(event: MouseEvent | TouchEvent) { function onPointerDown(event: MouseEvent | TouchEvent) {
@@ -123,6 +124,16 @@
prevConnections = connections ?? new Map(); prevConnections = connections ?? new Map();
} }
$: connectingFrom =
$connection.startHandle?.nodeId === nodeId &&
$connection.startHandle?.type === type &&
$connection.startHandle?.handleId === handleId;
$: connectingTo =
$connection.endHandle?.nodeId === nodeId &&
$connection.endHandle?.type === type &&
$connection.endHandle?.handleId === handleId;
$: valid = connectingTo && $connection.status === 'valid';
// @todo implement connectablestart, connectableend // @todo implement connectablestart, connectableend
</script> </script>
@@ -141,6 +152,11 @@ The Handle component is the part of a node that can be used to connect nodes.
'nodrag', 'nodrag',
'nopan', 'nopan',
position, position,
{
valid,
connectingto: connectingTo,
connectingfrom: connectingFrom
},
className className
])} ])}
class:source={!isTarget} class:source={!isTarget}
@@ -197,7 +197,7 @@
style:z-index={zIndex} style:z-index={zIndex}
style:transform="translate({positionOriginX}px, {positionOriginY}px)" style:transform="translate({positionOriginX}px, {positionOriginY}px)"
style:visibility={initialized ? 'visible' : 'hidden'} style:visibility={initialized ? 'visible' : 'hidden'}
style="{inlineStyleDimensions.width} {inlineStyleDimensions.height} {style ?? ''};" style="{style ?? ''};{inlineStyleDimensions.width}{inlineStyleDimensions.height}"
on:click={onSelectNodeHandler} on:click={onSelectNodeHandler}
on:mouseenter={(event) => dispatch('nodemouseenter', { node, event })} on:mouseenter={(event) => dispatch('nodemouseenter', { node, event })}
on:mouseleave={(event) => dispatch('nodemouseleave', { node, event })} on:mouseleave={(event) => dispatch('nodemouseleave', { node, event })}
@@ -35,7 +35,7 @@
let className: $$Props['class'] = ''; let className: $$Props['class'] = '';
export { className as class }; export { className as class };
const { nodeLookup, snapGrid, viewport, nodes } = useStore(); const { nodeLookup, snapGrid, viewport, nodes, nodeOrigin } = useStore();
const contextNodeId = getContext<string>('svelteflow__node_id'); const contextNodeId = getContext<string>('svelteflow__node_id');
$: id = typeof nodeId === 'string' ? nodeId : contextNodeId; $: id = typeof nodeId === 'string' ? nodeId : contextNodeId;
@@ -64,7 +64,8 @@
nodeLookup: $nodeLookup, nodeLookup: $nodeLookup,
transform: [$viewport.x, $viewport.y, $viewport.zoom], transform: [$viewport.x, $viewport.y, $viewport.zoom],
snapGrid: $snapGrid ?? undefined, snapGrid: $snapGrid ?? undefined,
snapToGrid: !!$snapGrid snapToGrid: !!$snapGrid,
nodeOrigin: $nodeOrigin
}; };
}, },
onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => { onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => {
+4
View File
@@ -223,6 +223,10 @@ svg.xy-flow__connectionline {
min-width: 5px; min-width: 5px;
min-height: 5px; min-height: 5px;
&.connectingfrom {
pointer-events: all;
}
&.connectionindicator { &.connectionindicator {
pointer-events: all; pointer-events: all;
cursor: crosshair; cursor: crosshair;
+1 -15
View File
@@ -15,7 +15,7 @@ import {
type ConnectionHandle, type ConnectionHandle,
} from '../types'; } from '../types';
import { getClosestHandle, getConnectionStatus, getHandleLookup, getHandleType, resetRecentHandle } from './utils'; import { getClosestHandle, getConnectionStatus, getHandleLookup, getHandleType } from './utils';
export type OnPointerDownParams = { export type OnPointerDownParams = {
autoPanOnConnect: boolean; autoPanOnConnect: boolean;
@@ -107,7 +107,6 @@ function onPointerDown(
return; return;
} }
let prevActiveHandle: Element;
let connectionPosition = getEventPosition(event, containerBounds); let connectionPosition = getEventPosition(event, containerBounds);
let autoPanStarted = false; let autoPanStarted = false;
let connection: Connection | null = null; let connection: Connection | null = null;
@@ -194,18 +193,6 @@ function onPointerDown(
connectionStatus: getConnectionStatus(!!closestHandle, isValid), connectionStatus: getConnectionStatus(!!closestHandle, isValid),
connectionEndHandle: result.endHandle, connectionEndHandle: result.endHandle,
}); });
if (!closestHandle && !isValid && !handleDomNode) {
return resetRecentHandle(prevActiveHandle, lib);
}
if (connection?.source !== connection?.target && handleDomNode) {
resetRecentHandle(prevActiveHandle, lib);
prevActiveHandle = handleDomNode;
handleDomNode.classList.add('connecting', `${lib}-flow__handle-connecting`);
handleDomNode.classList.toggle('valid', isValid);
handleDomNode.classList.toggle(`${lib}-flow__handle-valid`, isValid);
}
} }
function onPointerUp(event: MouseEvent | TouchEvent) { function onPointerUp(event: MouseEvent | TouchEvent) {
@@ -221,7 +208,6 @@ function onPointerDown(
onEdgeUpdateEnd?.(event); onEdgeUpdateEnd?.(event);
} }
resetRecentHandle(prevActiveHandle, lib);
cancelConnection(); cancelConnection();
cancelAnimationFrame(autoPanId); cancelAnimationFrame(autoPanId);
autoPanStarted = false; autoPanStarted = false;
+2 -6
View File
@@ -38,7 +38,7 @@ export function getClosestHandle(
let closestHandles: ConnectionHandle[] = []; let closestHandles: ConnectionHandle[] = [];
let minDistance = Infinity; let minDistance = Infinity;
handles.forEach((handle) => { for (const handle of handles) {
const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2)); const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2));
if (distance <= connectionRadius) { if (distance <= connectionRadius) {
if (distance < minDistance) { if (distance < minDistance) {
@@ -49,7 +49,7 @@ export function getClosestHandle(
} }
minDistance = distance; minDistance = distance;
} }
}); }
if (!closestHandles.length) { if (!closestHandles.length) {
return null; return null;
@@ -101,10 +101,6 @@ export function getHandleType(
return null; return null;
} }
export function resetRecentHandle(handleDomNode: Element, lib: string): void {
handleDomNode?.classList.remove('valid', 'connecting', `${lib}-flow__handle-valid`, `${lib}-flow__handle-connecting`);
}
export function getConnectionStatus(isInsideConnectionRadius: boolean, isHandleValid: boolean) { export function getConnectionStatus(isInsideConnectionRadius: boolean, isHandleValid: boolean) {
let connectionStatus = null; let connectionStatus = null;
+39 -34
View File
@@ -3,7 +3,7 @@ import { select } from 'd3-selection';
import { getControlDirection, getDimensionsAfterResize, getResizeDirection } from './utils'; import { getControlDirection, getDimensionsAfterResize, getResizeDirection } from './utils';
import { getPointerPosition } from '../utils'; import { getPointerPosition } from '../utils';
import type { CoordinateExtent, NodeBase, NodeLookup, Transform, XYPosition } from '../types'; import type { CoordinateExtent, NodeBase, NodeLookup, NodeOrigin, Transform, XYPosition } from '../types';
import type { OnResize, OnResizeEnd, OnResizeStart, ResizeDragEvent, ShouldResize, ControlPosition } from './types'; import type { OnResize, OnResizeEnd, OnResizeStart, ResizeDragEvent, ShouldResize, ControlPosition } from './types';
const initPrevValues = { width: 0, height: 0, x: 0, y: 0 }; const initPrevValues = { width: 0, height: 0, x: 0, y: 0 };
@@ -42,6 +42,7 @@ type XYResizerParams = {
transform: Transform; transform: Transform;
snapGrid?: [number, number]; snapGrid?: [number, number];
snapToGrid: boolean; snapToGrid: boolean;
nodeOrigin: NodeOrigin;
}; };
onChange: (changes: XYResizerChange, childChanges: XYResizerChildChange[]) => void; onChange: (changes: XYResizerChange, childChanges: XYResizerChildChange[]) => void;
onEnd?: () => void; onEnd?: () => void;
@@ -74,13 +75,17 @@ function nodeToParentExtent(node: NodeBase): CoordinateExtent {
]; ];
} }
function nodeToChildExtent(child: NodeBase, parent: NodeBase): CoordinateExtent { function nodeToChildExtent(child: NodeBase, parent: NodeBase, nodeOrigin: NodeOrigin): CoordinateExtent {
const x = parent.position.x + child.position.x;
const y = parent.position.y + child.position.y;
const width = child.computed!.width! ?? 0;
const height = child.computed!.height! ?? 0;
const originOffsetX = nodeOrigin[0] * width;
const originOffsetY = nodeOrigin[1] * height;
return [ return [
[parent.position.x + child.position.x, parent.position.y + child.position.y], [x - originOffsetX, y - originOffsetY],
[ [x + width - originOffsetX, y + height - originOffsetY],
parent.position.x + child.position.x + child.computed!.width!,
parent.position.y + child.position.y + child.computed!.height!,
],
]; ];
} }
@@ -109,7 +114,7 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
const dragHandler = drag<HTMLDivElement, unknown>() const dragHandler = drag<HTMLDivElement, unknown>()
.on('start', (event: ResizeDragEvent) => { .on('start', (event: ResizeDragEvent) => {
const { nodeLookup, transform, snapGrid, snapToGrid } = getStoreItems(); const { nodeLookup, transform, snapGrid, snapToGrid, nodeOrigin } = getStoreItems();
node = nodeLookup.get(nodeId); node = nodeLookup.get(nodeId);
if (node) { if (node) {
@@ -151,7 +156,7 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
}); });
if (child.extent === 'parent' || child.expandParent) { if (child.extent === 'parent' || child.expandParent) {
const extent = nodeToChildExtent(child, node!); const extent = nodeToChildExtent(child, node!, child.origin ?? nodeOrigin);
if (childExtent) { if (childExtent) {
childExtent = [ childExtent = [
@@ -169,14 +174,14 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
} }
}) })
.on('drag', (event: ResizeDragEvent) => { .on('drag', (event: ResizeDragEvent) => {
const { transform, snapGrid, snapToGrid } = getStoreItems(); const { transform, snapGrid, snapToGrid, nodeOrigin: storeNodeOrigin } = getStoreItems();
const pointerPosition = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid }); const pointerPosition = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
const childChanges: XYResizerChildChange[] = []; const childChanges: XYResizerChildChange[] = [];
if (node) { if (node) {
const change = { ...initChange };
const { x: prevX, y: prevY, width: prevWidth, height: prevHeight } = prevValues; const { x: prevX, y: prevY, width: prevWidth, height: prevHeight } = prevValues;
const change = { ...initChange };
const nodeOrigin = node.origin ?? storeNodeOrigin;
const { width, height, x, y } = getDimensionsAfterResize( const { width, height, x, y } = getDimensionsAfterResize(
startValues, startValues,
@@ -184,6 +189,7 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
pointerPosition, pointerPosition,
boundaries, boundaries,
keepAspectRatio, keepAspectRatio,
nodeOrigin,
parentExtent, parentExtent,
childExtent childExtent
); );
@@ -191,40 +197,39 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
const isWidthChange = width !== prevWidth; const isWidthChange = width !== prevWidth;
const isHeightChange = height !== prevHeight; const isHeightChange = height !== prevHeight;
if (controlDirection.affectsX || controlDirection.affectsY) { const isXPosChange = x !== prevX && isWidthChange;
const isXPosChange = x !== prevX && isWidthChange; const isYPosChange = y !== prevY && isHeightChange;
const isYPosChange = y !== prevY && isHeightChange;
if (isXPosChange || isYPosChange) { if (isXPosChange || isYPosChange || nodeOrigin[0] === 1 || nodeOrigin[1] == 1) {
change.isXPosChange = isXPosChange; change.isXPosChange = isXPosChange;
change.isYPosChange = isYPosChange; change.isYPosChange = isYPosChange;
change.x = isXPosChange ? x : prevX; change.x = isXPosChange ? x : prevX;
change.y = isYPosChange ? y : prevY; change.y = isYPosChange ? y : prevY;
prevValues.x = change.x; prevValues.x = change.x;
prevValues.y = change.y; prevValues.y = change.y;
// Fix expandParent when resizing from top/left // Fix expandParent when resizing from top/left
if (parentNode && node.expandParent) { if (parentNode && node.expandParent) {
if (change.x < 0) { if (change.x < 0) {
prevValues.x = 0; prevValues.x = 0;
startValues.x = startValues.x - change.x; startValues.x = startValues.x - change.x;
} }
if (change.y < 0) { if (change.y < 0) {
prevValues.y = 0; prevValues.y = 0;
startValues.y = startValues.y - change.y; startValues.y = startValues.y - change.y;
}
} }
} }
if (childNodes.length > 0) { if (childNodes.length > 0) {
const xChange = x - prevX; const xChange = x - prevX;
const yChange = y - prevY; const yChange = y - prevY;
for (const childNode of childNodes) { for (const childNode of childNodes) {
childNode.position = { childNode.position = {
x: childNode.position.x - xChange, x: childNode.position.x - xChange + nodeOrigin[0] * (width - prevWidth),
y: childNode.position.y - yChange, y: childNode.position.y - yChange + nodeOrigin[1] * (height - prevHeight),
}; };
childChanges.push(childNode); childChanges.push(childNode);
} }
+25 -12
View File
@@ -1,4 +1,4 @@
import { CoordinateExtent } from '../types'; import { CoordinateExtent, NodeOrigin } from '../types';
import { getPointerPosition } from '../utils'; import { getPointerPosition } from '../utils';
import { ControlPosition } from './types'; import { ControlPosition } from './types';
@@ -94,7 +94,7 @@ function xor(a: boolean, b: boolean) {
/** /**
* Calculates new width & height and x & y of node after resize based on pointer position * Calculates new width & height and x & y of node after resize based on pointer position
* @description - Buckle up, this is a chunky one! If you want to determine the new dimensions of a node after a resize, * @description - Buckle up, this is a chunky one... If you want to determine the new dimensions of a node after a resize,
* you have to account for all possible restrictions: min/max width/height of the node, the maximum extent the node is allowed * you have to account for all possible restrictions: min/max width/height of the node, the maximum extent the node is allowed
* to move in (in this case: resize into) determined by the parent node, the minimal extent determined by child nodes * to move in (in this case: resize into) determined by the parent node, the minimal extent determined by child nodes
* with expandParent or extent: 'parent' set and oh yeah, these things also have to work with keepAspectRatio! * with expandParent or extent: 'parent' set and oh yeah, these things also have to work with keepAspectRatio!
@@ -102,6 +102,8 @@ function xor(a: boolean, b: boolean) {
* strongest restriction. Because the resize affects x, y and width, height and width, height of a opposing side with keepAspectRatio, * strongest restriction. Because the resize affects x, y and width, height and width, height of a opposing side with keepAspectRatio,
* the resize amount is always kept in distX & distY amount (the distance in mouse movement) * the resize amount is always kept in distX & distY amount (the distance in mouse movement)
* Instead of clamping each value, we first calculate the biggest 'clamp' (for the lack of a better name) and then apply it to all values. * Instead of clamping each value, we first calculate the biggest 'clamp' (for the lack of a better name) and then apply it to all values.
* To complicate things nodeOrigin has to be taken into account as well. This is done by offsetting the nodes as if their origin is [0, 0],
* then calculating the restrictions as usual
* @param startValues - starting values of resize * @param startValues - starting values of resize
* @param controlDirection - dimensions affected by the resize * @param controlDirection - dimensions affected by the resize
* @param pointerPosition - the current pointer position corrected for snapping * @param pointerPosition - the current pointer position corrected for snapping
@@ -115,6 +117,7 @@ export function getDimensionsAfterResize(
pointerPosition: ReturnType<typeof getPointerPosition>, pointerPosition: ReturnType<typeof getPointerPosition>,
boundaries: { minWidth: number; maxWidth: number; minHeight: number; maxHeight: number }, boundaries: { minWidth: number; maxWidth: number; minHeight: number; maxHeight: number },
keepAspectRatio: boolean, keepAspectRatio: boolean,
nodeOrigin: NodeOrigin,
extent?: CoordinateExtent, extent?: CoordinateExtent,
childExtent?: CoordinateExtent childExtent?: CoordinateExtent
) { ) {
@@ -132,6 +135,9 @@ export function getDimensionsAfterResize(
const newWidth = startWidth + (affectsX ? -distX : distX); const newWidth = startWidth + (affectsX ? -distX : distX);
const newHeight = startHeight + (affectsY ? -distY : distY); const newHeight = startHeight + (affectsY ? -distY : distY);
const originOffsetX = -nodeOrigin[0] * startWidth;
const originOffsetY = -nodeOrigin[1] * startHeight;
// Check if maxWidth, minWWidth, maxHeight, minHeight are restricting the resize // Check if maxWidth, minWWidth, maxHeight, minHeight are restricting the resize
let clampX = getSizeClamp(newWidth, minWidth, maxWidth); let clampX = getSizeClamp(newWidth, minWidth, maxWidth);
let clampY = getSizeClamp(newHeight, minHeight, maxHeight); let clampY = getSizeClamp(newHeight, minHeight, maxHeight);
@@ -141,15 +147,15 @@ export function getDimensionsAfterResize(
let xExtentClamp = 0; let xExtentClamp = 0;
let yExtentClamp = 0; let yExtentClamp = 0;
if (affectsX && distX < 0) { if (affectsX && distX < 0) {
xExtentClamp = getLowerExtentClamp(startX + distX, extent[0][0]); xExtentClamp = getLowerExtentClamp(startX + distX + originOffsetX, extent[0][0]);
} else if (!affectsX && distX > 0) { } else if (!affectsX && distX > 0) {
xExtentClamp = getUpperExtentClamp(startX + newWidth, extent[1][0]); xExtentClamp = getUpperExtentClamp(startX + newWidth + originOffsetX, extent[1][0]);
} }
if (affectsY && distY < 0) { if (affectsY && distY < 0) {
yExtentClamp = getLowerExtentClamp(startY + distY, extent[0][1]); yExtentClamp = getLowerExtentClamp(startY + distY + originOffsetY, extent[0][1]);
} else if (!affectsY && distY > 0) { } else if (!affectsY && distY > 0) {
yExtentClamp = getUpperExtentClamp(startY + newHeight, extent[1][1]); yExtentClamp = getUpperExtentClamp(startY + newHeight + originOffsetY, extent[1][1]);
} }
clampX = Math.max(clampX, xExtentClamp); clampX = Math.max(clampX, xExtentClamp);
@@ -187,10 +193,12 @@ export function getDimensionsAfterResize(
if (extent) { if (extent) {
let aspectExtentClamp = 0; let aspectExtentClamp = 0;
if ((!affectsX && !affectsY) || (affectsX && !affectsY && isDiagonal)) { if ((!affectsX && !affectsY) || (affectsX && !affectsY && isDiagonal)) {
aspectExtentClamp = getUpperExtentClamp(startY + newWidth / aspectRatio, extent[1][1]) * aspectRatio; aspectExtentClamp =
getUpperExtentClamp(startY + originOffsetY + newWidth / aspectRatio, extent[1][1]) * aspectRatio;
} else { } else {
aspectExtentClamp = aspectExtentClamp =
getLowerExtentClamp(startY + (affectsX ? distX : -distX) / aspectRatio, extent[0][1]) * aspectRatio; getLowerExtentClamp(startY + originOffsetY + (affectsX ? distX : -distX) / aspectRatio, extent[0][1]) *
aspectRatio;
} }
clampX = Math.max(clampX, aspectExtentClamp); clampX = Math.max(clampX, aspectExtentClamp);
} }
@@ -216,10 +224,12 @@ export function getDimensionsAfterResize(
if (extent) { if (extent) {
let aspectExtentClamp = 0; let aspectExtentClamp = 0;
if ((!affectsX && !affectsY) || (affectsY && !affectsX && isDiagonal)) { if ((!affectsX && !affectsY) || (affectsY && !affectsX && isDiagonal)) {
aspectExtentClamp = getUpperExtentClamp(startX + newHeight * aspectRatio, extent[1][0]) / aspectRatio; aspectExtentClamp =
getUpperExtentClamp(startX + newHeight * aspectRatio + originOffsetX, extent[1][0]) / aspectRatio;
} else { } else {
aspectExtentClamp = aspectExtentClamp =
getLowerExtentClamp(startX + (affectsY ? distY : -distY) * aspectRatio, extent[0][0]) / aspectRatio; getLowerExtentClamp(startX + (affectsY ? distY : -distY) * aspectRatio + originOffsetX, extent[0][0]) /
aspectRatio;
} }
clampY = Math.max(clampY, aspectExtentClamp); clampY = Math.max(clampY, aspectExtentClamp);
} }
@@ -258,10 +268,13 @@ export function getDimensionsAfterResize(
} }
} }
const x = affectsX ? startX + distX : startX;
const y = affectsY ? startY + distY : startY;
return { return {
width: startWidth + (affectsX ? -distX : distX), width: startWidth + (affectsX ? -distX : distX),
height: startHeight + (affectsY ? -distY : distY), height: startHeight + (affectsY ? -distY : distY),
x: affectsX ? startX + distX : startX, x: nodeOrigin[0] * distX * (!affectsX ? 1 : -1) + x,
y: affectsY ? startY + distY : startY, y: nodeOrigin[1] * distY * (!affectsY ? 1 : -1) + y,
}; };
} }