payloadcms-import-export-plugin
Version:
A comprehensive Payload CMS plugin that enables seamless import and export of collection data with support for CSV and JSON formats, featuring advanced field mapping, duplicate handling, and batch processing capabilities.
171 lines (170 loc) • 6.83 kB
JavaScript
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { getTranslation } from '@payloadcms/translations';
import { CodeEditorLazy, Table, Translation, useConfig, useField, useTranslation } from '@payloadcms/ui';
import React from 'react';
import { useImportExport } from '../ImportExportProvider/index.js';
import './index.scss';
const baseClass = 'preview';
export const Preview = ()=>{
const { collection } = useImportExport();
const { config } = useConfig();
const { value: where } = useField({
path: 'where'
});
const { value: limit } = useField({
path: 'limit'
});
const { value: fields } = useField({
path: 'fields'
});
const { value: sort } = useField({
path: 'sort'
});
const { value: draft } = useField({
path: 'drafts'
});
const { value: locale } = useField({
path: 'locale'
});
const { value: format } = useField({
path: 'format'
});
const [dataToRender, setDataToRender] = React.useState([]);
const [resultCount, setResultCount] = React.useState('');
const [columns, setColumns] = React.useState([]);
const { i18n, t } = useTranslation();
const collectionSlug = typeof collection === 'string' && collection;
const collectionConfig = config.collections.find((collection)=>collection.slug === collectionSlug);
const disabledFieldsUnderscored = React.useMemo(()=>{
return collectionConfig?.admin?.custom?.['plugin-import-export']?.disabledFields?.map((f)=>f.replace(/\./g, '_')) ?? [];
}, [
collectionConfig
]);
const isCSV = format === 'csv';
React.useEffect(()=>{
const fetchData = async ()=>{
if (!collectionSlug || !collectionConfig) {
return;
}
try {
const res = await fetch('/api/preview-data', {
body: JSON.stringify({
collectionSlug,
draft,
fields,
limit,
locale,
sort,
where
}),
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
if (!res.ok) {
return;
}
const { docs, totalDocs } = await res.json();
setResultCount(limit && limit < totalDocs ? limit : totalDocs);
const allKeys = Array.from(new Set(docs.flatMap((doc)=>Object.keys(doc))));
const defaultMetaFields = [
'createdAt',
'updatedAt',
'_status',
'id'
];
// Match CSV column ordering by building keys based on fields and regex
const fieldToRegex = (field)=>{
const parts = field.split('.').map((part)=>`${part}(?:_\\d+)?`);
return new RegExp(`^${parts.join('_')}`);
};
// Construct final list of field keys to match field order + meta order
const selectedKeys = Array.isArray(fields) && fields.length > 0 ? fields.flatMap((field)=>{
const regex = fieldToRegex(field);
return allKeys.filter((key)=>regex.test(key));
}) : allKeys.filter((key)=>!defaultMetaFields.includes(key) && !disabledFieldsUnderscored.includes(key));
const fieldKeys = Array.isArray(fields) && fields.length > 0 ? selectedKeys // strictly only what was selected
: [
...selectedKeys,
...defaultMetaFields.filter((key)=>allKeys.includes(key))
];
// Build columns based on flattened keys
const newColumns = fieldKeys.map((key)=>({
accessor: key,
active: true,
field: {
name: key
},
Heading: getTranslation(key, i18n),
renderedCells: docs.map((doc)=>{
const val = doc[key];
if (val === undefined || val === null) {
return null;
}
// Avoid ESLint warning by type-checking before calling String()
if (typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') {
return String(val);
}
if (Array.isArray(val)) {
return val.map(String).join(', ');
}
return JSON.stringify(val);
})
}));
setColumns(newColumns);
setDataToRender(docs);
} catch (error) {
console.error('Error fetching preview data:', error);
}
};
void fetchData();
}, [
collectionConfig,
collectionSlug,
disabledFieldsUnderscored,
draft,
fields,
i18n,
limit,
locale,
sort,
where
]);
return /*#__PURE__*/ _jsxs("div", {
className: baseClass,
children: [
/*#__PURE__*/ _jsxs("div", {
className: `${baseClass}__header`,
children: [
/*#__PURE__*/ _jsx("h3", {
children: /*#__PURE__*/ _jsx(Translation, {
i18nKey: "version:preview",
t: t
})
}),
resultCount && /*#__PURE__*/ _jsx(Translation, {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
i18nKey: "plugin-import-export:totalDocumentsCount",
t: t,
variables: {
count: resultCount
}
})
]
}),
dataToRender && (isCSV ? /*#__PURE__*/ _jsx(Table, {
columns: columns,
data: dataToRender
}) : /*#__PURE__*/ _jsx(CodeEditorLazy, {
language: "json",
readOnly: true,
value: JSON.stringify(dataToRender, null, 2)
}))
]
});
};
//# sourceMappingURL=index.js.map