105 lines
2.1 KiB
TypeScript
105 lines
2.1 KiB
TypeScript
|
import { IBlockData } from "@schlechtenburg/core";
|
||
|
|
||
|
export interface IPage {
|
||
|
id?: string|null;
|
||
|
attributes?: {
|
||
|
title?: string;
|
||
|
block?: IBlockData<any>|null;
|
||
|
slug?: string;
|
||
|
parent?: {
|
||
|
data?: {
|
||
|
id?: string|null;
|
||
|
};
|
||
|
};
|
||
|
};
|
||
|
}
|
||
|
|
||
|
export const usePages = () => {
|
||
|
const pages = useState<IPage[]|[]>('pages', () => []);
|
||
|
|
||
|
const getPage = (id:string) => pages.value.find(p => p.id === id);
|
||
|
|
||
|
const setPages = (newPages: IPage[] = []) => {
|
||
|
pages.value = newPages;
|
||
|
};
|
||
|
|
||
|
const updatePage = (page: Partial<IPage>) => {
|
||
|
const existing = pages.value.find(p => p.id === page.id);
|
||
|
if (!existing) {
|
||
|
console.warn('Could not update page because it was not found in the store', page);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
setPages([
|
||
|
...pages.value.filter(p => p.id !== page.id),
|
||
|
{
|
||
|
id: existing.id,
|
||
|
attributes: {
|
||
|
...existing.attributes,
|
||
|
...page.attributes,
|
||
|
},
|
||
|
},
|
||
|
]);
|
||
|
};
|
||
|
|
||
|
const removePage = (id: string) => {
|
||
|
setPages(pages.value.filter(p => p.id !== id));
|
||
|
};
|
||
|
|
||
|
const insertPage = (page: IPage) => {
|
||
|
setPages([
|
||
|
...pages.value,
|
||
|
page,
|
||
|
]);
|
||
|
};
|
||
|
|
||
|
const fetchPages = async () => {
|
||
|
const { data, error } = await useAsyncGql('pages');
|
||
|
setPages(data.value?.pages?.data as IPage[]);
|
||
|
}
|
||
|
|
||
|
return {
|
||
|
pages,
|
||
|
setPages,
|
||
|
getPage,
|
||
|
|
||
|
fetchPages,
|
||
|
|
||
|
insertPage,
|
||
|
updatePage,
|
||
|
removePage,
|
||
|
};
|
||
|
};
|
||
|
|
||
|
export const useCurrentPage = () => {
|
||
|
const { pages, insertPage } = usePages();
|
||
|
|
||
|
const currentPageId = useState<string|null>('currentPageId', () => null);
|
||
|
|
||
|
const setCurrentPage = (newPage: IPage|null) => {
|
||
|
if (!newPage || !newPage.id) {
|
||
|
currentPageId.value = null;
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
if (!pages.value.find(p => p.id === newPage.id)) {
|
||
|
insertPage(newPage);
|
||
|
}
|
||
|
|
||
|
currentPageId.value = newPage.id;
|
||
|
};
|
||
|
|
||
|
const setCurrentPageId = (newPageId: string|null) => {
|
||
|
currentPageId.value = newPageId;
|
||
|
};
|
||
|
|
||
|
const currentPage = computed(() => pages.value.find(p => p.id === currentPageId.value));
|
||
|
|
||
|
return {
|
||
|
currentPage,
|
||
|
setCurrentPage,
|
||
|
currentPageId,
|
||
|
setCurrentPageId,
|
||
|
};
|
||
|
};
|