fixed useConnection hook, made derivedWarnings more specific, fixed updating when internals change

This commit is contained in:
peterkogo
2024-12-12 16:14:29 +01:00
parent 9105d22c46
commit 72c075e5fb
16 changed files with 176 additions and 154 deletions

View File

@@ -1,5 +1,4 @@
<script lang="ts">
import { writable } from 'svelte/store';
import {
SvelteFlow,
useSvelteFlow,
@@ -19,11 +18,11 @@
}
];
const nodes = writable<Node[]>(initialNodes);
const edges = writable<Edge[]>([]);
let nodes = $state.raw<Node[]>(initialNodes);
let edges = $state.raw<Edge[]>([]);
let connectingNodeId: string | null = $state('0');
let rect: DOMRectReadOnly = $state();
let rect = $state<DOMRectReadOnly>();
let id = 1;
const getId = () => `${id++}`;
@@ -56,15 +55,12 @@
origin: [0.5, 0.0]
};
$nodes.push(newNode);
$edges.push({
nodes.push(newNode);
edges.push({
source: connectingNodeId,
target: id,
id: `${connectingNodeId}--${id}`
});
$nodes = $nodes;
$edges = $edges;
}
};
</script>
@@ -73,8 +69,8 @@
<div class="wrapper" bind:contentRect={rect}>
<SvelteFlow
{nodes}
{edges}
bind:nodes
bind:edges
fitView
fitViewOptions={{ padding: 2 }}
onconnectstart={(_, { nodeId }) => {

View File

@@ -1,5 +1,4 @@
<script lang="ts">
import { writable } from 'svelte/store';
import {
SvelteFlow,
Controls,
@@ -18,7 +17,7 @@
targetPosition: Position.Left
};
const nodes = writable([
let nodes = $state.raw([
{
id: 'A',
position: { x: 0, y: 150 },
@@ -30,16 +29,16 @@
{ id: 'D', position: { x: 250, y: 300 }, data: { label: 'D' }, ...nodeDefaults }
]);
const edges = writable([
let edges = $state.raw([
{ id: 'A-B', source: 'A', target: 'B' },
{ id: 'A-C', source: 'A', target: 'C' },
{ id: 'A-D', source: 'A', target: 'D' }
]);
let colorMode: ColorMode = $state('light');
let colorMode: ColorMode = $state('dark');
</script>
<SvelteFlow {nodes} {edges} {colorMode} fitView>
<SvelteFlow bind:nodes bind:edges {colorMode} fitView>
<Controls />
<Background variant={BackgroundVariant.Dots} />
<MiniMap />

View File

@@ -1,7 +1,6 @@
<script lang="ts">
import { SvelteFlow } from '@xyflow/svelte';
import { Background, BackgroundVariant, type Edge, type Node } from '@xyflow/svelte';
import { writable } from 'svelte/store';
import CustomNode from './CustomNode.svelte';
import ConnectionLine from './ConnectionLine.svelte';
@@ -12,7 +11,7 @@
custom: CustomNode
};
const nodes = writable<Node[]>([
let nodes = $state.raw<Node[]>([
{
id: 'connectionline-1',
type: 'custom',
@@ -21,14 +20,14 @@
}
]);
const edges = writable<Edge[]>([]);
let edges = $state.raw<Edge[]>([]);
</script>
<div style="height:100vh;">
<SvelteFlow {nodeTypes} {nodes} {edges} fitView>
<SvelteFlow bind:nodes bind:edges {nodeTypes} fitView>
{#snippet connectionLine()}
<ConnectionLine />
{/snippet}
<ConnectionLine />
{/snippet}
<Background variant={BackgroundVariant.Lines} />
</SvelteFlow>
</div>

View File

@@ -1,11 +1,11 @@
<script lang="ts">
import { getBezierPath, useConnection } from '@xyflow/svelte';
const connection = useConnection();
const connection = $derived(useConnection());
let path: string | null = $derived.by(() => {
if ($connection.inProgress) {
const { from, to, fromPosition, toPosition } = $connection;
if (connection.inProgress) {
const { from, to, fromPosition, toPosition } = connection;
const pathParams = {
sourceX: from.x,
sourceY: from.y,
@@ -21,6 +21,6 @@
});
</script>
{#if $connection.inProgress}
<path d={path} fill="none" stroke={$connection.fromHandle.id} />
{#if connection.inProgress}
<path d={path} fill="none" stroke={connection.fromHandle.id} />
{/if}

View File

@@ -1,5 +1,13 @@
<script lang="ts" module>
// TODO: Is this the best way?
class background {
color: string = $state('#1A192B');
}
export const bg = new background();
</script>
<script lang="ts">
import { writable } from 'svelte/store';
import {
SvelteFlow,
Controls,
@@ -20,9 +28,7 @@
colorNode: CustomNode
};
const bgColor = writable('#1A192B');
const nodes = writable<Node[]>([
let nodes = $state.raw<Node[]>([
{
id: '1',
type: 'input',
@@ -33,7 +39,7 @@
{
id: '2',
type: 'colorNode',
data: { colorStore: bgColor },
data: {},
position: { x: 250, y: 50 }
},
{
@@ -52,7 +58,7 @@
}
]);
const edges = writable<Edge[]>([
let edges = $state.raw<Edge[]>([
{
id: 'e1-2',
source: '1',
@@ -81,10 +87,10 @@
</script>
<SvelteFlow
{nodes}
{edges}
bind:nodes
bind:edges
{nodeTypes}
style="--xy-background-color: {$bgColor}"
style="--xy-background-color: {bg.color}"
fitView
onconnect={onConnect}
>

View File

@@ -1,8 +1,8 @@
<script lang="ts">
import type { Writable } from 'svelte/store';
import { Handle, Position, type NodeProps, type Node } from '@xyflow/svelte';
import { bg } from './+page.svelte';
let { data }: NodeProps<Node<{ colorStore: Writable<string> }>> = $props();
let { data }: NodeProps<Node> = $props();
const { colorStore } = data;
</script>
@@ -10,13 +10,13 @@
<div class="custom">
<Handle type="target" position={Position.Left} />
<div>
Custom Color Picker Node: <strong>{$colorStore}</strong>
Custom Color Picker Node: <strong>{bg.color}</strong>
</div>
<input
class="nodrag"
type="color"
oninput={(evt) => colorStore.set(evt.currentTarget.value)}
value={$colorStore}
oninput={(evt) => (bg.color = evt.currentTarget.value)}
value={bg.color}
/>
<Handle type="source" position={Position.Right} id="a" style="top: 20px;" />
<Handle type="source" position={Position.Right} id="b" style="top: auto; bottom: 10px;" />

View File

@@ -1,79 +1,78 @@
<script lang="ts">
import { writable } from 'svelte/store';
import { SvelteFlow, Background, Position, ConnectionLineType, Panel } from '@xyflow/svelte';
import type { Edge, Node } from '@xyflow/svelte';
import dagre from '@dagrejs/dagre';
import { writable } from 'svelte/store';
import { SvelteFlow, Background, Position, ConnectionLineType, Panel } from '@xyflow/svelte';
import type { Edge, Node } from '@xyflow/svelte';
import dagre from '@dagrejs/dagre';
import '@xyflow/svelte/dist/style.css';
import '@xyflow/svelte/dist/style.css';
import { initialNodes, initialEdges } from './nodes-and-edges';
import { initialNodes, initialEdges } from './nodes-and-edges';
const dagreGraph = new dagre.graphlib.Graph();
dagreGraph.setDefaultEdgeLabel(() => ({}));
const dagreGraph = new dagre.graphlib.Graph();
dagreGraph.setDefaultEdgeLabel(() => ({}));
const nodeWidth = 172;
const nodeHeight = 36;
const nodeWidth = 172;
const nodeHeight = 36;
function getLayoutedElements(nodes: Node[], edges: Edge[], direction = 'TB') {
const isHorizontal = direction === 'LR';
dagreGraph.setGraph({ rankdir: direction });
function getLayoutedElements(nodes: Node[], edges: Edge[], direction = 'TB') {
const isHorizontal = direction === 'LR';
dagreGraph.setGraph({ rankdir: direction });
nodes.forEach((node) => {
dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
});
nodes.forEach((node) => {
dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
});
edges.forEach((edge) => {
dagreGraph.setEdge(edge.source, edge.target);
});
edges.forEach((edge) => {
dagreGraph.setEdge(edge.source, edge.target);
});
dagre.layout(dagreGraph);
dagre.layout(dagreGraph);
nodes.forEach((node) => {
const nodeWithPosition = dagreGraph.node(node.id);
node.targetPosition = isHorizontal ? Position.Left : Position.Top;
node.sourcePosition = isHorizontal ? Position.Right : Position.Bottom;
const layoutedNodes = nodes.map((node) => {
const nodeWithPosition = dagreGraph.node(node.id);
// We are shifting the dagre node position (anchor=center center) to the top left
// so it matches the React Flow node anchor point (top left).
node.position = {
x: nodeWithPosition.x - nodeWidth / 2,
y: nodeWithPosition.y - nodeHeight / 2
};
});
return {
...node,
targetPosition: isHorizontal ? Position.Left : Position.Top,
sourcePosition: isHorizontal ? Position.Right : Position.Bottom,
position: {
x: nodeWithPosition.x - nodeWidth / 2,
y: nodeWithPosition.y - nodeHeight / 2
}
};
});
return { nodes, edges };
}
return { nodes: layoutedNodes, edges };
}
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
initialNodes,
initialEdges
);
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
initialNodes,
initialEdges
);
const nodes = writable<Node[]>(layoutedNodes);
const edges = writable<Edge[]>(layoutedEdges);
let nodes = $state.raw<Node[]>(layoutedNodes);
let edges = $state.raw<Edge[]>(layoutedEdges);
function onLayout(direction: string) {
const layoutedElements = getLayoutedElements($nodes, $edges, direction);
function onLayout(direction: string) {
const layoutedElements = getLayoutedElements(nodes, edges, direction);
$nodes = layoutedElements.nodes;
$edges = layoutedElements.edges;
// nodes.set(layoutedElements.nodes);
// edges.set(layoutedElements.edges);
}
nodes = layoutedElements.nodes;
edges = layoutedElements.edges;
}
</script>
<div style="height:100vh;">
<SvelteFlow
{nodes}
{edges}
fitView
connectionLineType={ConnectionLineType.SmoothStep}
defaultEdgeOptions={{ type: 'smoothstep', animated: true }}
>
<Panel position="top-right">
<button onclick={() => onLayout('TB')}>vertical layout</button>
<button onclick={() => onLayout('LR')}>horizontal layout</button>
</Panel>
<Background />
</SvelteFlow>
<SvelteFlow
bind:nodes
bind:edges
fitView
connectionLineType={ConnectionLineType.SmoothStep}
defaultEdgeOptions={{ type: 'smoothstep', animated: true }}
>
<Panel position="top-right">
<button onclick={() => onLayout('TB')}>vertical layout</button>
<button onclick={() => onLayout('LR')}>horizontal layout</button>
</Panel>
<Background />
</SvelteFlow>
</div>

View File

@@ -23,8 +23,6 @@
connectionLine?: Snippet;
} = $props();
// $inspect(store.connection);
let path = $derived.by(() => {
if (!store.connection.inProgress) {
return '';

View File

@@ -99,7 +99,7 @@
// Set store for provider context
const providerContext = getContext<ProviderContext>(key);
if (providerContext) {
if (providerContext && providerContext.setStore) {
providerContext.setStore(store);
}

View File

@@ -2,7 +2,14 @@ import { key } from '$lib/store';
import type { StoreContext } from '$lib/store/types';
import { getContext } from 'svelte';
export function derivedWarning(functionName: string) {
/**
* Warns the user that they should use $derived() when calling a hook.
* This is not neccessarry when the hook is called inside a child of <SvelteFlowFlow />,
* however exceptions can be made if you don't want to return a closure.
* @param functionName - The name of the function that is being called
* @param force - If true, the warning will be shown regardless if child of <SvelteFlowFlow />
*/
export function derivedWarning(functionName: string, force?: boolean) {
const storeContext = getContext<StoreContext>(key);
if (!storeContext) {
@@ -11,9 +18,8 @@ export function derivedWarning(functionName: string) {
);
}
if (storeContext.provider && !$effect.tracking()) {
console.warn(
`Use $derived(${functionName}()), when not calling inside a child of the <SvelteFlow /> component.`
);
if ((force || storeContext.provider) && !$effect.tracking()) {
console.warn(`Use $derived(${functionName}()) to receive updates when values change.`);
console.trace(functionName);
}
}

View File

@@ -0,0 +1,18 @@
import { useStore } from '$lib/store';
import type { ConnectionState } from '@xyflow/system';
import { derivedWarning } from './derivedWarning.svelte';
/**
* Hook for receiving the current connection.
*
* @public
* @returns current connection as a readable store
*/
export function useConnection(): ConnectionState {
if (process.env.NODE_ENV === 'development') {
derivedWarning('useConnection', true);
}
return useStore().connection;
}

View File

@@ -1,16 +0,0 @@
import type { Readable } from 'svelte/store';
import { useStore } from '$lib/store';
import type { ConnectionState } from '@xyflow/system';
/**
* Hook for receiving the current connection.
*
* @public
* @returns current connection as a readable store
*/
export function useConnection(): Readable<ConnectionState> {
const { connection } = useStore();
return connection;
}

View File

@@ -4,18 +4,10 @@ import { errorMessages } from '@xyflow/system';
import { useStore } from '$lib/store';
export function useHandleEdgeSelect() {
const {
edgeLookup,
selectionRect,
selectionRectMode,
multiselectionKeyPressed,
addSelectedEdges,
unselectNodesAndEdges,
elementsSelectable
} = useStore();
const store = useStore();
return (id: string) => {
const edge = get(edgeLookup).get(id);
const edge = store.edgeLookup.get(id);
if (!edge) {
console.warn('012', errorMessages['error012'](id));
@@ -23,16 +15,16 @@ export function useHandleEdgeSelect() {
}
const selectable =
edge.selectable || (get(elementsSelectable) && typeof edge.selectable === 'undefined');
edge.selectable || (store.elementsSelectable && typeof edge.selectable === 'undefined');
if (selectable) {
selectionRect.set(null);
selectionRectMode.set(null);
store.selectionRect = null;
store.selectionRectMode = null;
if (!edge.selected) {
addSelectedEdges([id]);
} else if (edge.selected && get(multiselectionKeyPressed)) {
unselectNodesAndEdges({ nodes: [], edges: [edge] });
store.addSelectedEdges([id]);
} else if (edge.selected && store.multiselectionKeyPressed) {
store.unselectNodesAndEdges({ nodes: [], edges: [edge] });
}
}
};

View File

@@ -33,7 +33,7 @@ export * from '$lib/utils';
//hooks
export * from '$lib/hooks/useSvelteFlow';
export * from '$lib/hooks/useUpdateNodeInternals';
export * from '$lib/hooks/useConnection';
export * from '$lib/hooks/useConnection.svelte';
export * from '$lib/hooks/useNodesEdges';
export * from '$lib/hooks/useHandleConnections';
export * from '$lib/hooks/useNodesData';

View File

@@ -72,7 +72,7 @@ export const initialEdgeTypes = {
export const getInitialStore = (signals: StoreSignals) => {
// We use a class here, because Svelte adds getters & setter for us.
// Inline classes have some performance implications but we just call it once.
// Inline classes have some performance implications but we just call it once (max twice).
class SvelteFlowStore {
get nodes() {
return signals.nodes;
@@ -223,6 +223,11 @@ export const getInitialStore = (signals: StoreSignals) => {
});
this.viewport = getViewportForBounds(bounds, this.width, this.height, 0.5, 2, 0.1);
}
if (process.env.NODE_ENV === 'development') {
warnIfDeeplyReactive(signals.nodes, 'nodes');
warnIfDeeplyReactive(signals.edges, 'edges');
}
}
resetStoreValues() {
@@ -231,3 +236,16 @@ export const getInitialStore = (signals: StoreSignals) => {
}
return new SvelteFlowStore();
};
// Only way to check if an object is a proxy
// is to see if is failes to perform a structured clone
// TODO: is $state.raw really nessessary?
function warnIfDeeplyReactive(array: unknown[] | undefined, name: string) {
try {
if (array && array.length > 0) {
structuredClone(array[0]);
}
} catch {
console.warn(`Use $state.raw for ${name} to prevent performance issues.`);
}
}

View File

@@ -337,10 +337,13 @@ export function updateNodeInternals<NodeType extends InternalNodeBase>(
}
if (node.hidden) {
node.internals = {
...node.internals,
handleBounds: undefined,
};
nodeLookup.set(node.id, {
...node,
internals: {
...node.internals,
handleBounds: undefined,
},
});
updatedInternals = true;
} else {
const dimensions = getDimensions(update.nodeElement);
@@ -362,15 +365,19 @@ export function updateNodeInternals<NodeType extends InternalNodeBase>(
positionAbsolute = clampPosition(positionAbsolute, extent, dimensions);
}
node.measured = dimensions;
node.internals = {
...node.internals,
positionAbsolute,
handleBounds: {
source: getHandleBounds('source', update.nodeElement, nodeBounds, zoom, node.id),
target: getHandleBounds('target', update.nodeElement, nodeBounds, zoom, node.id),
nodeLookup.set(node.id, {
...node,
measured: dimensions,
internals: {
...node.internals,
positionAbsolute,
handleBounds: {
source: getHandleBounds('source', update.nodeElement, nodeBounds, zoom, node.id),
target: getHandleBounds('target', update.nodeElement, nodeBounds, zoom, node.id),
},
},
};
});
if (node.parentId) {
updateChildNode(node, nodeLookup, parentLookup, { nodeOrigin });
}