mirror of
https://github.com/foomo/contentfultree.git
synced 2025-10-16 12:25:41 +00:00
77 lines
1.9 KiB
TypeScript
77 lines
1.9 KiB
TypeScript
import { type EntryProps, type KeyValueMap } from 'contentful-management';
|
|
import { type ContentTreeNodeProps } from './ContentTreeNode';
|
|
|
|
export const emptyNodeProps = (): ContentTreeNodeProps => {
|
|
return { id: '', name: '', expand: false, parentId: '' };
|
|
};
|
|
|
|
const cfEntryHasChildren = (
|
|
entry: EntryProps<KeyValueMap>,
|
|
nodeContentTypes: string[],
|
|
locales: string[]
|
|
): boolean => {
|
|
for (const nodeContentType of nodeContentTypes) {
|
|
for (const locale of locales) {
|
|
if (entry.fields[nodeContentType]?.[locale]) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
};
|
|
|
|
const cfEntryPublishingStatus = (entry: EntryProps<KeyValueMap>): string => {
|
|
if (!entry.sys.publishedVersion) {
|
|
return 'draft';
|
|
}
|
|
if (entry.sys.version - entry.sys.publishedVersion === 1) {
|
|
return 'published';
|
|
}
|
|
return 'changed';
|
|
};
|
|
|
|
export const cfEntriesToNodes = (
|
|
entries: Array<EntryProps<KeyValueMap>>,
|
|
titleFields: string[],
|
|
stLocale: string,
|
|
locales: string[],
|
|
nodeContentTypes: string[],
|
|
iconRegistry?: Record<string, string>,
|
|
parentId?: string
|
|
): ContentTreeNodeProps[] => {
|
|
if (entries.length === 0) {
|
|
return [];
|
|
}
|
|
const nodeArray: ContentTreeNodeProps[] = [];
|
|
entries.forEach((entry) => {
|
|
if (!entry) {
|
|
return;
|
|
}
|
|
let name = '';
|
|
for (const titleField of titleFields) {
|
|
if (entry.fields[titleField]?.[stLocale]) {
|
|
name = entry.fields[titleField][stLocale];
|
|
break;
|
|
}
|
|
}
|
|
if (name === '') {
|
|
name = entry.sys.id;
|
|
}
|
|
const node: ContentTreeNodeProps = {
|
|
id: entry.sys.id,
|
|
name,
|
|
contentType: entry.sys.contentType.sys.id,
|
|
icon:
|
|
iconRegistry != null ? iconRegistry[entry.sys.contentType.sys.id] : '',
|
|
expand: !!parentId,
|
|
parentId,
|
|
hasChildNodes: cfEntryHasChildren(entry, nodeContentTypes, locales),
|
|
publishingStatus: cfEntryPublishingStatus(entry),
|
|
updatedAt: entry.sys.updatedAt,
|
|
publishedAt: entry.sys.publishedAt,
|
|
};
|
|
nodeArray.push(node);
|
|
});
|
|
return nodeArray;
|
|
};
|