@websolutespa/payload-plugin-bowl
Version:
Bowl PayloadCms plugin of the BOM Repository
1,475 lines (1,456 loc) • 292 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/components/CustomEditModal/CustomEditModal.tsx
var CustomEditModal_exports = {};
__export(CustomEditModal_exports, {
CustomEditModal: () => CustomEditModal,
default: () => CustomEditModal_default
});
var import_modal2, import_components3, import_hooks, import_utilities3, import_IDLabel, import_field_types, import_useRelatedCollections, import_RenderCustomComponent, import_SearchParams, import_Default, import_formatFields, import_utilities4, import_qs, import_react2, import_react_i18next2, import_react_toastify, import_jsx_runtime4, baseClass, CustomEditModal, CustomEditModal_default;
var init_CustomEditModal = __esm({
"src/components/CustomEditModal/CustomEditModal.tsx"() {
import_modal2 = require("@faceless-ui/modal");
import_components3 = require("payload/components");
import_hooks = require("payload/components/hooks");
import_utilities3 = require("payload/components/utilities");
import_IDLabel = __toESM(require("payload/dist/admin/components/elements/IDLabel"));
import_field_types = require("payload/dist/admin/components/forms/field-types");
import_useRelatedCollections = require("payload/dist/admin/components/forms/field-types/Relationship/AddNew/useRelatedCollections");
import_RenderCustomComponent = __toESM(require("payload/dist/admin/components/utilities/RenderCustomComponent"));
import_SearchParams = require("payload/dist/admin/components/utilities/SearchParams");
import_Default = __toESM(require("payload/dist/admin/components/views/collections/Edit/Default"));
import_formatFields = __toESM(require("payload/dist/admin/components/views/collections/Edit/formatFields"));
import_utilities4 = require("payload/utilities");
import_qs = __toESM(require("qs"));
import_react2 = require("react");
import_react_i18next2 = require("react-i18next");
import_react_toastify = require("react-toastify");
import_jsx_runtime4 = require("react/jsx-runtime");
baseClass = "collection-edit";
CustomEditModal = /* @__PURE__ */ __name(({
collectionSlug,
customHeader,
drawerSlug,
onSave,
...props
}) => {
const {
routes: { api },
serverURL
} = (0, import_utilities3.useConfig)();
const { closeModal, modalState, toggleModal } = (0, import_modal2.useModal)();
const { code: locale } = (0, import_utilities3.useLocale)();
const { user } = (0, import_utilities3.useAuth)();
const [internalState, setInternalState] = (0, import_react2.useState)();
const { i18n, t } = (0, import_react_i18next2.useTranslation)(["fields", "general"]);
const hasInitializedState = (0, import_react2.useRef)(false);
const [isOpen, setIsOpen] = (0, import_react2.useState)(false);
const [relatedCollection] = (0, import_useRelatedCollections.useRelatedCollections)(collectionSlug);
const collectionConfig = (0, import_react2.useMemo)(() => {
const filter = props.filter || ((fields2) => fields2);
return { ...relatedCollection, fields: filter(relatedCollection.fields) };
}, [relatedCollection, props.filter]);
const config = (0, import_utilities3.useConfig)();
const { admin: { components: { views: { Edit } = {} } = {} } = {} } = collectionConfig;
const { id, docPermissions, getDocPreferences } = (0, import_utilities3.useDocumentInfo)();
const [fields, setFields] = (0, import_react2.useState)(() => (0, import_formatFields.default)(collectionConfig, true));
const initialID = (0, import_react2.useRef)(id);
const [{ data, isError, isLoading: isLoadingDocument }] = (0, import_hooks.usePayloadAPI)(
initialID.current ? `${serverURL}${api}/${collectionSlug}/${initialID.current}` : null,
{ initialParams: { depth: 0, draft: "true", "fallback-locale": "null" } }
);
const CustomEditView = typeof Edit === "function" ? Edit : void 0;
(0, import_react2.useEffect)(() => {
setFields((0, import_formatFields.default)(collectionConfig, true));
}, [collectionSlug, collectionConfig]);
(0, import_react2.useEffect)(() => {
if (isLoadingDocument || hasInitializedState.current) {
return;
}
const awaitInitialState = /* @__PURE__ */ __name(async () => {
const preferences = await getDocPreferences();
const state = await (0, import_utilities3.buildStateFromSchema)({
id,
config,
data,
fieldSchema: fields,
locale,
operation: id ? "update" : "create",
preferences,
t,
user
});
setInternalState(state);
}, "awaitInitialState");
awaitInitialState();
hasInitializedState.current = true;
}, [data, fields, id, user, locale, isLoadingDocument, t, getDocPreferences, config]);
(0, import_react2.useEffect)(() => {
setIsOpen(Boolean(modalState[drawerSlug]?.isOpen));
}, [modalState, drawerSlug]);
(0, import_react2.useEffect)(() => {
if (isOpen && !isLoadingDocument && isError) {
closeModal(drawerSlug);
import_react_toastify.toast.error(data.errors?.[0].message || t("error:unspecific"));
}
}, [isError, t, isOpen, data, drawerSlug, closeModal, isLoadingDocument]);
const params = (0, import_SearchParams.useSearchParams)();
if (isError) {
return null;
}
const isEditing = Boolean(id);
const apiURL = id ? `${serverURL}${api}/${collectionSlug}/${id}?locale=${locale}` : null;
const formattedParams = import_qs.default.stringify(params);
const action = `${serverURL}${api}/${collectionSlug}${isEditing ? `/${id}` : ""}?${formattedParams}`;
const hasSavePermission = isEditing && docPermissions?.update?.permission || !isEditing && docPermissions?.create?.permission;
const isLoading = !internalState || !docPermissions || isLoadingDocument;
return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
import_RenderCustomComponent.default,
{
CustomComponent: CustomEditView,
DefaultComponent: import_Default.default,
componentProps: {
id,
action,
apiURL,
collection: collectionConfig,
customHeader: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: `${baseClass}__header`, children: [
/* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: `${baseClass}__header-content`, children: [
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h2", { className: `${baseClass}__header-text`, children: !customHeader ? t(!id ? "fields:addNewLabel" : "general:editLabel", {
label: (0, import_utilities4.getTranslation)(collectionConfig.labels.singular, i18n)
}) : customHeader }),
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
import_components3.Button,
{
"aria-label": t("general:close"),
buttonStyle: "none",
className: `${baseClass}__header-close`,
onClick: () => toggleModal(drawerSlug),
children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_components3.X, {})
}
)
] }),
id && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_IDLabel.default, { id: id.toString() })
] }),
data,
disableActions: true,
disableLeaveWithoutSaving: true,
disableRoutes: true,
fieldTypes: import_field_types.fieldTypes,
hasSavePermission,
internalState,
isEditing,
isLoading,
me: true,
onSave,
permissions: docPermissions
}
}
);
}, "CustomEditModal");
CustomEditModal_default = CustomEditModal;
}
});
// src/index.ts
var src_exports = {};
__export(src_exports, {
ActionDefault: () => ActionDefault,
AddressDefault: () => AddressDefault,
BlockDefaults: () => BlockDefaults,
CategoryDefaults: () => CategoryDefaults,
CategoryMenu: () => CategoryMenu,
CategoryTree: () => CategoryTree,
CheckboxDefaults: () => CheckboxDefaults,
CollectionDefault: () => CollectionDefault,
ColorCell: () => ColorCell,
ColorConfig: () => ColorConfig,
ColorField: () => ColorField,
ComponentsDefaults: () => ComponentsDefaults,
CustomEditModal: () => CustomEditModal,
DataTree: () => DataTree,
DataTreeDragItem: () => DataTreeDragItem,
DataTreeItem: () => DataTreeItem,
DataTreeItemLi: () => DataTreeItemLi,
DataTreeProvider: () => DataTreeProvider,
DataTreeRenameItem: () => DataTreeRenameItem,
DateDefaults: () => DateDefaults,
DebugField: () => DebugField,
DecoratedList: () => DecoratedList,
EndUserDefault: () => EndUserDefault,
GlobalDefault: () => GlobalDefault,
Icon: () => Icon,
ImportExportList: () => ImportExportList,
ImportExportRedirectList: () => ImportExportRedirectList,
ImportLogInvalidTypes: () => ImportLogInvalidTypes,
ImportLogType: () => ImportLogType,
ImportMode: () => ImportMode,
InMemoryCache: () => InMemoryCache,
LeaveModal: () => LeaveModal,
LeaveWithoutSavingModal: () => LeaveWithoutSavingModal,
LocalizedDescription: () => LocalizedDescription,
Logo: () => Logo,
MAX_INT: () => MAX_INT,
MarketDefaults: () => MarketDefaults,
MediaDefaults: () => MediaDefaults,
MediasDefaults: () => MediasDefaults,
MenuItem: () => MenuItem,
OrderDefaults: () => OrderDefaults,
PageDefault: () => PageDefault,
Publish: () => Publish,
ROOT_ITEM: () => ROOT_ITEM,
RelatedDefaults: () => RelatedDefaults,
RichTextDefaults: () => RichTextDefaults,
Save: () => Save,
SaveDraft: () => SaveDraft,
SelectDefaults: () => SelectDefaults,
StaticCollectionDefault: () => StaticCollectionDefault,
TemplateDefaults: () => TemplateDefaults,
TenantsDefault: () => TenantsDefault,
TextDefaults: () => TextDefaults,
UIStaticCell: () => UIStaticCell,
UIStaticField: () => UIStaticField,
UserDefault: () => UserDefault,
UserRolesDefaults: () => UserRolesDefaults,
afterCategoryChangeHook: () => afterCategoryChangeHook,
afterCategoryDeleteHook: () => afterCategoryDeleteHook,
afterChangeActionHook: () => afterChangeActionHook,
afterCollectionReadHook: () => afterCollectionReadHook,
afterMenuReadHook: () => afterMenuReadHook,
afterPageChangeHook: () => afterPageChangeHook,
afterPageDeleteHook: () => afterPageDeleteHook,
afterPageOperationHook: () => afterPageOperationHook,
afterPageReadHook: () => afterPageReadHook,
afterReadItem: () => afterReadItem,
afterReadItems: () => afterReadItems,
afterStaticReadHook: () => afterStaticReadHook,
appearanceOptions: () => appearanceOptions,
beforeChangeActionHook: () => beforeChangeActionHook,
beforeDuplicateCollectionHook: () => beforeDuplicateCollectionHook,
beforeValidate: () => beforeValidate,
beforeValidateActionHook: () => beforeValidateActionHook,
bowl: () => bowl,
collectionBulkPatch: () => collectionBulkPatch,
collectionDetailGet: () => collectionDetailGet,
collectionExportGet: () => collectionExportGet,
collectionImportPost: () => collectionImportPost,
collectionIndexGet: () => collectionIndexGet,
collectionUpdatePatch: () => collectionUpdatePatch,
debugField: () => debugField,
decorateCategories_: () => decorateCategories_,
decorateCategory_: () => decorateCategory_,
decorateHref_: () => decorateHref_,
decorateHrefs_: () => decorateHrefs_,
decorateMenuCategory_: () => decorateMenuCategory_,
decorateMenuGroup_: () => decorateMenuGroup_,
decorateMenuItem_: () => decorateMenuItem_,
decorateMenuLink_: () => decorateMenuLink_,
decorateMenuPage_: () => decorateMenuPage_,
decorateMenuRoute_: () => decorateMenuRoute_,
decorateMenu_: () => decorateMenu_,
decorateNavItem_: () => decorateNavItem_,
decorateNav_: () => decorateNav_,
decorateNavs_: () => decorateNavs_,
decorateSchema_: () => decorateSchema_,
decorateSchemas_: () => decorateSchemas_,
decrypt: () => decrypt,
decryptField: () => decryptField,
default: () => src_default,
defaultGroup: () => defaultGroup,
defaultLocale: () => defaultLocale,
defaultLocales: () => defaultLocales,
defaultMarket: () => defaultMarket,
defaultSlug: () => defaultSlug,
encrypt: () => encrypt,
encryptData: () => encryptData,
encryptField: () => encryptField,
endUserExistPost: () => endUserExistPost,
endUserForgotPost: () => endUserForgotPost,
endUserPasswordPost: () => endUserPasswordPost,
endUserResetPost: () => endUserResetPost,
filterRoutes: () => filterRoutes,
findCollection: () => findCollection,
getApiUrl: () => getApiUrl,
getCollectionItem: () => getCollectionItem,
getCollectionItems: () => getCollectionItems,
getEachMarketLocale: () => getEachMarketLocale,
getGlobalItems: () => getGlobalItems,
getLivePreviewURL: () => getLivePreviewURL,
getLocale: () => getLocale,
getNewCategoriesFromChanges: () => getNewCategoriesFromChanges,
getNumericParam: () => getNumericParam,
getObjectParam: () => getObjectParam,
getPages: () => getPages,
getPagination: () => getPagination,
getPreviewURL: () => getPreviewURL,
getPublicURL: () => getPublicURL,
getRoute: () => getRoute,
getRouteByCategoryAndLocale: () => getRouteByCategoryAndLocale,
getRouteByItemAndLocale: () => getRouteByItemAndLocale,
getRoutes: () => getRoutes,
getSearchUrl: () => getSearchUrl,
getStaticLoader: () => getStaticLoader,
getStringParam: () => getStringParam,
getSubRequest: () => getSubRequest,
getTranslation: () => getTranslation4,
getTranslations: () => getTranslations,
getTreeItemClassName: () => getTreeItemClassName,
hasMarket: () => hasMarket2,
hasRole: () => hasRole,
importExportListWithParser: () => importExportListWithParser,
internalSlugs: () => internalSlugs,
isAdmin: () => isAdmin,
isAdminOrOwn: () => isAdminOrOwn,
isAdminOrSelf: () => isAdminOrSelf,
isMixerRequest: () => isMixerRequest,
isOwn: () => isOwn,
isPageRole: () => isPageRole,
isRelation: () => isRelation,
isRole: () => isRole,
isSelf: () => isSelf,
isTenant: () => isTenant,
isUndecoratedNavItem: () => isUndecoratedNavItem,
keyWithRequest: () => keyWithRequest,
localeGet: () => localeGet,
localizeCollection: () => localizeCollection,
localizeItem: () => localizeItem,
log: () => log,
logMissingTranslations: () => logMissingTranslations,
menuDetailGet: () => menuDetailGet,
menuIndexGet: () => menuIndexGet,
mergeCollections: () => mergeCollections,
mergeFields: () => mergeFields,
mergeGlobals: () => mergeGlobals,
modalSlug: () => modalSlug,
optinGet: () => optinGet,
options: () => options,
optoutGet: () => optoutGet,
pageDetailGet: () => pageDetailGet,
pageIndexGet: () => pageIndexGet,
parseDepth: () => parseDepth,
redirectParser: () => redirectParser,
richTextAfterReadHook: () => richTextAfterReadHook,
roles: () => roles,
rolesEndUser: () => rolesEndUser,
rolesUser: () => rolesUser,
routeChangesPost: () => routeChangesPost,
routeGet: () => routeGet,
routePost: () => routePost,
routePostHandler: () => routePostHandler,
setMixerContext: () => setMixerContext,
slugToLabel: () => slugToLabel,
slugToLabels: () => slugToLabels,
sortByGroup: () => sortByGroup,
sortCollection: () => sortCollection,
staticCollectionLoaders: () => staticCollectionLoaders,
staticCollections: () => staticCollections,
staticDetailGet: () => staticDetailGet,
staticIndexGet: () => staticIndexGet,
storeGet: () => storeGet,
toBlock: () => toBlock,
toCollection: () => toCollection,
toField: () => toField,
toGlobal: () => toGlobal,
toTab: () => toTab,
translateBlock: () => translateBlock,
translateBlocks: () => translateBlocks,
translateCollection: () => translateCollection,
translateField: () => translateField,
translateFields: () => translateFields,
translateGlobal: () => translateGlobal,
translateTab: () => translateTab,
translateTabs: () => translateTabs,
webpack: () => webpack,
whereCollection: () => whereCollection,
withAbstract: () => withAbstract,
withAbstractRequired: () => withAbstractRequired,
withAction: () => withAction,
withAddress: () => withAddress,
withBlock: () => withBlock,
withCategory: () => withCategory,
withCategoryRequired: () => withCategoryRequired,
withCheckbox: () => withCheckbox,
withCheckboxRequired: () => withCheckboxRequired,
withCollection: () => withCollection,
withColor: () => withColor,
withColorRequired: () => withColorRequired,
withComponentBlock: () => withComponentBlock,
withComponents: () => withComponents,
withDate: () => withDate,
withDateRequired: () => withDateRequired,
withDescription: () => withDescription,
withDescriptionRequired: () => withDescriptionRequired,
withEndUser: () => withEndUser,
withGlobal: () => withGlobal,
withId: () => withId,
withIdRequired: () => withIdRequired,
withIsActive: () => withIsActive,
withIsActiveRequired: () => withIsActiveRequired,
withIsDefault: () => withIsDefault,
withIsDefaultRequired: () => withIsDefaultRequired,
withLink: () => withLink,
withLocalizedDescription: () => withLocalizedDescription,
withMarkets: () => withMarkets,
withMarketsRequired: () => withMarketsRequired,
withMedia: () => withMedia,
withMediaRequired: () => withMediaRequired,
withMedias: () => withMedias,
withMediasRequired: () => withMediasRequired,
withMenu: () => withMenu,
withName: () => withName,
withNameRequired: () => withNameRequired,
withOrder: () => withOrder,
withOrderRequired: () => withOrderRequired,
withPage: () => withPage,
withRelated: () => withRelated,
withRichText: () => withRichText,
withRichTextRequired: () => withRichTextRequired,
withRoles: () => withRoles,
withSelect: () => withSelect,
withSelectRequired: () => withSelectRequired,
withSlug: () => withSlug,
withSlugRequired: () => withSlugRequired,
withStaticCollection: () => withStaticCollection,
withTemplate: () => withTemplate,
withTemplateRequired: () => withTemplateRequired,
withTenants: () => withTenants,
withText: () => withText,
withTextRequired: () => withTextRequired,
withTitle: () => withTitle,
withTitleRequired: () => withTitleRequired,
withUIStatic: () => withUIStatic,
withUser: () => withUser
});
module.exports = __toCommonJS(src_exports);
// src/blocks/MenuItem.ts
var MenuItem = /* @__PURE__ */ __name((pages, customBlocks = [], depth = 0, maxDepth = 10) => {
const menuItem = {
type: "withBlock",
slug: `Level ${depth}`,
fields: [
// type
{
name: "type",
type: "select",
defaultValue: "category",
/*
admin: {
layout: 'horizontal',
},
*/
options: [
{
label: "Page",
value: "page"
},
{
label: "Category",
value: "category"
},
{
label: "Link",
value: "link"
},
{
label: "Group",
value: "group"
}
]
},
// tabs
{
type: "tabs",
tabs: [
// tab data
{
label: "Data",
fields: [
// category fields
{
type: "row",
fields: [
// category
{
type: "withCategory",
required: true,
admin: {
width: "50%",
condition: (_, siblingData) => siblingData?.type === "category"
}
},
// maxDepth
{
name: "maxDepth",
type: "number",
admin: {
width: "50%",
condition: (_, siblingData) => siblingData?.type === "category"
}
},
// strategy
{
name: "strategy",
type: "select",
defaultValue: "default",
admin: {
condition: (_, siblingData) => siblingData?.type === "category"
},
options: [
{
label: "Default",
value: "default"
},
{
label: "Exclude hidden categories",
value: "exclude-hidden"
}
]
}
],
admin: {
condition: (_, siblingData) => siblingData?.type === "category"
}
},
// page fields
{
type: "row",
fields: [
// page
{
name: "page",
type: "relationship",
relationTo: pages,
hasMany: false,
required: true,
maxDepth: 2,
admin: {
width: "50%",
condition: (_, siblingData) => siblingData?.type === "page"
}
}
],
admin: {
condition: (_, siblingData) => siblingData?.type === "page"
}
},
// title field
{
type: "withTitle",
required: true,
admin: {
condition: (_, siblingData) => siblingData?.type === "group" || siblingData?.type === "link"
}
},
// link fields
{
type: "row",
fields: [
// href
{
name: "href",
type: "text",
required: true,
localized: true,
admin: {
width: "50%",
condition: (_, siblingData) => siblingData?.type === "link"
}
},
// target
{
name: "target",
type: "text",
required: true,
defaultValue: "_blank",
admin: {
width: "50%",
condition: (_, siblingData) => siblingData?.type === "link"
}
}
],
admin: {
condition: (_, siblingData) => siblingData?.type === "link"
}
}
]
},
// markets
{
label: "Markets",
// description: 'Configure the list of available markets for this item. Leave empty for all markets.',
fields: [
// markets
{
type: "withMarkets"
}
]
},
// details
{
label: "Details",
fields: [
// title
{
type: "withText",
name: "customTitle",
localized: true,
admin: {
condition: (_, siblingData) => siblingData?.type === "category" || siblingData?.type === "page"
}
},
// abstract
{
type: "withAbstract"
},
// media
{
type: "withMedia"
},
// custom class
{
type: "withText",
name: "customClass"
},
// extra
{
type: "withText",
name: "extra",
localized: true
}
]
}
]
}
]
};
if (depth < maxDepth) {
depth++;
menuItem.fields.push({
name: "items",
label: "Items",
type: "blocks",
blocks: [MenuItem(pages, customBlocks, depth, maxDepth), ...customBlocks],
admin: {
condition: (_, siblingData) => siblingData?.type !== "category",
initCollapsed: true
}
});
}
return menuItem;
}, "MenuItem");
// src/blocks/withComponentBlock.ts
function withComponentBlock({ slug, fields = [], optionsFields = [] }) {
return {
type: "withBlock",
slug,
fields: [
{
type: "tabs",
tabs: [
{
label: "Content",
fields
},
{
label: "Options",
fields: [
{ type: "withAnchor" },
{ type: "withSeoWeight" },
...optionsFields
]
}
]
}
]
};
}
__name(withComponentBlock, "withComponentBlock");
// src/bowl.ts
var import_payload_utils46 = require("@websolutespa/payload-utils");
var path2 = __toESM(require("path"));
// src/collections/Address.ts
var Address = /* @__PURE__ */ __name((options2) => ({
type: "withAddress",
slug: options2.slug.address,
fields: []
}), "Address");
// src/components/Category/CategoryMenu.tsx
var import_bom_core = require("@websolutespa/bom-core");
var import_utilities = require("payload/components/utilities");
var import_react_router_dom = require("react-router-dom");
var import_jsx_runtime = require("react/jsx-runtime");
var CategoryMenu = /* @__PURE__ */ __name((props) => {
const { collection } = props;
const slug = collection.slug;
const { routes } = (0, import_utilities.useConfig)();
const match = (0, import_react_router_dom.useRouteMatch)();
const items = [
{
name: "List",
url: `${routes.admin}/collections/${slug}`
},
{
name: "Tree",
url: `${routes.admin}/collections/${slug}/tree`
}
];
const isActive = /* @__PURE__ */ __name((url) => {
return match.url === url;
}, "isActive");
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "tabs-field__tabs-wrap", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "tabs-field__tabs", children: items.map((item, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_react_router_dom.Link,
{
className: (0, import_bom_core.getClassNames)("tabs-field__tab-button", { "tabs-field__tab-button--active": isActive(item.url) }),
to: item.url,
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: item.name })
},
i
)) }) }) });
}, "CategoryMenu");
// src/components/Category/CategoryTree.tsx
var import_modal3 = require("@faceless-ui/modal");
var import_payload_utils2 = require("@websolutespa/payload-utils");
var import_components4 = require("payload/components");
var import_utilities5 = require("payload/components/utilities");
var import_Gutter = require("payload/dist/admin/components/elements/Gutter");
var import_ViewDescription = __toESM(require("payload/dist/admin/components/elements/ViewDescription"));
var import_Submit = __toESM(require("payload/dist/admin/components/forms/Submit"));
var import_DocumentInfo = require("payload/dist/admin/components/utilities/DocumentInfo");
var import_getTranslation = require("payload/dist/utilities/getTranslation");
var import_react3 = require("react");
var import_react_i18next3 = require("react-i18next");
var import_react_router_dom2 = require("react-router-dom");
var import_react_toastify2 = require("react-toastify");
// src/core/api/redirect.service.ts
var import_bom_core3 = require("@websolutespa/bom-core");
// src/translations.ts
var translations = {
en: {
group: {
content: "Content",
shop: "Shop",
nav: "Navigation",
actions: "Actions",
gdpr: "GDPR",
users: "Users",
config: "Configuration",
i18n: "I18N"
},
collection: {
singular: {
address: "Address",
category: "Category",
color: "Color",
country: "Country",
email_config: "Email configuration",
label: "Label",
language: "Language",
market: "Market",
media: "Media",
menu: "Menu",
page: "Page",
province: "Province",
redirect: "Redirect",
region: "Region",
template: "Template",
users: "User",
end_users: "End User",
legal_notice: "Legal notice",
consent_preference: "Consent preference",
i18n_continent: "Continent",
i18n_country_zone: "Country Zone",
i18n_country: "Country",
i18n_language: "Language",
i18n_municipality: "Municipality",
i18n_province: "Province",
i18n_region: "Region",
i18n_sub_continent: "Subcontinent",
"Level 0": "Level 0",
"Level 1": "Level 1",
"Level 2": "Level 2",
"Level 3": "Level 3",
"Level 4": "Level 4",
"Level 5": "Level 5",
"Level 6": "Level 6",
"Level 7": "Level 7",
"Level 8": "Level 8",
"Level 9": "Level 9",
"Level 10": "Level 10"
},
plural: {
address: "Addresses",
category: "Categories",
color: "Colors",
country: "Countries",
email_config: "Email configurations",
label: "Labels",
language: "Languages",
market: "Markets",
media: "Medias",
menu: "Menus",
page: "Pages",
province: "Provinces",
redirect: "Redirects",
region: "Regions",
template: "Templates",
users: "Users",
end_users: "End Users",
legal_notice: "Legal notices",
consent_preference: "Consent preferences",
i18n_continent: "Continents",
i18n_country_zone: "Country Zones",
i18n_country: "Countries",
i18n_language: "Languages",
i18n_municipality: "Municipalities",
i18n_province: "Provinces",
i18n_region: "Regions",
i18n_sub_continent: "Subcontinents",
"Level 0": "Levels 0",
"Level 1": "Levels 1",
"Level 2": "Levels 2",
"Level 3": "Levels 3",
"Level 4": "Levels 4",
"Level 5": "Levels 5",
"Level 6": "Levels 6",
"Level 7": "Levels 7",
"Level 8": "Levels 8",
"Level 9": "Levels 9",
"Level 10": "Levels 10"
}
},
global: {
locale: "Locales"
},
field: {
abstract: "Abstract",
action: "Action",
address: "Address",
alpha2Code: "Alpha2 Code",
alpha3Code: "Alpha3 Code",
alt: "Alt",
appearance: "Appearance",
bcc: "BCC",
blocks: "Blocks",
category_index: "Index of Category",
category: "Category",
cc: "CC",
city: "City",
code: "Code",
color: "Color",
companyName: "Company Name",
compatibleCollections: "Collections",
components: "Components",
consentPreference: "Consent Preference",
consentPreferences: "Consent Preferences",
consentRevoke: "Consent Revoke",
content: "Content",
continent: "Continent",
countries: "Countries",
country: "Country",
countryZone: "Country Zone",
customClass: "Custom Class",
date: "Date",
defaultLanguage: "Default Language",
description: "Description",
details: "Details",
email: "Email",
emailVerified: "Email Verified",
endUser: "End User",
englishName: "English Name",
extra: "Extra",
faxNumber: "Fax Number",
firstName: "First Name",
from: "From",
fromAddress: "From address",
hasCompatibleCollections: "Has Compatible Collections",
href: "Href",
id: "ID",
isActive: "Active",
isDefault: "Is Default",
isHidden: "Hidden",
items: "Items",
label: "Label",
language: "Language",
languages: "Languages",
lastName: "Last Name",
lat: "Latitude",
legalNotice: "Legal Notice",
link: "Link",
lng: "Longitude",
marketingEmail: "Marketing Email",
markets: "Markets",
maxDepth: "Max depth",
media: "Media",
medias: "Medias",
name: "Name",
nativeName: "Native Name",
newTab: "New Tab",
options: "Options",
order: "Order",
phoneNumber: "Phone Number",
position: "Position",
price: "Price",
province: "Province",
reference: "Reference",
region: "Region",
revoked: "Revoked",
revokedDate: "Revoked date",
roles: "Roles",
slug: "Slug",
status: "Status",
streetNumber: "Street Number",
subContinent: "Subcontinent",
subject: "Subject",
target: "Target",
template: "Template",
tenants: "Tenants",
text: "Text",
title: "Title",
to: "To",
type: "Type",
url: "Url",
useSplat: "Use Splat",
utmz: "Utmz",
websiteUrl: "Website Url",
zipCode: "ZipCode"
},
description: {
isDefaultPage: "Default documents inherit their slug from the parent category."
},
importExport: {
importCSV: "Import CSV",
exportCSV: "Export CSV",
modalTitle: "Import records",
dropTitle: "Drop the files here ...",
dropAbstract: "drop here a *.csv file, or click to select one",
parseError: "An error occurred parsing the csv",
clear: "Clear",
submit: "Submit",
importMode: "Import mode",
enableDataParsing: "Enable data parsing",
modeAppend: "Append",
modeReplace: "Replace",
modeUpdate: "Update",
records: "{0} records found in <i>{1}</i>",
errorRequired: "'{0}' required key missing",
errorOptional: "'{0}' optional key missing",
errorInvalid: "'{0}' invalid value found: ",
errorDuplicate: "'{0}' duplicate value found for unique field: ",
errorUnexpected: "'{0}' unexpected key found",
success: "Import successful.",
failure: "There was an error while importing data in '{0}'."
},
// override existing translation keys
general: {
// dashboard: 'Dashboard',
}
},
it: {
group: {
content: "Contenuti",
shop: "Shop",
nav: "Navigazione",
actions: "Azioni",
gdpr: "GDPR",
users: "Utenti",
config: "Configurazione",
i18n: "I18N"
},
collection: {
singular: {
address: "Indirizzo",
category: "Categoria",
color: "Colore",
country: "Nazione",
email_config: "Configurazione email",
label: "Etichetta",
language: "Lingua",
market: "Mercato",
media: "Media",
menu: "Menu",
page: "Pagina",
province: "Provincia",
redirect: "Reindirizzamento",
region: "Regione",
template: "Template",
users: "Utente",
end_users: "Utente sito",
legal_notice: "Informativa legale",
consent_preference: "Preferenza di consenso",
i18n_continent: "Continente",
i18n_country_zone: "Area Nazionale",
i18n_country: "Nazione",
i18n_language: "Lingua",
i18n_municipality: "Comune",
i18n_province: "Provincia",
i18n_region: "Regione",
i18n_sub_continent: "Subcontinente",
"Level 0": "Livello 0",
"Level 1": "Livello 1",
"Level 2": "Livello 2",
"Level 3": "Livello 3",
"Level 4": "Livello 4",
"Level 5": "Livello 5",
"Level 6": "Livello 6",
"Level 7": "Livello 7",
"Level 8": "Livello 8",
"Level 9": "Livello 9",
"Level 10": "Livello 10"
},
plural: {
address: "Indirizzi",
category: "Categorie",
color: "Colori",
country: "Nazioni",
email_config: "Configurazioni email",
label: "Etichette",
language: "Lingue",
login: "Login",
market: "Mercati",
media: "Media",
menu: "Menu",
page: "Pagine",
province: "Province",
redirect: "Reindirizzamenti",
region: "Regioni",
template: "Templates",
users: "Utenti",
end_users: "Utenti sito",
legal_notice: "Informative legali",
consent_preference: "Preferenze di consenso",
i18n_continent: "Continenti",
i18n_country_zone: "Aree Nazionali",
i18n_country: "Nazioni",
i18n_language: "Lingue",
i18n_municipality: "Comuni",
i18n_province: "Province",
i18n_region: "Regioni",
i18n_sub_continent: "Subcontinenti",
"Level 0": "Livelli 0",
"Level 1": "Livelli 1",
"Level 2": "Livelli 2",
"Level 3": "Livelli 3",
"Level 4": "Livelli 4",
"Level 5": "Livelli 5",
"Level 6": "Livelli 6",
"Level 7": "Livelli 7",
"Level 8": "Livelli 8",
"Level 9": "Livelli 9",
"Level 10": "Livelli 10"
}
},
global: {
locale: "Localizzazioni"
},
field: {
abstract: "Abstract",
action: "Azione",
address: "Indirizzo",
alpha2Code: "Codice Alpha2",
alpha3Code: "Codice Alpha3",
alt: "Testo Alternativo",
appearance: "Aspetto",
bcc: "CCN",
blocks: "Blocchi",
category_index: "Indice di Categoria",
category: "Categoria",
cc: "CC",
city: "Citt\xE0",
code: "Codice",
color: "Colore",
companyName: "Azienda",
compatibleCollections: "Collezioni",
components: "Componenti",
consentPreference: "Preferenza di consenso",
consentPreferences: "Preferenze di consenso",
consentRevoke: "Revoca consenso",
content: "Contenuto",
continent: "Continente",
countries: "Nazioni",
country: "Nazione",
countryZone: "Area Nazionale",
customClass: "Classe Custom",
date: "Data",
defaultLanguage: "Lingua di Default",
description: "Descrizione",
details: "Dettagli",
email: "Email",
emailVerified: "Email Verificata",
endUser: "Utente sito",
englishName: "Nome Inglese",
extra: "Extra",
faxNumber: "Numero di fax",
from: "Da",
fromAddress: "Indirizzo mittente",
hasCompatibleCollections: "Ha Collezioni Compatibili",
href: "Href",
id: "ID",
isActive: "Attivo",
isDefault: "Predefinito",
isHidden: "Nascosto",
items: "Elementi",
label: "Etichetta",
language: "Lingua",
languages: "Lingue",
lat: "Latitudine",
legalNotice: "Informativa Legale",
link: "Link",
lng: "Longitudine",
marketingEmail: "Email marketing",
markets: "Mercati",
maxDepth: "Profondit\xE0 massima",
media: "Media",
medias: "Media",
name: "Nome",
nativeName: "Nome Nativo",
newTab: "Nuovo Tab",
options: "Opzioni",
order: "Ordine",
phoneNumber: "Numero di telefono",
position: "Posizione",
price: "Prezzo",
province: "Provincia",
reference: "Riferimento",
region: "Regione",
revoked: "Revocato",
revokedDate: "Data di Revoca",
roles: "Ruoli",
slug: "Slug",
status: "Stato",
streetNumber: "Numero civico",
subContinent: "Subcontinente",
subject: "Oggetto",
target: "Target",
template: "Template",
tenants: "Tenants",
text: "Testo",
title: "Titolo",
to: "A",
type: "Tipo",
url: "Url",
useSplat: "Utilizza Splat",
utmz: "Utmz",
websiteUrl: "Indirizzo sito web",
zipCode: "CAP"
},
description: {
isDefaultPage: "I documenti predefiniti ereditano il loro slug dalla categoria principale."
},
importExport: {
importCSV: "Importa CSV",
exportCSV: "Esporta CSV",
modalTitle: "Importazione",
dropTitle: "Trascina un file qui...",
dropAbstract: "trascina qui un file *.csv, o clicca per selezionare",
parseError: "Si \xE8 verificato un errore durante l'analisi del file csv",
clear: "Annulla",
submit: "Invia",
importMode: "Modalit\xE0",
enableDataParsing: "Abilita il parsing",
modeAppend: "Aggiungi",
modeReplace: "Sostituisci",
modeUpdate: "Aggiorna",
records: "{0} record trovati in <i>{1}</i>",
errorRequired: "'{0}' chiave richiesta mancante",
errorOptional: "'{0}' chiave opzionale mancante",
errorInvalid: "'{0}' valore non valido trovato: ",
errorDuplicate: "'{0}' valore duplicato trovato per campo unico: ",
errorUnexpected: "'{0}' chiave inattesa trovata",
success: "Importato con successo.",
failure: "Si \xE8 verificato un errore durante l'importazione dei dati in '{0}'."
},
// override existing translation keys
general: {
// dashboard: 'Dashboard',
}
}
};
// src/types.ts
var roles = {
Admin: "admin",
Contributor: "contributor",
Editor: "editor",
Guest: "guest",
// api requests (from Oven) will be made with this role if the user didn't authenticate
User: "user"
};
var rolesUser = [roles.Admin, roles.Contributor, roles.Editor];
var rolesEndUser = [roles.User, roles.Guest];
// src/options.ts
var defaultSlug = {
// core
address: "address",
category: "category",
emailConfig: "email_config",
label: "label",
locale: "locale",
market: "market",
media: "media",
menu: "menu",
redirect: "redirect",
template: "template",
// pages
// gdpr
consentPreference: "consent_preference",
legalNotice: "legal_notice",
// users
endUsers: "end_users",
users: "users",
// i18n
continent: "i18n_continent",
country: "i18n_country",
countryZone: "i18n_country_zone",
language: "i18n_language",
municipality: "i18n_municipality",
province: "i18n_province",
region: "i18n_region",
subContinent: "i18n_sub_continent"
// actions
};
var defaultGroup = {
content: "content",
shop: "shop",
nav: "nav",
actions: "actions",
gdpr: "gdpr",
users: "users",
config: "config",
i18n: "i18n"
};
var defaultLocales = ["en", "it"];
var defaultLocale = process.env.DEFAULT_LOCALE || "en";
var defaultMarket = process.env.DEFAULT_MARKET || "ww";
var rolesList = Object.values(roles);
rolesList.sort();
var options = {
actions: [],
bowlCollections: [],
bowlGlobals: [],
collections: [],
defaultLocale,
defaultMarket,
group: defaultGroup,
locales: defaultLocales,
menu: {
blocks: []
},
pages: [],
plugins: [],
roles,
rolesEndUser,
rolesList,
rolesUser,
slug: defaultSlug,
translations,
users: []
};
var internalSlugs = Object.entries(defaultSlug).map((x) => x[1]);
// src/core/api/route.service.ts
var import_bom_core2 = require("@websolutespa/bom-core");
// src/core/api/where.service.ts
function existsClause(value, exists) {
if (typeof exists === "boolean") {
return value != null === exists;
}
return true;
}
__name(existsClause, "existsClause");
function equalsClause(value, equals) {
if (typeof equals !== "undefined") {
return value === equals;
}
return true;
}
__name(equalsClause, "equalsClause");
function inClause(value, values) {
if (Array.isArray(values)) {
return values.indexOf(value) !== -1;
}
return true;
}
__name(inClause, "inClause");
function notInClause(value, values) {
if (Array.isArray(values)) {
return values.indexOf(value) === -1;
}
return true;
}
__name(notInClause, "notInClause");
function likeClause(value, query) {
if (typeof query === "string") {
return String(value).toLowerCase().indexOf(query.toLowerCase()) !== -1;
}
return true;
}
__name(likeClause, "likeClause");
function whereItem(item, where) {
let has = true;
if (typeof where === "object") {
Object.entries(where).forEach(([k, v]) => {
switch (k) {
case "and":
if (Array.isArray(v)) {
has = v.reduce((p, c) => {
return p && whereItem(item, c);
}, has);
}
break;
case "or":
if (Array.isArray(v)) {
has = has && v.reduce((p, c) => {
return p || whereItem(item, c);
}, false);
}
break;
default:
if (typeof v === "object") {
const value = item[k];
has = has && existsClause(value, v.exists);
has = has && equalsClause(value, v.equals);
has = has && inClause(value, v.in);
has = has && notInClause(value, v.not_in);
has = has && likeClause(value, v.like);
}
}
});
}
return has;
}
__name(whereItem, "whereItem");
async function whereCollection(items, where) {
if (typeof where === "object") {
items = items.filter((item) => whereItem(item, where));
}
return items;
}
__name(whereCollection, "whereCollection");
async function sortCollection(items, sort) {
if (sort) {
const keys = sort.split("-");
const reverse = keys.length > 1 ? -1 : 1;
const key = keys.pop();
items = [...items];
items.sort((a, b) => {
const aValue = a[key];
const bValue = b[key];
if (typeof aValue === "number" && typeof bValue === "number") {
return (aValue - bValue) * reverse;
}
const aStringValue = String(aValue);
const bStringValue = String(bValue);
return aStringValue.localeCompare(bStringValue) * reverse;
});
}
return items;
}
__name(sortCollection, "sortCollection");
// src/core/api/cache.service.ts
var CACHE_DURATION = 5 * 60 * 1e3;
var InMemoryCache = class {
duration = CACHE_DURATION;
cache;
constructor(options2 = {}) {
this.duration = typeof options2.duration !== "undefined" ? options2.duration : this.duration;
this.cache = /* @__PURE__ */ new Map();
}
isExpired_(key) {
return this.duration === false ? true : this.cache.get(key).timestamp < (/* @__PURE__ */ new Date()).getTime() - this.duration;
}
has(key) {
return this.cache.has(key) && !this.isExpired_(key);
}
get(key) {
return this.cache.get(key).data;
}
set(key, data) {
this.cache.set(key, {
timestamp: (/* @__PURE__ */ new Date()).getTime(),
data
});
}
};
__name(InMemoryCache, "InMemoryCache");
function keyWithRequest(key, req) {
const segments = req.url.split("?");
return segments.length > 1 ? `${key}-${segments[1]}` : key;
}
__name(keyWithRequest, "keyWithRequest");
// src/core/api/collection.service.ts
var import_payload_utils = require("@websolutespa/payload-utils");
var Papa = __toESM(require("papaparse"));
var import_uuid = require("uuid");
// src/core/decorators/schema.ts
async function decorateSchema_(item, slug) {
return { ...item, schema: item.schema || slug };
}
__name(decorateSchema_, "decorateSchema_");
async function decorateSchemas_(items, slug) {
return items.map((item) => {
return { ...item, schema: item.schema || slug };
});
}
__name(decorateSchemas_, "decorateSchemas_");
// src/core/api/pagination.service.ts
async function getPagination(items, page = 1, limit = 10) {
const totalDocs = items.length;
const totalPages = Math.ceil(items.length / limit);
const hasNextPage = page < totalPages;
const hasPrevPage = page > 1;
const index = page - 1;
const from = index * limit;
const to = Math.min(page * limit, totalDocs);
const docs = items.slice(from, to);
const pagination = {
totalDocs,
totalPages,
page,
limit,
hasNextPage,
hasPrevPage,
nextPage: hasNextPage ? page + 1 : null,
prevPage: hasPrevPage ? page - 1 : null,
pagingCounter: from + 1
};
return {
docs,
...pagination
};
}
__name(getPagination, "getPagination");
// src/core/api/utils.ts
function getObjectParam(value) {
if (typeof value === "object") {
return value;
}
return void 0;
}
__name(getObjectParam, "getObjectParam");
function getNum