Skip to content

Commit

Permalink
refactor: don't trigger resolveFields multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisvxd committed Feb 21, 2025
1 parent f2523a5 commit 506fdf3
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 46 deletions.
9 changes: 6 additions & 3 deletions packages/core/lib/use-resolved-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,11 @@ export const useResolvedFields = () => {
useEffect(() => {
resolveFields(true);

return useNodeStore.subscribe(() => {
resolveFields();
});
return useNodeStore.subscribe(
(s) => s.nodes[id || "root"],
() => {
resolveFields();
}
);
}, [id]);
};
89 changes: 46 additions & 43 deletions packages/core/stores/node-store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { create } from "zustand";
import { ComponentData } from "../types";
import deepEqual from "fast-deep-equal";
import { subscribeWithSelector } from "zustand/middleware";

const partialDeepEqual = (
newItem: Record<string, any>,
Expand Down Expand Up @@ -35,61 +36,63 @@ type NodeStore = {
unregisterNode: (id: string, node?: Partial<PuckNode>) => void;
};

export const useNodeStore = create<NodeStore>((set) => ({
nodes: {},
registerNode: (id: string, node: Partial<PuckNode>) => {
set((s) => {
// Only update node if it changes
if (s.nodes[id] && partialDeepEqual(node, s.nodes[id])) {
return s;
}

const emptyNode: PuckNode = {
id,
methods: { sync: () => null },
data: { props: { id }, type: "unknown" },
parentId: "",
zone: "",
path: [],
element: null,
index: -1,
};
export const useNodeStore = create<NodeStore>()(
subscribeWithSelector((set) => ({
nodes: {},
registerNode: (id: string, node: Partial<PuckNode>) => {
set((s) => {
// Only update node if it changes
if (s.nodes[id] && partialDeepEqual(node, s.nodes[id])) {
return s;
}

const existingNode: PuckNode | undefined = s.nodes[id];
const emptyNode: PuckNode = {
id,
methods: { sync: () => null },
data: { props: { id }, type: "unknown" },
parentId: "",
zone: "",
path: [],
element: null,
index: -1,
};

return {
...s,
nodes: {
...s.nodes,
[id]: {
...emptyNode,
...existingNode,
...node,
id,
},
},
};
});
},
unregisterNode: (id: string, node?: Partial<PuckNode>) => {
set((s) => {
const existingNode: PuckNode | undefined = s.nodes[id];
const existingNode: PuckNode | undefined = s.nodes[id];

if (existingNode) {
return {
...s,
nodes: {
...s.nodes,
[id]: {
...emptyNode,
...existingNode,
...node,
id,
},
},
};
}
});
},
unregisterNode: (id: string, node?: Partial<PuckNode>) => {
set((s) => {
const existingNode: PuckNode | undefined = s.nodes[id];

return s;
});
},
}));
if (existingNode) {
return {
...s,
nodes: {
...s.nodes,
[id]: {
...existingNode,
...node,
id,
},
},
};
}

return s;
});
},
}))
);

0 comments on commit 506fdf3

Please sign in to comment.