import type { ItemProps, ResponseProps } from '@components/DesignPanel/types'; import apiFetch from '@wordpress/api-fetch'; type ActionType = { type: string; value: any; crud: string; }; type CrudType = 'upsert' | 'delete' | 'init'; export const newItems = (items: ItemProps[], action: ActionType) => { switch (action.crud) { case 'upsert': const upsertIndex = items.findIndex( (item) => item.id === action.value.id ); if (upsertIndex === -1) { items.push(action.value); } else { items[upsertIndex] = action.value; } break; case 'delete': const deleteIndex = items.findIndex( (item) => item.id === action.value.id ); if (deleteIndex !== -1) { items.splice(deleteIndex, 1); } break; case 'init': items = action.value; break; case 'toggle_default': items = items.map((item) => { if (item.id === action.value.id) { item.is_default = action.value.is_default; } else if (item.blockname === action.value.blockname) { item.is_default = false; } return item; }); break; default: console.warn(`Unknown action type: ${action.crud}`); break; } return items; }; export const hydrateItem = (values: any, crud: CrudType) => { return { type: 'HYDRATE', value: values, crud: crud, }; }; export const getItems = async (handle: string) => { const response = (await apiFetch({ path: `/blockbite/v1/items/get/?handle=${handle}`, })) as ResponseProps; if (response.status === 200) { return response.data; } }; export const getItemByHandle = async (handle: string) => { const response = (await apiFetch({ path: `/blockbite/v1/items/get-item/?handle=${handle}`, })) as ResponseProps; if (response.status === 200) { return response.data; } }; export const getItemsByHandles = async (handles: string[]) => { const stringifiedHandles = handles.join(','); const response = (await apiFetch({ path: `/blockbite/v1/items/get-item/?handles=${stringifiedHandles}`, })) as ResponseProps; if (response.status === 200) { return response.data; } }; export const upsertItem = (item: ItemProps) => { return async ({ dispatch }: any) => { const response = (await apiFetch({ path: `/blockbite/v1/items/upsert`, method: 'POST', data: item, })) as ResponseProps; if (response.status === 200) { dispatch.hydrateItem(response.data, 'upsert'); } }; }; export const deleteItem = (item: ItemProps) => { return async ({ dispatch }: any) => { const response = (await apiFetch({ path: `/blockbite/v1/items/delete`, method: 'POST', data: item, })) as ResponseProps; if (response.status === 200) { dispatch.hydrateItem(item, 'delete'); } }; }; export const toggleDefaultItem = (item: ItemProps) => { return async ({ dispatch }: any) => { // put new correct state in post object item.is_default = !item.is_default; const response = (await apiFetch({ path: `/blockbite/v1/items/toggle-default`, method: 'POST', data: item, })) as ResponseProps; if (response.status === 200) { dispatch.hydrateItem(item, 'toggle_default'); } }; };