MCPcopy
hub / github.com/puckeditor/puck / insertComponent

Function insertComponent

packages/core/lib/insert-component.ts:9–65  ·  view source on GitHub ↗
(
  componentType: string,
  zone: string,
  index: number,
  appStore: ReturnType<typeof useAppStoreApi>
)

Source from the content-addressed store, hash-verified

7
8// Makes testing easier without mocks
9export const insertComponent = async (
10 componentType: string,
11 zone: string,
12 index: number,
13 appStore: ReturnType<typeof useAppStoreApi>
14) => {
15 const { getState } = appStore;
16
17 // Reuse newData so ID retains parity between dispatch and resolver
18 const id = generateId(componentType);
19
20 const insertActionData: InsertAction = {
21 type: "insert",
22 componentType,
23 destinationIndex: index,
24 destinationZone: zone,
25 id,
26 };
27
28 const stateBefore = getState().state;
29 const insertedState = insertAction(stateBefore, insertActionData, getState());
30
31 // Dispatch the insert, immediately
32 const dispatch = getState().dispatch;
33 dispatch({
34 ...insertActionData, // Dispatch insert rather set, as user's may rely on this via onAction
35
36 // We must always record history here so the insert is added to user history
37 // If the user has defined a resolveData method, they will end up with 2 history
38 // entries on insert - one for the initial insert, and one when the data resolves
39 recordHistory: true,
40 });
41
42 const itemSelector = { index, zone };
43
44 // Select the item, immediately
45 dispatch({ type: "setUi", ui: { itemSelector } });
46
47 const itemData = getItem(itemSelector, insertedState);
48 if (!itemData) return;
49
50 // Run any resolvers
51 const resolveComponentData = getState().resolveComponentData;
52 const resolved = await resolveComponentData(itemData, "insert");
53 if (!resolved.didChange) return;
54
55 // Use latest position, in case it has moved
56 const latestItemSelector = getSelectorForId(getState().state, id);
57 if (!latestItemSelector) return;
58
59 dispatch({
60 type: "replace",
61 destinationZone: latestItemSelector.zone,
62 destinationIndex: latestItemSelector.index,
63 data: resolved.node,
64 });
65};

Callers 2

onAnimationEndFunction · 0.90

Calls 5

generateIdFunction · 0.90
insertActionFunction · 0.90
getItemFunction · 0.90
getSelectorForIdFunction · 0.90
resolveComponentDataFunction · 0.85

Tested by

no test coverage detected