| 1 |
/** |
| 2 |
* External dependencies |
| 3 |
*/ |
| 4 |
|
| 5 |
/** |
| 6 |
* WordPress dependencies |
| 7 |
*/ |
| 8 |
import apiFetch from "@wordpress/api-fetch"; |
| 9 |
|
| 10 |
/** |
| 11 |
* Internal dependencies |
| 12 |
*/ |
| 13 |
|
| 14 |
/** |
| 15 |
* Constants |
| 16 |
*/ |
| 17 |
|
| 18 |
/** |
| 19 |
* Initial state |
| 20 |
*/ |
| 21 |
const initialState = { |
| 22 |
missingBlocks: { |
| 23 |
blocks: {}, |
| 24 |
statuses: {}, |
| 25 |
}, |
| 26 |
}; |
| 27 |
|
| 28 |
export const missingBlocksSelectors = { |
| 29 |
getMissingBlock(state, filterValue) { |
| 30 |
return state.missingBlocks.blocks[filterValue] ?? false; |
| 31 |
}, |
| 32 |
getMissingBlockStatus(state, id) { |
| 33 |
return state.missingBlocks.statuses[id] ?? false; |
| 34 |
}, |
| 35 |
}; |
| 36 |
|
| 37 |
export const missingBlocksActions = { |
| 38 |
setMissingBlockStatus(id) { |
| 39 |
return { |
| 40 |
type: "SET_MISSING_BLOCK_STATUS", |
| 41 |
payload: id, |
| 42 |
}; |
| 43 |
}, |
| 44 |
loadMissingBlock(filterValue) { |
| 45 |
return async ({ select, dispatch }) => { |
| 46 |
let missingBlock = select.getMissingBlock(filterValue); |
| 47 |
if (missingBlock === false) { |
| 48 |
const blocks = await apiFetch({ |
| 49 |
path: `wp/v2/block-directory/search?term=${filterValue}`, |
| 50 |
}); |
| 51 |
|
| 52 |
missingBlock = blocks[0] ?? {}; |
| 53 |
|
| 54 |
dispatch({ |
| 55 |
type: "SET_MISSING_BLOCK", |
| 56 |
payload: { |
| 57 |
[filterValue]: missingBlock, |
| 58 |
}, |
| 59 |
}); |
| 60 |
} |
| 61 |
|
| 62 |
return missingBlock; |
| 63 |
}; |
| 64 |
}, |
| 65 |
}; |
| 66 |
|
| 67 |
export const missingBlocksReducer = ( |
| 68 |
state = initialState.missingBlocks, |
| 69 |
action, |
| 70 |
) => { |
| 71 |
switch (action.type) { |
| 72 |
case "SET_MISSING_BLOCK": |
| 73 |
return { |
| 74 |
...state, |
| 75 |
blocks: { |
| 76 |
...state.missingBlocks, |
| 77 |
...action.payload, |
| 78 |
}, |
| 79 |
}; |
| 80 |
|
| 81 |
case "SET_MISSING_BLOCK_STATUS": |
| 82 |
return { |
| 83 |
...state, |
| 84 |
statuses: { |
| 85 |
...state.statuses, |
| 86 |
[action.payload]: true, |
| 87 |
}, |
| 88 |
}; |
| 89 |
} |
| 90 |
|
| 91 |
return state; |
| 92 |
}; |
| 93 |
|