@payloadcms/plugin-import-export
Version:
Import-Export plugin for Payload
175 lines (174 loc) • 7.13 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 { buildDisabledFieldRegex } from '../../utilities/buildDisabledFieldRegex.js';
import './index.scss';
import { useImportExport } from '../ImportExportProvider/index.js';
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 disabledFieldRegexes = React.useMemo(()=>{
const disabledFieldPaths = collectionConfig?.admin?.custom?.['plugin-import-export']?.disabledFields ?? [];
return disabledFieldPaths.map(buildDisabledFieldRegex);
}, [
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,
format,
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) && !disabledFieldRegexes.some((disabledRegex)=>disabledRegex.test(key)));
}) : allKeys.filter((key)=>!defaultMetaFields.includes(key) && !disabledFieldRegexes.some((regex)=>regex.test(key)));
const fieldKeys = Array.isArray(fields) && fields.length > 0 ? selectedKeys // strictly use selected fields only
: [
...selectedKeys,
...defaultMetaFields.filter((key)=>allKeys.includes(key) && !selectedKeys.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,
disabledFieldRegexes,
draft,
fields,
format,
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