@strapi/content-manager 5.60.0 → 5.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/constants/customOrder.js +14 -0
- package/dist/admin/constants/customOrder.js.map +1 -0
- package/dist/admin/constants/customOrder.mjs +10 -0
- package/dist/admin/constants/customOrder.mjs.map +1 -0
- package/dist/admin/hooks/useDocument.js +22 -11
- package/dist/admin/hooks/useDocument.js.map +1 -1
- package/dist/admin/hooks/useDocument.mjs +22 -11
- package/dist/admin/hooks/useDocument.mjs.map +1 -1
- package/dist/admin/hooks/useDocumentLayout.js.map +1 -1
- package/dist/admin/hooks/useDocumentLayout.mjs.map +1 -1
- package/dist/admin/hooks/useHasBeenNearViewport.js +70 -0
- package/dist/admin/hooks/useHasBeenNearViewport.js.map +1 -0
- package/dist/admin/hooks/useHasBeenNearViewport.mjs +46 -0
- package/dist/admin/hooks/useHasBeenNearViewport.mjs.map +1 -0
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/Image.js +102 -32
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/Image.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/Image.mjs +104 -35
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/Image.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/List.js +20 -17
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/List.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/List.mjs +20 -17
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/Blocks/List.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/BlocksContent.js +15 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/BlocksContent.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/BlocksContent.mjs +17 -3
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/BlocksContent.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/plugins/withStrapiSchema.js +21 -0
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/plugins/withStrapiSchema.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/plugins/withStrapiSchema.mjs +22 -1
- package/dist/admin/pages/EditView/components/FormInputs/BlocksInput/plugins/withStrapiSchema.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/RelationModal.js +4 -7
- package/dist/admin/pages/EditView/components/FormInputs/Relations/RelationModal.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/RelationModal.mjs +4 -7
- package/dist/admin/pages/EditView/components/FormInputs/Relations/RelationModal.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.js +46 -10
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.mjs +47 -11
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/FormLayout.js +201 -51
- package/dist/admin/pages/EditView/components/FormLayout.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormLayout.mjs +202 -53
- package/dist/admin/pages/EditView/components/FormLayout.mjs.map +1 -1
- package/dist/admin/pages/ListConfiguration/components/Settings.js +31 -2
- package/dist/admin/pages/ListConfiguration/components/Settings.js.map +1 -1
- package/dist/admin/pages/ListConfiguration/components/Settings.mjs +31 -2
- package/dist/admin/pages/ListConfiguration/components/Settings.mjs.map +1 -1
- package/dist/admin/pages/ListView/ListViewPage.js +196 -132
- package/dist/admin/pages/ListView/ListViewPage.js.map +1 -1
- package/dist/admin/pages/ListView/ListViewPage.mjs +196 -132
- package/dist/admin/pages/ListView/ListViewPage.mjs.map +1 -1
- package/dist/admin/pages/ListView/components/CustomOrder.js +571 -0
- package/dist/admin/pages/ListView/components/CustomOrder.js.map +1 -0
- package/dist/admin/pages/ListView/components/CustomOrder.mjs +546 -0
- package/dist/admin/pages/ListView/components/CustomOrder.mjs.map +1 -0
- package/dist/admin/pages/ListView/components/TableActions.js +4 -1
- package/dist/admin/pages/ListView/components/TableActions.js.map +1 -1
- package/dist/admin/pages/ListView/components/TableActions.mjs +4 -1
- package/dist/admin/pages/ListView/components/TableActions.mjs.map +1 -1
- package/dist/admin/services/documents.js +22 -1
- package/dist/admin/services/documents.js.map +1 -1
- package/dist/admin/services/documents.mjs +21 -2
- package/dist/admin/services/documents.mjs.map +1 -1
- package/dist/admin/src/constants/customOrder.d.ts +8 -0
- package/dist/admin/src/exports.d.ts +1 -1
- package/dist/admin/src/hooks/useDocument.d.ts +4 -0
- package/dist/admin/src/hooks/useDocumentLayout.d.ts +6 -2
- package/dist/admin/src/hooks/useHasBeenNearViewport.d.ts +13 -0
- package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Image.d.ts +13 -1
- package/dist/admin/src/pages/EditView/components/FormLayout.d.ts +11 -1
- package/dist/admin/src/pages/ListView/components/CustomOrder.d.ts +72 -0
- package/dist/admin/src/services/documents.d.ts +10 -2
- package/dist/admin/translations/en.json.js +9 -0
- package/dist/admin/translations/en.json.js.map +1 -1
- package/dist/admin/translations/en.json.mjs +9 -0
- package/dist/admin/translations/en.json.mjs.map +1 -1
- package/dist/server/audit-logs.js +36 -0
- package/dist/server/audit-logs.js.map +1 -0
- package/dist/server/audit-logs.mjs +33 -0
- package/dist/server/audit-logs.mjs.map +1 -0
- package/dist/server/bootstrap.js +8 -0
- package/dist/server/bootstrap.js.map +1 -1
- package/dist/server/bootstrap.mjs +8 -0
- package/dist/server/bootstrap.mjs.map +1 -1
- package/dist/server/controllers/collection-types.js +8 -0
- package/dist/server/controllers/collection-types.js.map +1 -1
- package/dist/server/controllers/collection-types.mjs +8 -0
- package/dist/server/controllers/collection-types.mjs.map +1 -1
- package/dist/server/controllers/content-types.js +15 -0
- package/dist/server/controllers/content-types.js.map +1 -1
- package/dist/server/controllers/content-types.mjs +16 -1
- package/dist/server/controllers/content-types.mjs.map +1 -1
- package/dist/server/controllers/index.js +3 -1
- package/dist/server/controllers/index.js.map +1 -1
- package/dist/server/controllers/index.mjs +2 -0
- package/dist/server/controllers/index.mjs.map +1 -1
- package/dist/server/controllers/relations.js +5 -1
- package/dist/server/controllers/relations.js.map +1 -1
- package/dist/server/controllers/relations.mjs +5 -1
- package/dist/server/controllers/relations.mjs.map +1 -1
- package/dist/server/controllers/single-types.js +10 -1
- package/dist/server/controllers/single-types.js.map +1 -1
- package/dist/server/controllers/single-types.mjs +10 -1
- package/dist/server/controllers/single-types.mjs.map +1 -1
- package/dist/server/controllers/validation/model-configuration.js +2 -1
- package/dist/server/controllers/validation/model-configuration.js.map +1 -1
- package/dist/server/controllers/validation/model-configuration.mjs +2 -1
- package/dist/server/controllers/validation/model-configuration.mjs.map +1 -1
- package/dist/server/custom-order/constants.js +21 -0
- package/dist/server/custom-order/constants.js.map +1 -0
- package/dist/server/custom-order/constants.mjs +17 -0
- package/dist/server/custom-order/constants.mjs.map +1 -0
- package/dist/server/custom-order/controllers/custom-order.js +77 -0
- package/dist/server/custom-order/controllers/custom-order.js.map +1 -0
- package/dist/server/custom-order/controllers/custom-order.mjs +75 -0
- package/dist/server/custom-order/controllers/custom-order.mjs.map +1 -0
- package/dist/server/custom-order/controllers/index.js +10 -0
- package/dist/server/custom-order/controllers/index.js.map +1 -0
- package/dist/server/custom-order/controllers/index.mjs +8 -0
- package/dist/server/custom-order/controllers/index.mjs.map +1 -0
- package/dist/server/custom-order/index.js +71 -0
- package/dist/server/custom-order/index.js.map +1 -0
- package/dist/server/custom-order/index.mjs +69 -0
- package/dist/server/custom-order/index.mjs.map +1 -0
- package/dist/server/custom-order/routes/custom-order.js +38 -0
- package/dist/server/custom-order/routes/custom-order.js.map +1 -0
- package/dist/server/custom-order/routes/custom-order.mjs +36 -0
- package/dist/server/custom-order/routes/custom-order.mjs.map +1 -0
- package/dist/server/custom-order/routes/index.js +13 -0
- package/dist/server/custom-order/routes/index.js.map +1 -0
- package/dist/server/custom-order/routes/index.mjs +11 -0
- package/dist/server/custom-order/routes/index.mjs.map +1 -0
- package/dist/server/custom-order/services/custom-order.js +286 -0
- package/dist/server/custom-order/services/custom-order.js.map +1 -0
- package/dist/server/custom-order/services/custom-order.mjs +284 -0
- package/dist/server/custom-order/services/custom-order.mjs.map +1 -0
- package/dist/server/custom-order/services/document-middleware.js +83 -0
- package/dist/server/custom-order/services/document-middleware.js.map +1 -0
- package/dist/server/custom-order/services/document-middleware.mjs +81 -0
- package/dist/server/custom-order/services/document-middleware.mjs.map +1 -0
- package/dist/server/custom-order/services/index.js +10 -0
- package/dist/server/custom-order/services/index.js.map +1 -0
- package/dist/server/custom-order/services/index.mjs +8 -0
- package/dist/server/custom-order/services/index.mjs.map +1 -0
- package/dist/server/custom-order/services/utils.js +152 -0
- package/dist/server/custom-order/services/utils.js.map +1 -0
- package/dist/server/custom-order/services/utils.mjs +148 -0
- package/dist/server/custom-order/services/utils.mjs.map +1 -0
- package/dist/server/custom-order/utils.js +13 -0
- package/dist/server/custom-order/utils.js.map +1 -0
- package/dist/server/custom-order/utils.mjs +10 -0
- package/dist/server/custom-order/utils.mjs.map +1 -0
- package/dist/server/history/constants.js +2 -1
- package/dist/server/history/constants.js.map +1 -1
- package/dist/server/history/constants.mjs +2 -1
- package/dist/server/history/constants.mjs.map +1 -1
- package/dist/server/history/controllers/history-version.js +6 -2
- package/dist/server/history/controllers/history-version.js.map +1 -1
- package/dist/server/history/controllers/history-version.mjs +6 -2
- package/dist/server/history/controllers/history-version.mjs.map +1 -1
- package/dist/server/history/services/history.js +23 -6
- package/dist/server/history/services/history.js.map +1 -1
- package/dist/server/history/services/history.mjs +24 -7
- package/dist/server/history/services/history.mjs.map +1 -1
- package/dist/server/history/services/lifecycles.js +2 -16
- package/dist/server/history/services/lifecycles.js.map +1 -1
- package/dist/server/history/services/lifecycles.mjs +2 -16
- package/dist/server/history/services/lifecycles.mjs.map +1 -1
- package/dist/server/register.js +4 -0
- package/dist/server/register.js.map +1 -1
- package/dist/server/register.mjs +4 -0
- package/dist/server/register.mjs.map +1 -1
- package/dist/server/routes/index.js +3 -1
- package/dist/server/routes/index.js.map +1 -1
- package/dist/server/routes/index.mjs +2 -0
- package/dist/server/routes/index.mjs.map +1 -1
- package/dist/server/services/content-types.js +2 -2
- package/dist/server/services/content-types.js.map +1 -1
- package/dist/server/services/content-types.mjs +2 -2
- package/dist/server/services/content-types.mjs.map +1 -1
- package/dist/server/services/document-manager.js +13 -0
- package/dist/server/services/document-manager.js.map +1 -1
- package/dist/server/services/document-manager.mjs +14 -1
- package/dist/server/services/document-manager.mjs.map +1 -1
- package/dist/server/services/index.js +3 -1
- package/dist/server/services/index.js.map +1 -1
- package/dist/server/services/index.mjs +2 -0
- package/dist/server/services/index.mjs.map +1 -1
- package/dist/server/services/utils/configuration/settings.js +2 -1
- package/dist/server/services/utils/configuration/settings.js.map +1 -1
- package/dist/server/services/utils/configuration/settings.mjs +2 -1
- package/dist/server/services/utils/configuration/settings.mjs.map +1 -1
- package/dist/server/src/audit-logs.d.ts +40 -0
- package/dist/server/src/audit-logs.d.ts.map +1 -0
- package/dist/server/src/bootstrap.d.ts.map +1 -1
- package/dist/server/src/controllers/collection-types.d.ts +1 -1
- package/dist/server/src/controllers/collection-types.d.ts.map +1 -1
- package/dist/server/src/controllers/content-types.d.ts.map +1 -1
- package/dist/server/src/controllers/index.d.ts +21 -3
- package/dist/server/src/controllers/index.d.ts.map +1 -1
- package/dist/server/src/controllers/relations.d.ts +19 -1
- package/dist/server/src/controllers/relations.d.ts.map +1 -1
- package/dist/server/src/controllers/single-types.d.ts +1 -1
- package/dist/server/src/controllers/single-types.d.ts.map +1 -1
- package/dist/server/src/custom-order/constants.d.ts +18 -0
- package/dist/server/src/custom-order/constants.d.ts.map +1 -0
- package/dist/server/src/custom-order/controllers/custom-order.d.ts +8 -0
- package/dist/server/src/custom-order/controllers/custom-order.d.ts.map +1 -0
- package/dist/server/src/custom-order/controllers/index.d.ts +3 -0
- package/dist/server/src/custom-order/controllers/index.d.ts.map +1 -0
- package/dist/server/src/custom-order/index.d.ts +8 -0
- package/dist/server/src/custom-order/index.d.ts.map +1 -0
- package/dist/server/src/custom-order/routes/custom-order.d.ts +4 -0
- package/dist/server/src/custom-order/routes/custom-order.d.ts.map +1 -0
- package/dist/server/src/custom-order/routes/index.d.ts +10 -0
- package/dist/server/src/custom-order/routes/index.d.ts.map +1 -0
- package/dist/server/src/custom-order/services/custom-order.d.ts +43 -0
- package/dist/server/src/custom-order/services/custom-order.d.ts.map +1 -0
- package/dist/server/src/custom-order/services/document-middleware.d.ts +16 -0
- package/dist/server/src/custom-order/services/document-middleware.d.ts.map +1 -0
- package/dist/server/src/custom-order/services/index.d.ts +24 -0
- package/dist/server/src/custom-order/services/index.d.ts.map +1 -0
- package/dist/server/src/custom-order/services/utils.d.ts +34 -0
- package/dist/server/src/custom-order/services/utils.d.ts.map +1 -0
- package/dist/server/src/custom-order/utils.d.ts +6 -0
- package/dist/server/src/custom-order/utils.d.ts.map +1 -0
- package/dist/server/src/history/constants.d.ts.map +1 -1
- package/dist/server/src/history/controllers/history-version.d.ts.map +1 -1
- package/dist/server/src/history/services/history.d.ts.map +1 -1
- package/dist/server/src/history/services/lifecycles.d.ts.map +1 -1
- package/dist/server/src/index.d.ts +22 -6
- package/dist/server/src/index.d.ts.map +1 -1
- package/dist/server/src/register.d.ts.map +1 -1
- package/dist/server/src/routes/index.d.ts.map +1 -1
- package/dist/server/src/services/content-types.d.ts +1 -3
- package/dist/server/src/services/content-types.d.ts.map +1 -1
- package/dist/server/src/services/document-manager.d.ts.map +1 -1
- package/dist/server/src/services/index.d.ts +1 -3
- package/dist/server/src/services/index.d.ts.map +1 -1
- package/dist/server/src/services/utils/configuration/settings.d.ts.map +1 -1
- package/dist/shared/contracts/content-types.d.ts +5 -0
- package/dist/shared/contracts/content-types.d.ts.map +1 -1
- package/dist/shared/contracts/custom-order.d.ts +33 -0
- package/dist/shared/contracts/custom-order.d.ts.map +1 -0
- package/dist/shared/contracts/custom-order.js +3 -0
- package/dist/shared/contracts/custom-order.js.map +1 -0
- package/dist/shared/contracts/custom-order.mjs +2 -0
- package/dist/shared/contracts/custom-order.mjs.map +1 -0
- package/dist/shared/contracts/history-versions.d.ts +0 -1
- package/dist/shared/contracts/history-versions.d.ts.map +1 -1
- package/dist/shared/contracts/index.d.ts +1 -0
- package/dist/shared/contracts/index.d.ts.map +1 -1
- package/dist/shared/contracts/index.js +2 -0
- package/dist/shared/contracts/index.js.map +1 -1
- package/dist/shared/contracts/index.mjs +2 -0
- package/dist/shared/contracts/index.mjs.map +1 -1
- package/package.json +8 -8
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Hidden field holding the position of an entry in the custom order of its collection type.
|
|
5
|
+
* It is never part of the content type schema sent to the admin, it can only be sorted on.
|
|
6
|
+
*/ const CUSTOM_ORDER_FIELD = 'strapi_position';
|
|
7
|
+
const CUSTOM_ORDER_SORT = `${CUSTOM_ORDER_FIELD}:ASC`;
|
|
8
|
+
const CUSTOM_ORDER_FUTURE_FLAG = 'unstableCustomOrder';
|
|
9
|
+
const isCustomOrderFeatureEnabled = ()=>window.strapi.future.isEnabled(CUSTOM_ORDER_FUTURE_FLAG) === true;
|
|
10
|
+
|
|
11
|
+
exports.CUSTOM_ORDER_FIELD = CUSTOM_ORDER_FIELD;
|
|
12
|
+
exports.CUSTOM_ORDER_SORT = CUSTOM_ORDER_SORT;
|
|
13
|
+
exports.isCustomOrderFeatureEnabled = isCustomOrderFeatureEnabled;
|
|
14
|
+
//# sourceMappingURL=customOrder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"customOrder.js","sources":["../../../admin/src/constants/customOrder.ts"],"sourcesContent":["/**\n * Hidden field holding the position of an entry in the custom order of its collection type.\n * It is never part of the content type schema sent to the admin, it can only be sorted on.\n */\nconst CUSTOM_ORDER_FIELD = 'strapi_position';\n\nconst CUSTOM_ORDER_SORT = `${CUSTOM_ORDER_FIELD}:ASC`;\n\nconst CUSTOM_ORDER_FUTURE_FLAG = 'unstableCustomOrder';\n\nconst isCustomOrderFeatureEnabled = () =>\n window.strapi.future.isEnabled(CUSTOM_ORDER_FUTURE_FLAG) === true;\n\nexport { CUSTOM_ORDER_FIELD, CUSTOM_ORDER_SORT, isCustomOrderFeatureEnabled };\n"],"names":["CUSTOM_ORDER_FIELD","CUSTOM_ORDER_SORT","CUSTOM_ORDER_FUTURE_FLAG","isCustomOrderFeatureEnabled","window","strapi","future","isEnabled"],"mappings":";;AAAA;;;AAGC,UACKA,kBAAAA,GAAqB;AAE3B,MAAMC,iBAAAA,GAAoB,CAAA,EAAGD,kBAAAA,CAAmB,IAAI;AAEpD,MAAME,wBAAAA,GAA2B,qBAAA;AAEjC,MAAMC,2BAAAA,GAA8B,IAClCC,MAAAA,CAAOC,MAAM,CAACC,MAAM,CAACC,SAAS,CAACL,wBAAAA,CAAAA,KAA8B;;;;;;"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hidden field holding the position of an entry in the custom order of its collection type.
|
|
3
|
+
* It is never part of the content type schema sent to the admin, it can only be sorted on.
|
|
4
|
+
*/ const CUSTOM_ORDER_FIELD = 'strapi_position';
|
|
5
|
+
const CUSTOM_ORDER_SORT = `${CUSTOM_ORDER_FIELD}:ASC`;
|
|
6
|
+
const CUSTOM_ORDER_FUTURE_FLAG = 'unstableCustomOrder';
|
|
7
|
+
const isCustomOrderFeatureEnabled = ()=>window.strapi.future.isEnabled(CUSTOM_ORDER_FUTURE_FLAG) === true;
|
|
8
|
+
|
|
9
|
+
export { CUSTOM_ORDER_FIELD, CUSTOM_ORDER_SORT, isCustomOrderFeatureEnabled };
|
|
10
|
+
//# sourceMappingURL=customOrder.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"customOrder.mjs","sources":["../../../admin/src/constants/customOrder.ts"],"sourcesContent":["/**\n * Hidden field holding the position of an entry in the custom order of its collection type.\n * It is never part of the content type schema sent to the admin, it can only be sorted on.\n */\nconst CUSTOM_ORDER_FIELD = 'strapi_position';\n\nconst CUSTOM_ORDER_SORT = `${CUSTOM_ORDER_FIELD}:ASC`;\n\nconst CUSTOM_ORDER_FUTURE_FLAG = 'unstableCustomOrder';\n\nconst isCustomOrderFeatureEnabled = () =>\n window.strapi.future.isEnabled(CUSTOM_ORDER_FUTURE_FLAG) === true;\n\nexport { CUSTOM_ORDER_FIELD, CUSTOM_ORDER_SORT, isCustomOrderFeatureEnabled };\n"],"names":["CUSTOM_ORDER_FIELD","CUSTOM_ORDER_SORT","CUSTOM_ORDER_FUTURE_FLAG","isCustomOrderFeatureEnabled","window","strapi","future","isEnabled"],"mappings":"AAAA;;;AAGC,UACKA,kBAAAA,GAAqB;AAE3B,MAAMC,iBAAAA,GAAoB,CAAA,EAAGD,kBAAAA,CAAmB,IAAI;AAEpD,MAAME,wBAAAA,GAA2B,qBAAA;AAEjC,MAAMC,2BAAAA,GAA8B,IAClCC,MAAAA,CAAOC,MAAM,CAACC,MAAM,CAACC,SAAS,CAACL,wBAAAA,CAAAA,KAA8B;;;;"}
|
|
@@ -34,6 +34,24 @@ function _interopNamespace(e) {
|
|
|
34
34
|
|
|
35
35
|
var React__namespace = /*#__PURE__*/_interopNamespace(React);
|
|
36
36
|
|
|
37
|
+
// Building the yup schema of a model clones a schema for every nested component and dynamic
|
|
38
|
+
// zone: on large models it takes seconds and gigabytes. `schema` and `components` identities
|
|
39
|
+
// are shared across hook instances (see `useContentTypeSchema`), so build it once per pair,
|
|
40
|
+
// and only when something actually validates.
|
|
41
|
+
const validationSchemaCache = new WeakMap();
|
|
42
|
+
const getValidationSchema = (schema, components)=>{
|
|
43
|
+
let byComponents = validationSchemaCache.get(schema);
|
|
44
|
+
if (!byComponents) {
|
|
45
|
+
byComponents = new WeakMap();
|
|
46
|
+
validationSchemaCache.set(schema, byComponents);
|
|
47
|
+
}
|
|
48
|
+
let validationSchema = byComponents.get(components);
|
|
49
|
+
if (!validationSchema) {
|
|
50
|
+
validationSchema = validation.createYupSchema(schema.attributes, components);
|
|
51
|
+
byComponents.set(components, validationSchema);
|
|
52
|
+
}
|
|
53
|
+
return validationSchema;
|
|
54
|
+
};
|
|
37
55
|
/**
|
|
38
56
|
* Mirrors the server's `isLocalizedAttribute` in
|
|
39
57
|
* `packages/plugins/i18n/server/src/services/content-types.ts`: an attribute
|
|
@@ -121,19 +139,11 @@ var React__namespace = /*#__PURE__*/_interopNamespace(React);
|
|
|
121
139
|
formatAPIError,
|
|
122
140
|
args.collectionType
|
|
123
141
|
]);
|
|
124
|
-
const validationSchema = React__namespace.useMemo(()=>{
|
|
125
|
-
if (!schema) {
|
|
126
|
-
return null;
|
|
127
|
-
}
|
|
128
|
-
return validation.createYupSchema(schema.attributes, components);
|
|
129
|
-
}, [
|
|
130
|
-
schema,
|
|
131
|
-
components
|
|
132
|
-
]);
|
|
133
142
|
const validate = React__namespace.useCallback((document)=>{
|
|
134
|
-
if (!
|
|
143
|
+
if (!schema) {
|
|
135
144
|
throw new Error('There is no validation schema generated, this is likely due to the schema not being loaded yet.');
|
|
136
145
|
}
|
|
146
|
+
const validationSchema = getValidationSchema(schema, components);
|
|
137
147
|
try {
|
|
138
148
|
validationSchema.validateSync(document, {
|
|
139
149
|
abortEarly: false,
|
|
@@ -147,7 +157,8 @@ var React__namespace = /*#__PURE__*/_interopNamespace(React);
|
|
|
147
157
|
throw error;
|
|
148
158
|
}
|
|
149
159
|
}, [
|
|
150
|
-
|
|
160
|
+
schema,
|
|
161
|
+
components
|
|
151
162
|
]);
|
|
152
163
|
/**
|
|
153
164
|
* Schema attributes that should be inherited from a sibling locale when
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDocument.js","sources":["../../../admin/src/hooks/useDocument.ts"],"sourcesContent":["/**\n * This hook doesn't use a context provider because we fetch directly from the server,\n * this sounds expensive but actually, it's really not. Because we have redux-toolkit-query\n * being a cache layer so if nothing invalidates the cache, we don't fetch again.\n */\n\nimport * as React from 'react';\n\nimport {\n useNotification,\n useAPIErrorHandler,\n useQueryParams,\n FormErrors,\n getYupValidationErrors,\n useForm,\n} from '@strapi/admin/strapi-admin';\nimport { useIntl } from 'react-intl';\nimport { useParams } from 'react-router-dom';\nimport { ValidationError } from 'yup';\n\nimport { SINGLE_TYPES } from '../constants/collections';\nimport { type AnyData, transformDocument } from '../pages/EditView/utils/data';\nimport { createDefaultForm } from '../pages/EditView/utils/forms';\nimport { useGetDocumentQuery } from '../services/documents';\nimport { buildValidParams } from '../utils/api';\nimport { createYupSchema } from '../utils/validation';\n\nimport { useContentTypeSchema, ComponentsDictionary } from './useContentTypeSchema';\nimport { useDocumentLayout } from './useDocumentLayout';\n\nimport type { FindOne } from '../../../shared/contracts/collection-types';\nimport type { ContentType } from '../../../shared/contracts/content-types';\nimport type { Modules } from '@strapi/types';\n\ninterface UseDocumentArgs {\n collectionType: string;\n model: string;\n documentId?: string;\n params?: object;\n}\n\ntype UseDocumentOpts = Parameters<typeof useGetDocumentQuery>[1];\n\ntype Document = FindOne.Response['data'];\n\ntype Schema = ContentType;\n\ntype UseDocument = (\n args: UseDocumentArgs,\n opts?: UseDocumentOpts\n) => {\n /**\n * These are the schemas of the components used in the content type, organised\n * by their uid.\n */\n components: ComponentsDictionary;\n document?: Document;\n meta?: FindOne.Response['meta'];\n isLoading: boolean;\n /**\n * This is the schema of the content type, it is not the same as the layout.\n */\n schema?: Schema;\n schemas?: Schema[];\n hasError?: boolean;\n refetch: () => void;\n validate: (document: Document) => null | FormErrors;\n /**\n * Get the document's title\n */\n getTitle: (mainField: string) => string;\n /**\n * Get the initial form values for the document\n */\n getInitialFormValues: (isCreatingDocument?: boolean) => AnyData | undefined;\n};\n\n/**\n * Mirrors the server's `isLocalizedAttribute` in\n * `packages/plugins/i18n/server/src/services/content-types.ts`: an attribute\n * counts as localized only when `pluginOptions.i18n.localized` is explicitly\n * `true`. Both `false` and `undefined` mean \"non-localized\" — important here\n * because attributes created without the i18n plugin omit the field entirely,\n * and we still want them inherited when creating a new locale draft.\n */\nconst isLocalizedAttribute = (attribute: { pluginOptions?: object }): boolean => {\n // `pluginOptions` on the base attribute is typed as `object`, so we have to\n // narrow it to the i18n-specific shape here.\n const i18nOptions = attribute.pluginOptions as { i18n?: { localized?: boolean } } | undefined;\n return i18nOptions?.i18n?.localized === true;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocument\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @alpha\n * @public\n * @description Returns a document based on the model, collection type & id passed as arguments.\n * Also extracts its schema from the redux cache to be used for creating a validation schema.\n * @example\n * ```tsx\n * const { id, model, collectionType } = useParams<{ id: string; model: string; collectionType: string }>();\n *\n * if(!model || !collectionType) return null;\n *\n * const { document, isLoading, validate } = useDocument({ documentId: id, model, collectionType, params: { locale: 'en-GB' } })\n * const { update } = useDocumentActions()\n *\n * const onSubmit = async (document: Document) => {\n * const errors = validate(document);\n *\n * if(errors) {\n * // handle errors\n * }\n *\n * await update({ collectionType, model, id }, document)\n * }\n * ```\n *\n */\nconst useDocument: UseDocument = (args, opts) => {\n const { toggleNotification } = useNotification();\n const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();\n const { formatMessage } = useIntl();\n\n const {\n currentData: data,\n isLoading: isLoadingDocument,\n isFetching: isFetchingDocument,\n error,\n refetch,\n } = useGetDocumentQuery(args, {\n ...opts,\n skip: (!args.documentId && args.collectionType !== SINGLE_TYPES) || opts?.skip,\n });\n const document = data?.data;\n const meta = data?.meta;\n\n const {\n components,\n schema,\n schemas,\n isLoading: isLoadingSchema,\n } = useContentTypeSchema(args.model);\n const isSingleType = schema?.kind === 'singleType';\n\n const getTitle = React.useCallback(\n (mainField: string) => {\n // Always use mainField if it's not an id\n if (mainField !== 'id' && document?.[mainField]) {\n return document[mainField];\n }\n\n // When it's a singleType without a mainField, use the contentType displayName\n if (schema?.kind === 'singleType' && schema.info.displayName) {\n return formatMessage({\n id: schema.info.displayName,\n defaultMessage: schema.info.displayName,\n });\n }\n\n // Otherwise, use a fallback\n return formatMessage({\n id: 'content-manager.containers.untitled',\n defaultMessage: 'Untitled',\n });\n },\n [document, formatMessage, schema]\n );\n\n React.useEffect(() => {\n if (error) {\n toggleNotification({\n type: 'danger',\n message: formatAPIError(error),\n });\n }\n }, [toggleNotification, error, formatAPIError, args.collectionType]);\n\n const validationSchema = React.useMemo(() => {\n if (!schema) {\n return null;\n }\n\n return createYupSchema(schema.attributes, components);\n }, [schema, components]);\n\n const validate = React.useCallback(\n (document: Modules.Documents.AnyDocument): FormErrors | null => {\n if (!validationSchema) {\n throw new Error(\n 'There is no validation schema generated, this is likely due to the schema not being loaded yet.'\n );\n }\n\n try {\n validationSchema.validateSync(document, { abortEarly: false, strict: true });\n return null;\n } catch (error) {\n if (error instanceof ValidationError) {\n return getYupValidationErrors(error);\n }\n\n throw error;\n }\n },\n [validationSchema]\n );\n\n /**\n * Schema attributes that should be inherited from a sibling locale when\n * creating a new locale draft.\n *\n * Scope intentionally matches what the server populates into\n * `meta.availableLocales` (see `packages/core/content-manager/server/src/services/document-metadata.ts`):\n * - non-localized — `isLocalizedAttribute` semantics, so attributes whose\n * `pluginOptions.i18n.localized` is `undefined` count as non-localized\n * (an attribute created without the i18n plugin has no i18n options at\n * all but is still inherited at save by `copyNonLocalizedFields`).\n * - scalar or media — `component` / `dynamiczone` / `relation` are excluded\n * because the server doesn't populate them in `availableLocales` either,\n * so there'd be nothing to copy from.\n */\n const nonLocalizedScalarAndMediaFields = React.useMemo(() => {\n if (!schema?.attributes) {\n return [];\n }\n\n return Object.keys(schema.attributes).filter((name) => {\n const attribute = schema.attributes[name];\n\n if (isLocalizedAttribute(attribute)) {\n return false;\n }\n\n return (\n attribute.type !== 'component' &&\n attribute.type !== 'dynamiczone' &&\n attribute.type !== 'relation'\n );\n });\n }, [schema]);\n\n /**\n * Here we prepare the form for editing, we need to:\n * - remove prohibited fields from the document (passwords | ADD YOURS WHEN THERES A NEW ONE)\n * - swap out count objects on relations for empty arrays\n * - set __temp_key__ on array objects for drag & drop\n *\n * We also prepare the form for new documents, so we need to:\n * - set default values on fields\n * - inherit non-localized scalar/media values from a sibling locale.\n * Scope is intentionally limited to scalars and media — that is exactly\n * what the server populates into `meta.availableLocales` (see\n * `packages/core/content-manager/server/src/services/document-metadata.ts`).\n * Components, dynamic zones, and relations are not in that payload; the\n * server fills them at save time via `copyNonLocalizedFields` (in\n * `packages/core/core/src/services/document-service/internationalization.ts`)\n * when the new locale row is first created.\n * Baking the inheritance into `initialValues` here is what lets it survive\n * `<Form>` re-inits: the `SET_INITIAL_VALUES` effect in\n * `packages/core/admin/admin/src/components/Form.tsx` re-applies these\n * values whenever `initialValues` changes (e.g. after a locale switch),\n * which the previous side-effect-based prefill in `LocalePickerAction`\n * could not survive on revisits.\n */\n const getInitialFormValues = React.useCallback(\n (isCreatingDocument: boolean = false) => {\n if ((!document && !isCreatingDocument && !isSingleType) || !schema) {\n return undefined;\n }\n\n /**\n * Check that we have an ID so we know the\n * document has been created in some way.\n */\n if (document?.id) {\n return transformDocument(schema, components)(document);\n }\n\n let form: AnyData = createDefaultForm(schema, components);\n\n // Intentionally use `availableLocales[0]`:\n // - The server sorts `getAvailableLocales` with the default locale first\n // (see `document-metadata.ts`), so index 0 is the canonical inheritance\n // source. Sibling locales can drift on non-localized fields because the\n // server only syncs them at locale-creation time, not on subsequent\n // updates — preferring the default keeps the surfaced values stable.\n // - Avoids coupling this hook to `useGetLocalesQuery` just to find the\n // default locale.\n const sibling = meta?.availableLocales?.[0] as Record<string, unknown> | undefined;\n if (sibling && nonLocalizedScalarAndMediaFields.length > 0) {\n const inherited = nonLocalizedScalarAndMediaFields.reduce<AnyData>((acc, name) => {\n if (name in sibling) {\n acc[name] = sibling[name];\n }\n return acc;\n }, {});\n\n form = { ...form, ...inherited };\n }\n\n return transformDocument(schema, components)(form);\n },\n [\n document,\n isSingleType,\n schema,\n components,\n meta?.availableLocales,\n nonLocalizedScalarAndMediaFields,\n ]\n );\n\n const isLoading = isLoadingDocument || isFetchingDocument || isLoadingSchema;\n const hasError = !!error;\n\n return React.useMemo(\n () =>\n ({\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n }) satisfies ReturnType<UseDocument>,\n [\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n ]\n );\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDoc\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal this hook uses the router to extract the model, collection type & id from the url.\n * therefore, it shouldn't be used outside of the content-manager because it won't work as intended.\n */\nconst useDoc = (opts?: UseDocumentOpts) => {\n const { id, slug, collectionType, origin } = useParams<{\n id: string;\n origin: string;\n slug: string;\n collectionType: string;\n }>();\n const [{ query }] = useQueryParams();\n const params = React.useMemo(() => buildValidParams(query), [query]);\n\n if (!collectionType) {\n throw new Error('Could not find collectionType in url params');\n }\n\n if (!slug) {\n throw new Error('Could not find model in url params');\n }\n\n const document = useDocument(\n { documentId: origin || id, model: slug, collectionType, params },\n {\n ...opts,\n skip: id === 'create' || (!origin && !id && collectionType !== SINGLE_TYPES) || opts?.skip,\n }\n );\n\n const returnId = origin || (id === 'create' ? undefined : id);\n\n return {\n collectionType,\n model: slug,\n id: returnId,\n ...document,\n };\n};\n\n/**\n * @public\n * @experimental\n * Content manager context hooks for plugin development.\n * Make sure to use this hook inside the content manager.\n */\nconst useContentManagerContext = () => {\n const {\n collectionType,\n model,\n id,\n components,\n isLoading: isLoadingDoc,\n schema,\n schemas,\n } = useDoc();\n\n const layout = useDocumentLayout(model);\n\n const form = useForm<unknown>('useContentManagerContext', (state) => state);\n\n const isSingleType = collectionType === SINGLE_TYPES;\n const slug = model;\n const isCreatingEntry = id === 'create';\n\n useContentTypeSchema();\n\n const isLoading = isLoadingDoc || layout.isLoading;\n const error = layout.error;\n\n return {\n error,\n isLoading,\n\n // Base metadata\n model,\n collectionType,\n id,\n slug,\n isCreatingEntry,\n isSingleType,\n hasDraftAndPublish: schema?.options?.draftAndPublish ?? false,\n\n // All schema infos\n components,\n contentType: schema,\n contentTypes: schemas,\n\n // Form state\n form,\n\n // layout infos\n layout,\n };\n};\n\nexport { useDocument, useDoc, useContentManagerContext };\nexport type { UseDocument, UseDocumentArgs, Document, Schema, ComponentsDictionary };\n"],"names":["isLocalizedAttribute","attribute","i18nOptions","pluginOptions","i18n","localized","useDocument","args","opts","toggleNotification","useNotification","_unstableFormatAPIError","formatAPIError","useAPIErrorHandler","formatMessage","useIntl","currentData","data","isLoading","isLoadingDocument","isFetching","isFetchingDocument","error","refetch","useGetDocumentQuery","skip","documentId","collectionType","SINGLE_TYPES","document","meta","components","schema","schemas","isLoadingSchema","useContentTypeSchema","model","isSingleType","kind","getTitle","React","useCallback","mainField","info","displayName","id","defaultMessage","useEffect","type","message","validationSchema","useMemo","createYupSchema","attributes","validate","Error","validateSync","abortEarly","strict","ValidationError","getYupValidationErrors","nonLocalizedScalarAndMediaFields","Object","keys","filter","name","getInitialFormValues","isCreatingDocument","undefined","transformDocument","form","createDefaultForm","sibling","availableLocales","length","inherited","reduce","acc","hasError","useDoc","slug","origin","useParams","query","useQueryParams","params","buildValidParams","returnId","useContentManagerContext","isLoadingDoc","layout","useDocumentLayout","useForm","state","isCreatingEntry","hasDraftAndPublish","options","draftAndPublish","contentType","contentTypes"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA;;;;;;;IAQA,MAAMA,uBAAuB,CAACC,SAAAA,GAAAA;;;IAG5B,MAAMC,WAAAA,GAAcD,UAAUE,aAAa;IAC3C,OAAOD,WAAAA,EAAaE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DlE,QAAAA,UAAAA;QACAmE,WAAAA,EAAalE,MAAAA;QACbmE,YAAAA,EAAclE,OAAAA;;AAGdqC,QAAAA,IAAAA;;AAGAoB,QAAAA;AACF,KAAA;AACF;;;;;;"}
|
|
1
|
+
{"version":3,"file":"useDocument.js","sources":["../../../admin/src/hooks/useDocument.ts"],"sourcesContent":["/**\n * This hook doesn't use a context provider because we fetch directly from the server,\n * this sounds expensive but actually, it's really not. Because we have redux-toolkit-query\n * being a cache layer so if nothing invalidates the cache, we don't fetch again.\n *\n * The network is deduplicated, but the work done inside the hook is not: it can be mounted\n * by hundreds of fields at once, so anything expensive it derives must be cached outside of\n * the hook instance (see `getValidationSchema`).\n */\n\nimport * as React from 'react';\n\nimport {\n useNotification,\n useAPIErrorHandler,\n useQueryParams,\n FormErrors,\n getYupValidationErrors,\n useForm,\n} from '@strapi/admin/strapi-admin';\nimport { useIntl } from 'react-intl';\nimport { useParams } from 'react-router-dom';\nimport { ValidationError } from 'yup';\n\nimport { SINGLE_TYPES } from '../constants/collections';\nimport { type AnyData, transformDocument } from '../pages/EditView/utils/data';\nimport { createDefaultForm } from '../pages/EditView/utils/forms';\nimport { useGetDocumentQuery } from '../services/documents';\nimport { buildValidParams } from '../utils/api';\nimport { createYupSchema } from '../utils/validation';\n\nimport { useContentTypeSchema, ComponentsDictionary } from './useContentTypeSchema';\nimport { useDocumentLayout } from './useDocumentLayout';\n\nimport type { FindOne } from '../../../shared/contracts/collection-types';\nimport type { ContentType } from '../../../shared/contracts/content-types';\nimport type { Modules } from '@strapi/types';\n\ninterface UseDocumentArgs {\n collectionType: string;\n model: string;\n documentId?: string;\n params?: object;\n}\n\ntype UseDocumentOpts = Parameters<typeof useGetDocumentQuery>[1];\n\ntype Document = FindOne.Response['data'];\n\ntype Schema = ContentType;\n\ntype ValidationSchema = ReturnType<typeof createYupSchema>;\n\n// Building the yup schema of a model clones a schema for every nested component and dynamic\n// zone: on large models it takes seconds and gigabytes. `schema` and `components` identities\n// are shared across hook instances (see `useContentTypeSchema`), so build it once per pair,\n// and only when something actually validates.\nconst validationSchemaCache = new WeakMap<\n Schema,\n WeakMap<ComponentsDictionary, ValidationSchema>\n>();\n\nconst getValidationSchema = (schema: Schema, components: ComponentsDictionary) => {\n let byComponents = validationSchemaCache.get(schema);\n\n if (!byComponents) {\n byComponents = new WeakMap();\n validationSchemaCache.set(schema, byComponents);\n }\n\n let validationSchema = byComponents.get(components);\n\n if (!validationSchema) {\n validationSchema = createYupSchema(schema.attributes, components);\n byComponents.set(components, validationSchema);\n }\n\n return validationSchema;\n};\n\ntype UseDocument = (\n args: UseDocumentArgs,\n opts?: UseDocumentOpts\n) => {\n /**\n * These are the schemas of the components used in the content type, organised\n * by their uid.\n */\n components: ComponentsDictionary;\n document?: Document;\n meta?: FindOne.Response['meta'];\n isLoading: boolean;\n /**\n * This is the schema of the content type, it is not the same as the layout.\n */\n schema?: Schema;\n schemas?: Schema[];\n hasError?: boolean;\n refetch: () => void;\n validate: (document: Document) => null | FormErrors;\n /**\n * Get the document's title\n */\n getTitle: (mainField: string) => string;\n /**\n * Get the initial form values for the document\n */\n getInitialFormValues: (isCreatingDocument?: boolean) => AnyData | undefined;\n};\n\n/**\n * Mirrors the server's `isLocalizedAttribute` in\n * `packages/plugins/i18n/server/src/services/content-types.ts`: an attribute\n * counts as localized only when `pluginOptions.i18n.localized` is explicitly\n * `true`. Both `false` and `undefined` mean \"non-localized\" — important here\n * because attributes created without the i18n plugin omit the field entirely,\n * and we still want them inherited when creating a new locale draft.\n */\nconst isLocalizedAttribute = (attribute: { pluginOptions?: object }): boolean => {\n // `pluginOptions` on the base attribute is typed as `object`, so we have to\n // narrow it to the i18n-specific shape here.\n const i18nOptions = attribute.pluginOptions as { i18n?: { localized?: boolean } } | undefined;\n return i18nOptions?.i18n?.localized === true;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocument\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @alpha\n * @public\n * @description Returns a document based on the model, collection type & id passed as arguments.\n * Also extracts its schema from the redux cache to be used for creating a validation schema.\n * @example\n * ```tsx\n * const { id, model, collectionType } = useParams<{ id: string; model: string; collectionType: string }>();\n *\n * if(!model || !collectionType) return null;\n *\n * const { document, isLoading, validate } = useDocument({ documentId: id, model, collectionType, params: { locale: 'en-GB' } })\n * const { update } = useDocumentActions()\n *\n * const onSubmit = async (document: Document) => {\n * const errors = validate(document);\n *\n * if(errors) {\n * // handle errors\n * }\n *\n * await update({ collectionType, model, id }, document)\n * }\n * ```\n *\n */\nconst useDocument: UseDocument = (args, opts) => {\n const { toggleNotification } = useNotification();\n const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();\n const { formatMessage } = useIntl();\n\n const {\n currentData: data,\n isLoading: isLoadingDocument,\n isFetching: isFetchingDocument,\n error,\n refetch,\n } = useGetDocumentQuery(args, {\n ...opts,\n skip: (!args.documentId && args.collectionType !== SINGLE_TYPES) || opts?.skip,\n });\n const document = data?.data;\n const meta = data?.meta;\n\n const {\n components,\n schema,\n schemas,\n isLoading: isLoadingSchema,\n } = useContentTypeSchema(args.model);\n const isSingleType = schema?.kind === 'singleType';\n\n const getTitle = React.useCallback(\n (mainField: string) => {\n // Always use mainField if it's not an id\n if (mainField !== 'id' && document?.[mainField]) {\n return document[mainField];\n }\n\n // When it's a singleType without a mainField, use the contentType displayName\n if (schema?.kind === 'singleType' && schema.info.displayName) {\n return formatMessage({\n id: schema.info.displayName,\n defaultMessage: schema.info.displayName,\n });\n }\n\n // Otherwise, use a fallback\n return formatMessage({\n id: 'content-manager.containers.untitled',\n defaultMessage: 'Untitled',\n });\n },\n [document, formatMessage, schema]\n );\n\n React.useEffect(() => {\n if (error) {\n toggleNotification({\n type: 'danger',\n message: formatAPIError(error),\n });\n }\n }, [toggleNotification, error, formatAPIError, args.collectionType]);\n\n const validate = React.useCallback(\n (document: Modules.Documents.AnyDocument): FormErrors | null => {\n if (!schema) {\n throw new Error(\n 'There is no validation schema generated, this is likely due to the schema not being loaded yet.'\n );\n }\n\n const validationSchema = getValidationSchema(schema, components);\n\n try {\n validationSchema.validateSync(document, { abortEarly: false, strict: true });\n return null;\n } catch (error) {\n if (error instanceof ValidationError) {\n return getYupValidationErrors(error);\n }\n\n throw error;\n }\n },\n [schema, components]\n );\n\n /**\n * Schema attributes that should be inherited from a sibling locale when\n * creating a new locale draft.\n *\n * Scope intentionally matches what the server populates into\n * `meta.availableLocales` (see `packages/core/content-manager/server/src/services/document-metadata.ts`):\n * - non-localized — `isLocalizedAttribute` semantics, so attributes whose\n * `pluginOptions.i18n.localized` is `undefined` count as non-localized\n * (an attribute created without the i18n plugin has no i18n options at\n * all but is still inherited at save by `copyNonLocalizedFields`).\n * - scalar or media — `component` / `dynamiczone` / `relation` are excluded\n * because the server doesn't populate them in `availableLocales` either,\n * so there'd be nothing to copy from.\n */\n const nonLocalizedScalarAndMediaFields = React.useMemo(() => {\n if (!schema?.attributes) {\n return [];\n }\n\n return Object.keys(schema.attributes).filter((name) => {\n const attribute = schema.attributes[name];\n\n if (isLocalizedAttribute(attribute)) {\n return false;\n }\n\n return (\n attribute.type !== 'component' &&\n attribute.type !== 'dynamiczone' &&\n attribute.type !== 'relation'\n );\n });\n }, [schema]);\n\n /**\n * Here we prepare the form for editing, we need to:\n * - remove prohibited fields from the document (passwords | ADD YOURS WHEN THERES A NEW ONE)\n * - swap out count objects on relations for empty arrays\n * - set __temp_key__ on array objects for drag & drop\n *\n * We also prepare the form for new documents, so we need to:\n * - set default values on fields\n * - inherit non-localized scalar/media values from a sibling locale.\n * Scope is intentionally limited to scalars and media — that is exactly\n * what the server populates into `meta.availableLocales` (see\n * `packages/core/content-manager/server/src/services/document-metadata.ts`).\n * Components, dynamic zones, and relations are not in that payload; the\n * server fills them at save time via `copyNonLocalizedFields` (in\n * `packages/core/core/src/services/document-service/internationalization.ts`)\n * when the new locale row is first created.\n * Baking the inheritance into `initialValues` here is what lets it survive\n * `<Form>` re-inits: the `SET_INITIAL_VALUES` effect in\n * `packages/core/admin/admin/src/components/Form.tsx` re-applies these\n * values whenever `initialValues` changes (e.g. after a locale switch),\n * which the previous side-effect-based prefill in `LocalePickerAction`\n * could not survive on revisits.\n */\n const getInitialFormValues = React.useCallback(\n (isCreatingDocument: boolean = false) => {\n if ((!document && !isCreatingDocument && !isSingleType) || !schema) {\n return undefined;\n }\n\n /**\n * Check that we have an ID so we know the\n * document has been created in some way.\n */\n if (document?.id) {\n return transformDocument(schema, components)(document);\n }\n\n let form: AnyData = createDefaultForm(schema, components);\n\n // Intentionally use `availableLocales[0]`:\n // - The server sorts `getAvailableLocales` with the default locale first\n // (see `document-metadata.ts`), so index 0 is the canonical inheritance\n // source. Sibling locales can drift on non-localized fields because the\n // server only syncs them at locale-creation time, not on subsequent\n // updates — preferring the default keeps the surfaced values stable.\n // - Avoids coupling this hook to `useGetLocalesQuery` just to find the\n // default locale.\n const sibling = meta?.availableLocales?.[0] as Record<string, unknown> | undefined;\n if (sibling && nonLocalizedScalarAndMediaFields.length > 0) {\n const inherited = nonLocalizedScalarAndMediaFields.reduce<AnyData>((acc, name) => {\n if (name in sibling) {\n acc[name] = sibling[name];\n }\n return acc;\n }, {});\n\n form = { ...form, ...inherited };\n }\n\n return transformDocument(schema, components)(form);\n },\n [\n document,\n isSingleType,\n schema,\n components,\n meta?.availableLocales,\n nonLocalizedScalarAndMediaFields,\n ]\n );\n\n const isLoading = isLoadingDocument || isFetchingDocument || isLoadingSchema;\n const hasError = !!error;\n\n return React.useMemo(\n () =>\n ({\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n }) satisfies ReturnType<UseDocument>,\n [\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n ]\n );\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDoc\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal this hook uses the router to extract the model, collection type & id from the url.\n * therefore, it shouldn't be used outside of the content-manager because it won't work as intended.\n */\nconst useDoc = (opts?: UseDocumentOpts) => {\n const { id, slug, collectionType, origin } = useParams<{\n id: string;\n origin: string;\n slug: string;\n collectionType: string;\n }>();\n const [{ query }] = useQueryParams();\n const params = React.useMemo(() => buildValidParams(query), [query]);\n\n if (!collectionType) {\n throw new Error('Could not find collectionType in url params');\n }\n\n if (!slug) {\n throw new Error('Could not find model in url params');\n }\n\n const document = useDocument(\n { documentId: origin || id, model: slug, collectionType, params },\n {\n ...opts,\n skip: id === 'create' || (!origin && !id && collectionType !== SINGLE_TYPES) || opts?.skip,\n }\n );\n\n const returnId = origin || (id === 'create' ? undefined : id);\n\n return {\n collectionType,\n model: slug,\n id: returnId,\n ...document,\n };\n};\n\n/**\n * @public\n * @experimental\n * Content manager context hooks for plugin development.\n * Make sure to use this hook inside the content manager.\n */\nconst useContentManagerContext = () => {\n const {\n collectionType,\n model,\n id,\n components,\n isLoading: isLoadingDoc,\n schema,\n schemas,\n } = useDoc();\n\n const layout = useDocumentLayout(model);\n\n const form = useForm<unknown>('useContentManagerContext', (state) => state);\n\n const isSingleType = collectionType === SINGLE_TYPES;\n const slug = model;\n const isCreatingEntry = id === 'create';\n\n useContentTypeSchema();\n\n const isLoading = isLoadingDoc || layout.isLoading;\n const error = layout.error;\n\n return {\n error,\n isLoading,\n\n // Base metadata\n model,\n collectionType,\n id,\n slug,\n isCreatingEntry,\n isSingleType,\n hasDraftAndPublish: schema?.options?.draftAndPublish ?? false,\n\n // All schema infos\n components,\n contentType: schema,\n contentTypes: schemas,\n\n // Form state\n form,\n\n // layout infos\n layout,\n };\n};\n\nexport { useDocument, useDoc, useContentManagerContext };\nexport type { UseDocument, UseDocumentArgs, Document, Schema, ComponentsDictionary };\n"],"names":["validationSchemaCache","WeakMap","getValidationSchema","schema","components","byComponents","get","set","validationSchema","createYupSchema","attributes","isLocalizedAttribute","attribute","i18nOptions","pluginOptions","i18n","localized","useDocument","args","opts","toggleNotification","useNotification","_unstableFormatAPIError","formatAPIError","useAPIErrorHandler","formatMessage","useIntl","currentData","data","isLoading","isLoadingDocument","isFetching","isFetchingDocument","error","refetch","useGetDocumentQuery","skip","documentId","collectionType","SINGLE_TYPES","document","meta","schemas","isLoadingSchema","useContentTypeSchema","model","isSingleType","kind","getTitle","React","useCallback","mainField","info","displayName","id","defaultMessage","useEffect","type","message","validate","Error","validateSync","abortEarly","strict","ValidationError","getYupValidationErrors","nonLocalizedScalarAndMediaFields","useMemo","Object","keys","filter","name","getInitialFormValues","isCreatingDocument","undefined","transformDocument","form","createDefaultForm","sibling","availableLocales","length","inherited","reduce","acc","hasError","useDoc","slug","origin","useParams","query","useQueryParams","params","buildValidParams","returnId","useContentManagerContext","isLoadingDoc","layout","useDocumentLayout","useForm","state","isCreatingEntry","hasDraftAndPublish","options","draftAndPublish","contentType","contentTypes"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA;AACA;AACA;AACA;AACA,MAAMA,wBAAwB,IAAIC,OAAAA,EAAAA;AAKlC,MAAMC,mBAAAA,GAAsB,CAACC,MAAAA,EAAgBC,UAAAA,GAAAA;IAC3C,IAAIC,YAAAA,GAAeL,qBAAAA,CAAsBM,GAAG,CAACH,MAAAA,CAAAA;AAE7C,IAAA,IAAI,CAACE,YAAAA,EAAc;AACjBA,QAAAA,YAAAA,GAAe,IAAIJ,OAAAA,EAAAA;QACnBD,qBAAAA,CAAsBO,GAAG,CAACJ,MAAAA,EAAQE,YAAAA,CAAAA;AACpC,IAAA;IAEA,IAAIG,gBAAAA,GAAmBH,YAAAA,CAAaC,GAAG,CAACF,UAAAA,CAAAA;AAExC,IAAA,IAAI,CAACI,gBAAAA,EAAkB;QACrBA,gBAAAA,GAAmBC,0BAAAA,CAAgBN,MAAAA,CAAOO,UAAU,EAAEN,UAAAA,CAAAA;QACtDC,YAAAA,CAAaE,GAAG,CAACH,UAAAA,EAAYI,gBAAAA,CAAAA;AAC/B,IAAA;IAEA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AA,UAAAA;QACAoG,WAAAA,EAAarG,MAAAA;QACbsG,YAAAA,EAAc/D,OAAAA;;AAGdkC,QAAAA,IAAAA;;AAGAoB,QAAAA;AACF,KAAA;AACF;;;;;;"}
|
|
@@ -12,6 +12,24 @@ import { createYupSchema } from '../utils/validation.mjs';
|
|
|
12
12
|
import { useContentTypeSchema } from './useContentTypeSchema.mjs';
|
|
13
13
|
import { useDocumentLayout } from './useDocumentLayout.mjs';
|
|
14
14
|
|
|
15
|
+
// Building the yup schema of a model clones a schema for every nested component and dynamic
|
|
16
|
+
// zone: on large models it takes seconds and gigabytes. `schema` and `components` identities
|
|
17
|
+
// are shared across hook instances (see `useContentTypeSchema`), so build it once per pair,
|
|
18
|
+
// and only when something actually validates.
|
|
19
|
+
const validationSchemaCache = new WeakMap();
|
|
20
|
+
const getValidationSchema = (schema, components)=>{
|
|
21
|
+
let byComponents = validationSchemaCache.get(schema);
|
|
22
|
+
if (!byComponents) {
|
|
23
|
+
byComponents = new WeakMap();
|
|
24
|
+
validationSchemaCache.set(schema, byComponents);
|
|
25
|
+
}
|
|
26
|
+
let validationSchema = byComponents.get(components);
|
|
27
|
+
if (!validationSchema) {
|
|
28
|
+
validationSchema = createYupSchema(schema.attributes, components);
|
|
29
|
+
byComponents.set(components, validationSchema);
|
|
30
|
+
}
|
|
31
|
+
return validationSchema;
|
|
32
|
+
};
|
|
15
33
|
/**
|
|
16
34
|
* Mirrors the server's `isLocalizedAttribute` in
|
|
17
35
|
* `packages/plugins/i18n/server/src/services/content-types.ts`: an attribute
|
|
@@ -99,19 +117,11 @@ import { useDocumentLayout } from './useDocumentLayout.mjs';
|
|
|
99
117
|
formatAPIError,
|
|
100
118
|
args.collectionType
|
|
101
119
|
]);
|
|
102
|
-
const validationSchema = React.useMemo(()=>{
|
|
103
|
-
if (!schema) {
|
|
104
|
-
return null;
|
|
105
|
-
}
|
|
106
|
-
return createYupSchema(schema.attributes, components);
|
|
107
|
-
}, [
|
|
108
|
-
schema,
|
|
109
|
-
components
|
|
110
|
-
]);
|
|
111
120
|
const validate = React.useCallback((document)=>{
|
|
112
|
-
if (!
|
|
121
|
+
if (!schema) {
|
|
113
122
|
throw new Error('There is no validation schema generated, this is likely due to the schema not being loaded yet.');
|
|
114
123
|
}
|
|
124
|
+
const validationSchema = getValidationSchema(schema, components);
|
|
115
125
|
try {
|
|
116
126
|
validationSchema.validateSync(document, {
|
|
117
127
|
abortEarly: false,
|
|
@@ -125,7 +135,8 @@ import { useDocumentLayout } from './useDocumentLayout.mjs';
|
|
|
125
135
|
throw error;
|
|
126
136
|
}
|
|
127
137
|
}, [
|
|
128
|
-
|
|
138
|
+
schema,
|
|
139
|
+
components
|
|
129
140
|
]);
|
|
130
141
|
/**
|
|
131
142
|
* Schema attributes that should be inherited from a sibling locale when
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDocument.mjs","sources":["../../../admin/src/hooks/useDocument.ts"],"sourcesContent":["/**\n * This hook doesn't use a context provider because we fetch directly from the server,\n * this sounds expensive but actually, it's really not. Because we have redux-toolkit-query\n * being a cache layer so if nothing invalidates the cache, we don't fetch again.\n */\n\nimport * as React from 'react';\n\nimport {\n useNotification,\n useAPIErrorHandler,\n useQueryParams,\n FormErrors,\n getYupValidationErrors,\n useForm,\n} from '@strapi/admin/strapi-admin';\nimport { useIntl } from 'react-intl';\nimport { useParams } from 'react-router-dom';\nimport { ValidationError } from 'yup';\n\nimport { SINGLE_TYPES } from '../constants/collections';\nimport { type AnyData, transformDocument } from '../pages/EditView/utils/data';\nimport { createDefaultForm } from '../pages/EditView/utils/forms';\nimport { useGetDocumentQuery } from '../services/documents';\nimport { buildValidParams } from '../utils/api';\nimport { createYupSchema } from '../utils/validation';\n\nimport { useContentTypeSchema, ComponentsDictionary } from './useContentTypeSchema';\nimport { useDocumentLayout } from './useDocumentLayout';\n\nimport type { FindOne } from '../../../shared/contracts/collection-types';\nimport type { ContentType } from '../../../shared/contracts/content-types';\nimport type { Modules } from '@strapi/types';\n\ninterface UseDocumentArgs {\n collectionType: string;\n model: string;\n documentId?: string;\n params?: object;\n}\n\ntype UseDocumentOpts = Parameters<typeof useGetDocumentQuery>[1];\n\ntype Document = FindOne.Response['data'];\n\ntype Schema = ContentType;\n\ntype UseDocument = (\n args: UseDocumentArgs,\n opts?: UseDocumentOpts\n) => {\n /**\n * These are the schemas of the components used in the content type, organised\n * by their uid.\n */\n components: ComponentsDictionary;\n document?: Document;\n meta?: FindOne.Response['meta'];\n isLoading: boolean;\n /**\n * This is the schema of the content type, it is not the same as the layout.\n */\n schema?: Schema;\n schemas?: Schema[];\n hasError?: boolean;\n refetch: () => void;\n validate: (document: Document) => null | FormErrors;\n /**\n * Get the document's title\n */\n getTitle: (mainField: string) => string;\n /**\n * Get the initial form values for the document\n */\n getInitialFormValues: (isCreatingDocument?: boolean) => AnyData | undefined;\n};\n\n/**\n * Mirrors the server's `isLocalizedAttribute` in\n * `packages/plugins/i18n/server/src/services/content-types.ts`: an attribute\n * counts as localized only when `pluginOptions.i18n.localized` is explicitly\n * `true`. Both `false` and `undefined` mean \"non-localized\" — important here\n * because attributes created without the i18n plugin omit the field entirely,\n * and we still want them inherited when creating a new locale draft.\n */\nconst isLocalizedAttribute = (attribute: { pluginOptions?: object }): boolean => {\n // `pluginOptions` on the base attribute is typed as `object`, so we have to\n // narrow it to the i18n-specific shape here.\n const i18nOptions = attribute.pluginOptions as { i18n?: { localized?: boolean } } | undefined;\n return i18nOptions?.i18n?.localized === true;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocument\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @alpha\n * @public\n * @description Returns a document based on the model, collection type & id passed as arguments.\n * Also extracts its schema from the redux cache to be used for creating a validation schema.\n * @example\n * ```tsx\n * const { id, model, collectionType } = useParams<{ id: string; model: string; collectionType: string }>();\n *\n * if(!model || !collectionType) return null;\n *\n * const { document, isLoading, validate } = useDocument({ documentId: id, model, collectionType, params: { locale: 'en-GB' } })\n * const { update } = useDocumentActions()\n *\n * const onSubmit = async (document: Document) => {\n * const errors = validate(document);\n *\n * if(errors) {\n * // handle errors\n * }\n *\n * await update({ collectionType, model, id }, document)\n * }\n * ```\n *\n */\nconst useDocument: UseDocument = (args, opts) => {\n const { toggleNotification } = useNotification();\n const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();\n const { formatMessage } = useIntl();\n\n const {\n currentData: data,\n isLoading: isLoadingDocument,\n isFetching: isFetchingDocument,\n error,\n refetch,\n } = useGetDocumentQuery(args, {\n ...opts,\n skip: (!args.documentId && args.collectionType !== SINGLE_TYPES) || opts?.skip,\n });\n const document = data?.data;\n const meta = data?.meta;\n\n const {\n components,\n schema,\n schemas,\n isLoading: isLoadingSchema,\n } = useContentTypeSchema(args.model);\n const isSingleType = schema?.kind === 'singleType';\n\n const getTitle = React.useCallback(\n (mainField: string) => {\n // Always use mainField if it's not an id\n if (mainField !== 'id' && document?.[mainField]) {\n return document[mainField];\n }\n\n // When it's a singleType without a mainField, use the contentType displayName\n if (schema?.kind === 'singleType' && schema.info.displayName) {\n return formatMessage({\n id: schema.info.displayName,\n defaultMessage: schema.info.displayName,\n });\n }\n\n // Otherwise, use a fallback\n return formatMessage({\n id: 'content-manager.containers.untitled',\n defaultMessage: 'Untitled',\n });\n },\n [document, formatMessage, schema]\n );\n\n React.useEffect(() => {\n if (error) {\n toggleNotification({\n type: 'danger',\n message: formatAPIError(error),\n });\n }\n }, [toggleNotification, error, formatAPIError, args.collectionType]);\n\n const validationSchema = React.useMemo(() => {\n if (!schema) {\n return null;\n }\n\n return createYupSchema(schema.attributes, components);\n }, [schema, components]);\n\n const validate = React.useCallback(\n (document: Modules.Documents.AnyDocument): FormErrors | null => {\n if (!validationSchema) {\n throw new Error(\n 'There is no validation schema generated, this is likely due to the schema not being loaded yet.'\n );\n }\n\n try {\n validationSchema.validateSync(document, { abortEarly: false, strict: true });\n return null;\n } catch (error) {\n if (error instanceof ValidationError) {\n return getYupValidationErrors(error);\n }\n\n throw error;\n }\n },\n [validationSchema]\n );\n\n /**\n * Schema attributes that should be inherited from a sibling locale when\n * creating a new locale draft.\n *\n * Scope intentionally matches what the server populates into\n * `meta.availableLocales` (see `packages/core/content-manager/server/src/services/document-metadata.ts`):\n * - non-localized — `isLocalizedAttribute` semantics, so attributes whose\n * `pluginOptions.i18n.localized` is `undefined` count as non-localized\n * (an attribute created without the i18n plugin has no i18n options at\n * all but is still inherited at save by `copyNonLocalizedFields`).\n * - scalar or media — `component` / `dynamiczone` / `relation` are excluded\n * because the server doesn't populate them in `availableLocales` either,\n * so there'd be nothing to copy from.\n */\n const nonLocalizedScalarAndMediaFields = React.useMemo(() => {\n if (!schema?.attributes) {\n return [];\n }\n\n return Object.keys(schema.attributes).filter((name) => {\n const attribute = schema.attributes[name];\n\n if (isLocalizedAttribute(attribute)) {\n return false;\n }\n\n return (\n attribute.type !== 'component' &&\n attribute.type !== 'dynamiczone' &&\n attribute.type !== 'relation'\n );\n });\n }, [schema]);\n\n /**\n * Here we prepare the form for editing, we need to:\n * - remove prohibited fields from the document (passwords | ADD YOURS WHEN THERES A NEW ONE)\n * - swap out count objects on relations for empty arrays\n * - set __temp_key__ on array objects for drag & drop\n *\n * We also prepare the form for new documents, so we need to:\n * - set default values on fields\n * - inherit non-localized scalar/media values from a sibling locale.\n * Scope is intentionally limited to scalars and media — that is exactly\n * what the server populates into `meta.availableLocales` (see\n * `packages/core/content-manager/server/src/services/document-metadata.ts`).\n * Components, dynamic zones, and relations are not in that payload; the\n * server fills them at save time via `copyNonLocalizedFields` (in\n * `packages/core/core/src/services/document-service/internationalization.ts`)\n * when the new locale row is first created.\n * Baking the inheritance into `initialValues` here is what lets it survive\n * `<Form>` re-inits: the `SET_INITIAL_VALUES` effect in\n * `packages/core/admin/admin/src/components/Form.tsx` re-applies these\n * values whenever `initialValues` changes (e.g. after a locale switch),\n * which the previous side-effect-based prefill in `LocalePickerAction`\n * could not survive on revisits.\n */\n const getInitialFormValues = React.useCallback(\n (isCreatingDocument: boolean = false) => {\n if ((!document && !isCreatingDocument && !isSingleType) || !schema) {\n return undefined;\n }\n\n /**\n * Check that we have an ID so we know the\n * document has been created in some way.\n */\n if (document?.id) {\n return transformDocument(schema, components)(document);\n }\n\n let form: AnyData = createDefaultForm(schema, components);\n\n // Intentionally use `availableLocales[0]`:\n // - The server sorts `getAvailableLocales` with the default locale first\n // (see `document-metadata.ts`), so index 0 is the canonical inheritance\n // source. Sibling locales can drift on non-localized fields because the\n // server only syncs them at locale-creation time, not on subsequent\n // updates — preferring the default keeps the surfaced values stable.\n // - Avoids coupling this hook to `useGetLocalesQuery` just to find the\n // default locale.\n const sibling = meta?.availableLocales?.[0] as Record<string, unknown> | undefined;\n if (sibling && nonLocalizedScalarAndMediaFields.length > 0) {\n const inherited = nonLocalizedScalarAndMediaFields.reduce<AnyData>((acc, name) => {\n if (name in sibling) {\n acc[name] = sibling[name];\n }\n return acc;\n }, {});\n\n form = { ...form, ...inherited };\n }\n\n return transformDocument(schema, components)(form);\n },\n [\n document,\n isSingleType,\n schema,\n components,\n meta?.availableLocales,\n nonLocalizedScalarAndMediaFields,\n ]\n );\n\n const isLoading = isLoadingDocument || isFetchingDocument || isLoadingSchema;\n const hasError = !!error;\n\n return React.useMemo(\n () =>\n ({\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n }) satisfies ReturnType<UseDocument>,\n [\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n ]\n );\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDoc\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal this hook uses the router to extract the model, collection type & id from the url.\n * therefore, it shouldn't be used outside of the content-manager because it won't work as intended.\n */\nconst useDoc = (opts?: UseDocumentOpts) => {\n const { id, slug, collectionType, origin } = useParams<{\n id: string;\n origin: string;\n slug: string;\n collectionType: string;\n }>();\n const [{ query }] = useQueryParams();\n const params = React.useMemo(() => buildValidParams(query), [query]);\n\n if (!collectionType) {\n throw new Error('Could not find collectionType in url params');\n }\n\n if (!slug) {\n throw new Error('Could not find model in url params');\n }\n\n const document = useDocument(\n { documentId: origin || id, model: slug, collectionType, params },\n {\n ...opts,\n skip: id === 'create' || (!origin && !id && collectionType !== SINGLE_TYPES) || opts?.skip,\n }\n );\n\n const returnId = origin || (id === 'create' ? undefined : id);\n\n return {\n collectionType,\n model: slug,\n id: returnId,\n ...document,\n };\n};\n\n/**\n * @public\n * @experimental\n * Content manager context hooks for plugin development.\n * Make sure to use this hook inside the content manager.\n */\nconst useContentManagerContext = () => {\n const {\n collectionType,\n model,\n id,\n components,\n isLoading: isLoadingDoc,\n schema,\n schemas,\n } = useDoc();\n\n const layout = useDocumentLayout(model);\n\n const form = useForm<unknown>('useContentManagerContext', (state) => state);\n\n const isSingleType = collectionType === SINGLE_TYPES;\n const slug = model;\n const isCreatingEntry = id === 'create';\n\n useContentTypeSchema();\n\n const isLoading = isLoadingDoc || layout.isLoading;\n const error = layout.error;\n\n return {\n error,\n isLoading,\n\n // Base metadata\n model,\n collectionType,\n id,\n slug,\n isCreatingEntry,\n isSingleType,\n hasDraftAndPublish: schema?.options?.draftAndPublish ?? false,\n\n // All schema infos\n components,\n contentType: schema,\n contentTypes: schemas,\n\n // Form state\n form,\n\n // layout infos\n layout,\n };\n};\n\nexport { useDocument, useDoc, useContentManagerContext };\nexport type { UseDocument, UseDocumentArgs, Document, Schema, ComponentsDictionary };\n"],"names":["isLocalizedAttribute","attribute","i18nOptions","pluginOptions","i18n","localized","useDocument","args","opts","toggleNotification","useNotification","_unstableFormatAPIError","formatAPIError","useAPIErrorHandler","formatMessage","useIntl","currentData","data","isLoading","isLoadingDocument","isFetching","isFetchingDocument","error","refetch","useGetDocumentQuery","skip","documentId","collectionType","SINGLE_TYPES","document","meta","components","schema","schemas","isLoadingSchema","useContentTypeSchema","model","isSingleType","kind","getTitle","React","useCallback","mainField","info","displayName","id","defaultMessage","useEffect","type","message","validationSchema","useMemo","createYupSchema","attributes","validate","Error","validateSync","abortEarly","strict","ValidationError","getYupValidationErrors","nonLocalizedScalarAndMediaFields","Object","keys","filter","name","getInitialFormValues","isCreatingDocument","undefined","transformDocument","form","createDefaultForm","sibling","availableLocales","length","inherited","reduce","acc","hasError","useDoc","slug","origin","useParams","query","useQueryParams","params","buildValidParams","returnId","useContentManagerContext","isLoadingDoc","layout","useDocumentLayout","useForm","state","isCreatingEntry","hasDraftAndPublish","options","draftAndPublish","contentType","contentTypes"],"mappings":";;;;;;;;;;;;;;AA6EA;;;;;;;IAQA,MAAMA,uBAAuB,CAACC,SAAAA,GAAAA;;;IAG5B,MAAMC,WAAAA,GAAcD,UAAUE,aAAa;IAC3C,OAAOD,WAAAA,EAAaE,MAAMC,SAAAA,KAAc,IAAA;AAC1C,CAAA;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA8BA,MAAMC,WAAAA,GAA2B,CAACC,IAAAA,EAAMC,IAAAA,GAAAA;IACtC,MAAM,EAAEC,kBAAkB,EAAE,GAAGC,eAAAA,EAAAA;AAC/B,IAAA,MAAM,EAAEC,uBAAAA,EAAyBC,cAAc,EAAE,GAAGC,kBAAAA,EAAAA;IACpD,MAAM,EAAEC,aAAa,EAAE,GAAGC,OAAAA,EAAAA;AAE1B,IAAA,MAAM,EACJC,WAAAA,EAAaC,IAAI,EACjBC,SAAAA,EAAWC,iBAAiB,EAC5BC,UAAAA,EAAYC,kBAAkB,EAC9BC,KAAK,EACLC,OAAO,EACR,GAAGC,oBAAoBjB,IAAAA,EAAM;AAC5B,QAAA,GAAGC,IAAI;QACPiB,IAAAA,EAAO,CAAClB,IAAAA,CAAKmB,UAAU,IAAInB,IAAAA,CAAKoB,cAAc,KAAKC,YAAAA,IAAiBpB,IAAAA,EAAMiB;AAC5E,KAAA,CAAA;AACA,IAAA,MAAMI,WAAWZ,IAAAA,EAAMA,IAAAA;AACvB,IAAA,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C,IAAA,MAAMoD,IAAAA,GAAO5C,KAAAA;AACb,IAAA,MAAM0D,kBAAkBjD,EAAAA,KAAO,QAAA;AAE/BV,IAAAA,oBAAAA,EAAAA;IAEA,MAAMjB,SAAAA,GAAYuE,YAAAA,IAAgBC,MAAAA,CAAOxE,SAAS;IAClD,MAAMI,KAAAA,GAAQoE,OAAOpE,KAAK;IAE1B,OAAO;AACLA,QAAAA,KAAAA;AACAJ,QAAAA,SAAAA;;AAGAkB,QAAAA,KAAAA;AACAT,QAAAA,cAAAA;AACAkB,QAAAA,EAAAA;AACAmC,QAAAA,IAAAA;AACAc,QAAAA,eAAAA;AACAzD,QAAAA,YAAAA;QACA0D,kBAAAA,EAAoB/D,MAAAA,EAAQgE,SAASC,eAAAA,IAAmB,KAAA;;AAGxDlE,QAAAA,UAAAA;QACAmE,WAAAA,EAAalE,MAAAA;QACbmE,YAAAA,EAAclE,OAAAA;;AAGdqC,QAAAA,IAAAA;;AAGAoB,QAAAA;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"useDocument.mjs","sources":["../../../admin/src/hooks/useDocument.ts"],"sourcesContent":["/**\n * This hook doesn't use a context provider because we fetch directly from the server,\n * this sounds expensive but actually, it's really not. Because we have redux-toolkit-query\n * being a cache layer so if nothing invalidates the cache, we don't fetch again.\n *\n * The network is deduplicated, but the work done inside the hook is not: it can be mounted\n * by hundreds of fields at once, so anything expensive it derives must be cached outside of\n * the hook instance (see `getValidationSchema`).\n */\n\nimport * as React from 'react';\n\nimport {\n useNotification,\n useAPIErrorHandler,\n useQueryParams,\n FormErrors,\n getYupValidationErrors,\n useForm,\n} from '@strapi/admin/strapi-admin';\nimport { useIntl } from 'react-intl';\nimport { useParams } from 'react-router-dom';\nimport { ValidationError } from 'yup';\n\nimport { SINGLE_TYPES } from '../constants/collections';\nimport { type AnyData, transformDocument } from '../pages/EditView/utils/data';\nimport { createDefaultForm } from '../pages/EditView/utils/forms';\nimport { useGetDocumentQuery } from '../services/documents';\nimport { buildValidParams } from '../utils/api';\nimport { createYupSchema } from '../utils/validation';\n\nimport { useContentTypeSchema, ComponentsDictionary } from './useContentTypeSchema';\nimport { useDocumentLayout } from './useDocumentLayout';\n\nimport type { FindOne } from '../../../shared/contracts/collection-types';\nimport type { ContentType } from '../../../shared/contracts/content-types';\nimport type { Modules } from '@strapi/types';\n\ninterface UseDocumentArgs {\n collectionType: string;\n model: string;\n documentId?: string;\n params?: object;\n}\n\ntype UseDocumentOpts = Parameters<typeof useGetDocumentQuery>[1];\n\ntype Document = FindOne.Response['data'];\n\ntype Schema = ContentType;\n\ntype ValidationSchema = ReturnType<typeof createYupSchema>;\n\n// Building the yup schema of a model clones a schema for every nested component and dynamic\n// zone: on large models it takes seconds and gigabytes. `schema` and `components` identities\n// are shared across hook instances (see `useContentTypeSchema`), so build it once per pair,\n// and only when something actually validates.\nconst validationSchemaCache = new WeakMap<\n Schema,\n WeakMap<ComponentsDictionary, ValidationSchema>\n>();\n\nconst getValidationSchema = (schema: Schema, components: ComponentsDictionary) => {\n let byComponents = validationSchemaCache.get(schema);\n\n if (!byComponents) {\n byComponents = new WeakMap();\n validationSchemaCache.set(schema, byComponents);\n }\n\n let validationSchema = byComponents.get(components);\n\n if (!validationSchema) {\n validationSchema = createYupSchema(schema.attributes, components);\n byComponents.set(components, validationSchema);\n }\n\n return validationSchema;\n};\n\ntype UseDocument = (\n args: UseDocumentArgs,\n opts?: UseDocumentOpts\n) => {\n /**\n * These are the schemas of the components used in the content type, organised\n * by their uid.\n */\n components: ComponentsDictionary;\n document?: Document;\n meta?: FindOne.Response['meta'];\n isLoading: boolean;\n /**\n * This is the schema of the content type, it is not the same as the layout.\n */\n schema?: Schema;\n schemas?: Schema[];\n hasError?: boolean;\n refetch: () => void;\n validate: (document: Document) => null | FormErrors;\n /**\n * Get the document's title\n */\n getTitle: (mainField: string) => string;\n /**\n * Get the initial form values for the document\n */\n getInitialFormValues: (isCreatingDocument?: boolean) => AnyData | undefined;\n};\n\n/**\n * Mirrors the server's `isLocalizedAttribute` in\n * `packages/plugins/i18n/server/src/services/content-types.ts`: an attribute\n * counts as localized only when `pluginOptions.i18n.localized` is explicitly\n * `true`. Both `false` and `undefined` mean \"non-localized\" — important here\n * because attributes created without the i18n plugin omit the field entirely,\n * and we still want them inherited when creating a new locale draft.\n */\nconst isLocalizedAttribute = (attribute: { pluginOptions?: object }): boolean => {\n // `pluginOptions` on the base attribute is typed as `object`, so we have to\n // narrow it to the i18n-specific shape here.\n const i18nOptions = attribute.pluginOptions as { i18n?: { localized?: boolean } } | undefined;\n return i18nOptions?.i18n?.localized === true;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocument\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @alpha\n * @public\n * @description Returns a document based on the model, collection type & id passed as arguments.\n * Also extracts its schema from the redux cache to be used for creating a validation schema.\n * @example\n * ```tsx\n * const { id, model, collectionType } = useParams<{ id: string; model: string; collectionType: string }>();\n *\n * if(!model || !collectionType) return null;\n *\n * const { document, isLoading, validate } = useDocument({ documentId: id, model, collectionType, params: { locale: 'en-GB' } })\n * const { update } = useDocumentActions()\n *\n * const onSubmit = async (document: Document) => {\n * const errors = validate(document);\n *\n * if(errors) {\n * // handle errors\n * }\n *\n * await update({ collectionType, model, id }, document)\n * }\n * ```\n *\n */\nconst useDocument: UseDocument = (args, opts) => {\n const { toggleNotification } = useNotification();\n const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();\n const { formatMessage } = useIntl();\n\n const {\n currentData: data,\n isLoading: isLoadingDocument,\n isFetching: isFetchingDocument,\n error,\n refetch,\n } = useGetDocumentQuery(args, {\n ...opts,\n skip: (!args.documentId && args.collectionType !== SINGLE_TYPES) || opts?.skip,\n });\n const document = data?.data;\n const meta = data?.meta;\n\n const {\n components,\n schema,\n schemas,\n isLoading: isLoadingSchema,\n } = useContentTypeSchema(args.model);\n const isSingleType = schema?.kind === 'singleType';\n\n const getTitle = React.useCallback(\n (mainField: string) => {\n // Always use mainField if it's not an id\n if (mainField !== 'id' && document?.[mainField]) {\n return document[mainField];\n }\n\n // When it's a singleType without a mainField, use the contentType displayName\n if (schema?.kind === 'singleType' && schema.info.displayName) {\n return formatMessage({\n id: schema.info.displayName,\n defaultMessage: schema.info.displayName,\n });\n }\n\n // Otherwise, use a fallback\n return formatMessage({\n id: 'content-manager.containers.untitled',\n defaultMessage: 'Untitled',\n });\n },\n [document, formatMessage, schema]\n );\n\n React.useEffect(() => {\n if (error) {\n toggleNotification({\n type: 'danger',\n message: formatAPIError(error),\n });\n }\n }, [toggleNotification, error, formatAPIError, args.collectionType]);\n\n const validate = React.useCallback(\n (document: Modules.Documents.AnyDocument): FormErrors | null => {\n if (!schema) {\n throw new Error(\n 'There is no validation schema generated, this is likely due to the schema not being loaded yet.'\n );\n }\n\n const validationSchema = getValidationSchema(schema, components);\n\n try {\n validationSchema.validateSync(document, { abortEarly: false, strict: true });\n return null;\n } catch (error) {\n if (error instanceof ValidationError) {\n return getYupValidationErrors(error);\n }\n\n throw error;\n }\n },\n [schema, components]\n );\n\n /**\n * Schema attributes that should be inherited from a sibling locale when\n * creating a new locale draft.\n *\n * Scope intentionally matches what the server populates into\n * `meta.availableLocales` (see `packages/core/content-manager/server/src/services/document-metadata.ts`):\n * - non-localized — `isLocalizedAttribute` semantics, so attributes whose\n * `pluginOptions.i18n.localized` is `undefined` count as non-localized\n * (an attribute created without the i18n plugin has no i18n options at\n * all but is still inherited at save by `copyNonLocalizedFields`).\n * - scalar or media — `component` / `dynamiczone` / `relation` are excluded\n * because the server doesn't populate them in `availableLocales` either,\n * so there'd be nothing to copy from.\n */\n const nonLocalizedScalarAndMediaFields = React.useMemo(() => {\n if (!schema?.attributes) {\n return [];\n }\n\n return Object.keys(schema.attributes).filter((name) => {\n const attribute = schema.attributes[name];\n\n if (isLocalizedAttribute(attribute)) {\n return false;\n }\n\n return (\n attribute.type !== 'component' &&\n attribute.type !== 'dynamiczone' &&\n attribute.type !== 'relation'\n );\n });\n }, [schema]);\n\n /**\n * Here we prepare the form for editing, we need to:\n * - remove prohibited fields from the document (passwords | ADD YOURS WHEN THERES A NEW ONE)\n * - swap out count objects on relations for empty arrays\n * - set __temp_key__ on array objects for drag & drop\n *\n * We also prepare the form for new documents, so we need to:\n * - set default values on fields\n * - inherit non-localized scalar/media values from a sibling locale.\n * Scope is intentionally limited to scalars and media — that is exactly\n * what the server populates into `meta.availableLocales` (see\n * `packages/core/content-manager/server/src/services/document-metadata.ts`).\n * Components, dynamic zones, and relations are not in that payload; the\n * server fills them at save time via `copyNonLocalizedFields` (in\n * `packages/core/core/src/services/document-service/internationalization.ts`)\n * when the new locale row is first created.\n * Baking the inheritance into `initialValues` here is what lets it survive\n * `<Form>` re-inits: the `SET_INITIAL_VALUES` effect in\n * `packages/core/admin/admin/src/components/Form.tsx` re-applies these\n * values whenever `initialValues` changes (e.g. after a locale switch),\n * which the previous side-effect-based prefill in `LocalePickerAction`\n * could not survive on revisits.\n */\n const getInitialFormValues = React.useCallback(\n (isCreatingDocument: boolean = false) => {\n if ((!document && !isCreatingDocument && !isSingleType) || !schema) {\n return undefined;\n }\n\n /**\n * Check that we have an ID so we know the\n * document has been created in some way.\n */\n if (document?.id) {\n return transformDocument(schema, components)(document);\n }\n\n let form: AnyData = createDefaultForm(schema, components);\n\n // Intentionally use `availableLocales[0]`:\n // - The server sorts `getAvailableLocales` with the default locale first\n // (see `document-metadata.ts`), so index 0 is the canonical inheritance\n // source. Sibling locales can drift on non-localized fields because the\n // server only syncs them at locale-creation time, not on subsequent\n // updates — preferring the default keeps the surfaced values stable.\n // - Avoids coupling this hook to `useGetLocalesQuery` just to find the\n // default locale.\n const sibling = meta?.availableLocales?.[0] as Record<string, unknown> | undefined;\n if (sibling && nonLocalizedScalarAndMediaFields.length > 0) {\n const inherited = nonLocalizedScalarAndMediaFields.reduce<AnyData>((acc, name) => {\n if (name in sibling) {\n acc[name] = sibling[name];\n }\n return acc;\n }, {});\n\n form = { ...form, ...inherited };\n }\n\n return transformDocument(schema, components)(form);\n },\n [\n document,\n isSingleType,\n schema,\n components,\n meta?.availableLocales,\n nonLocalizedScalarAndMediaFields,\n ]\n );\n\n const isLoading = isLoadingDocument || isFetchingDocument || isLoadingSchema;\n const hasError = !!error;\n\n return React.useMemo(\n () =>\n ({\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n }) satisfies ReturnType<UseDocument>,\n [\n components,\n document,\n meta,\n isLoading,\n hasError,\n schema,\n schemas,\n validate,\n getTitle,\n getInitialFormValues,\n refetch,\n ]\n );\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDoc\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal this hook uses the router to extract the model, collection type & id from the url.\n * therefore, it shouldn't be used outside of the content-manager because it won't work as intended.\n */\nconst useDoc = (opts?: UseDocumentOpts) => {\n const { id, slug, collectionType, origin } = useParams<{\n id: string;\n origin: string;\n slug: string;\n collectionType: string;\n }>();\n const [{ query }] = useQueryParams();\n const params = React.useMemo(() => buildValidParams(query), [query]);\n\n if (!collectionType) {\n throw new Error('Could not find collectionType in url params');\n }\n\n if (!slug) {\n throw new Error('Could not find model in url params');\n }\n\n const document = useDocument(\n { documentId: origin || id, model: slug, collectionType, params },\n {\n ...opts,\n skip: id === 'create' || (!origin && !id && collectionType !== SINGLE_TYPES) || opts?.skip,\n }\n );\n\n const returnId = origin || (id === 'create' ? undefined : id);\n\n return {\n collectionType,\n model: slug,\n id: returnId,\n ...document,\n };\n};\n\n/**\n * @public\n * @experimental\n * Content manager context hooks for plugin development.\n * Make sure to use this hook inside the content manager.\n */\nconst useContentManagerContext = () => {\n const {\n collectionType,\n model,\n id,\n components,\n isLoading: isLoadingDoc,\n schema,\n schemas,\n } = useDoc();\n\n const layout = useDocumentLayout(model);\n\n const form = useForm<unknown>('useContentManagerContext', (state) => state);\n\n const isSingleType = collectionType === SINGLE_TYPES;\n const slug = model;\n const isCreatingEntry = id === 'create';\n\n useContentTypeSchema();\n\n const isLoading = isLoadingDoc || layout.isLoading;\n const error = layout.error;\n\n return {\n error,\n isLoading,\n\n // Base metadata\n model,\n collectionType,\n id,\n slug,\n isCreatingEntry,\n isSingleType,\n hasDraftAndPublish: schema?.options?.draftAndPublish ?? false,\n\n // All schema infos\n components,\n contentType: schema,\n contentTypes: schemas,\n\n // Form state\n form,\n\n // layout infos\n layout,\n };\n};\n\nexport { useDocument, useDoc, useContentManagerContext };\nexport type { UseDocument, UseDocumentArgs, Document, Schema, ComponentsDictionary };\n"],"names":["validationSchemaCache","WeakMap","getValidationSchema","schema","components","byComponents","get","set","validationSchema","createYupSchema","attributes","isLocalizedAttribute","attribute","i18nOptions","pluginOptions","i18n","localized","useDocument","args","opts","toggleNotification","useNotification","_unstableFormatAPIError","formatAPIError","useAPIErrorHandler","formatMessage","useIntl","currentData","data","isLoading","isLoadingDocument","isFetching","isFetchingDocument","error","refetch","useGetDocumentQuery","skip","documentId","collectionType","SINGLE_TYPES","document","meta","schemas","isLoadingSchema","useContentTypeSchema","model","isSingleType","kind","getTitle","React","useCallback","mainField","info","displayName","id","defaultMessage","useEffect","type","message","validate","Error","validateSync","abortEarly","strict","ValidationError","getYupValidationErrors","nonLocalizedScalarAndMediaFields","useMemo","Object","keys","filter","name","getInitialFormValues","isCreatingDocument","undefined","transformDocument","form","createDefaultForm","sibling","availableLocales","length","inherited","reduce","acc","hasError","useDoc","slug","origin","useParams","query","useQueryParams","params","buildValidParams","returnId","useContentManagerContext","isLoadingDoc","layout","useDocumentLayout","useForm","state","isCreatingEntry","hasDraftAndPublish","options","draftAndPublish","contentType","contentTypes"],"mappings":";;;;;;;;;;;;;;AAqDA;AACA;AACA;AACA;AACA,MAAMA,wBAAwB,IAAIC,OAAAA,EAAAA;AAKlC,MAAMC,mBAAAA,GAAsB,CAACC,MAAAA,EAAgBC,UAAAA,GAAAA;IAC3C,IAAIC,YAAAA,GAAeL,qBAAAA,CAAsBM,GAAG,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MuD,kBAAkB9C,EAAAA,KAAO,QAAA;AAE/BV,IAAAA,oBAAAA,EAAAA;IAEA,MAAMf,SAAAA,GAAYkE,YAAAA,IAAgBC,MAAAA,CAAOnE,SAAS;IAClD,MAAMI,KAAAA,GAAQ+D,OAAO/D,KAAK;IAE1B,OAAO;AACLA,QAAAA,KAAAA;AACAJ,QAAAA,SAAAA;;AAGAgB,QAAAA,KAAAA;AACAP,QAAAA,cAAAA;AACAgB,QAAAA,EAAAA;AACAgC,QAAAA,IAAAA;AACAc,QAAAA,eAAAA;AACAtD,QAAAA,YAAAA;QACAuD,kBAAAA,EAAoBlG,MAAAA,EAAQmG,SAASC,eAAAA,IAAmB,KAAA;;AAGxDnG,QAAAA,UAAAA;QACAoG,WAAAA,EAAarG,MAAAA;QACbsG,YAAAA,EAAc/D,OAAAA;;AAGdkC,QAAAA,IAAAA;;AAGAoB,QAAAA;AACF,KAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDocumentLayout.js","sources":["../../../admin/src/hooks/useDocumentLayout.ts"],"sourcesContent":["import * as React from 'react';\n\nimport { SerializedError } from '@reduxjs/toolkit';\nimport {\n useNotification,\n useStrapiApp,\n useAPIErrorHandler,\n useQueryParams,\n} from '@strapi/admin/strapi-admin';\n\nimport { HOOKS } from '../constants/hooks';\nimport { useGetContentTypeConfigurationQuery } from '../services/contentTypes';\nimport { BaseQueryError } from '../utils/api';\nimport { getMainField } from '../utils/attributes';\nimport { normalizeContentManagerLayout } from '../utils/layouts/normalizeContentManagerLayout';\n\nimport { useContentTypeSchema } from './useContentTypeSchema';\nimport {\n type ComponentsDictionary,\n type Document,\n type Schema,\n useDoc,\n useDocument,\n} from './useDocument';\n\nimport type { ComponentConfiguration } from '../../../shared/contracts/components';\nimport type {\n Metadatas,\n FindContentTypeConfiguration,\n Settings,\n} from '../../../shared/contracts/content-types';\nimport type { Filters, InputProps, Table } from '@strapi/admin/strapi-admin';\nimport type { Schema as SchemaUtils } from '@strapi/types';\n\ntype LayoutOptions = Schema['options'] & Schema['pluginOptions'] & object;\n\ninterface LayoutSettings extends Settings {\n displayName?: string;\n icon?: never;\n}\n\ninterface ListFieldLayout\n extends Table.Header<Document, ListFieldLayout>, Pick<Filters.Filter, 'mainField'> {\n attribute: SchemaUtils.Attribute.AnyAttribute | { type: 'custom' };\n}\n\ninterface ListLayout {\n layout: ListFieldLayout[];\n components?: never;\n metadatas: {\n [K in keyof Metadatas]: Metadatas[K]['list'];\n };\n options: LayoutOptions;\n settings: LayoutSettings;\n}\ninterface EditFieldSharedProps\n extends Omit<InputProps, 'hint' | 'label' | 'type'>, Pick<Filters.Filter, 'mainField'> {\n hint?: string;\n label: string;\n size: number;\n unique?: boolean;\n visible?: boolean;\n}\n\n/**\n * Map over all the types in Attribute Types and use that to create a union of new types where the attribute type\n * is under the property attribute and the type is under the property type.\n */\ntype EditFieldLayout = {\n [K in SchemaUtils.Attribute.Kind]: EditFieldSharedProps & {\n attribute: Extract<SchemaUtils.Attribute.AnyAttribute, { type: K }>;\n type: K;\n };\n}[SchemaUtils.Attribute.Kind];\n\ninterface EditLayout {\n layout: Array<Array<EditFieldLayout[]>>;\n components: {\n [uid: string]: {\n layout: Array<EditFieldLayout[]>;\n settings: ComponentConfiguration['settings'] & {\n displayName?: string;\n icon?: string;\n };\n };\n };\n metadatas: {\n [K in keyof Metadatas]: Metadatas[K]['edit'];\n };\n options: LayoutOptions;\n settings: LayoutSettings;\n}\n\n/**\n * Data required to resolve `mainField` when converting list column names to field layouts for\n * component and relation attributes; mirrors the fourth and fifth arguments of `formatListLayout`.\n */\ntype ListViewConversionContext = {\n componentConfigurations: FindContentTypeConfiguration.Response['data']['components'];\n componentSchemas: ComponentsDictionary;\n contentTypeSchemas: Schema[];\n};\n\ntype UseDocumentLayout = (model: string) => {\n error?: BaseQueryError | SerializedError;\n isLoading: boolean;\n /**\n * This is the layout for the edit view,\n */\n edit: EditLayout;\n list: ListLayout;\n /**\n * Populated when configuration is loaded; pass into `convertListLayoutToFieldLayouts` with\n * `list.metadatas` when mapping persisted list column names (e.g. custom displayed headers).\n */\n listViewConversionContext: ListViewConversionContext | null;\n};\n\ntype ResolvedLayouts = {\n edit: EditLayout;\n list: ListLayout;\n listViewConversionContext: ListViewConversionContext;\n};\n\ntype ResolvedLayoutCacheEntry = {\n components: ComponentsDictionary;\n data: LayoutData;\n model: string;\n schema?: Schema;\n schemas: Schema[];\n value: ResolvedLayouts;\n};\n\nconst RESOLVED_LAYOUT_CACHE_LIMIT = 25;\n// Module-level cache keeps resolved layout object identities stable across hook instances\n// when RTK Query returns the same schema/configuration references.\nconst resolvedLayoutCache: ResolvedLayoutCacheEntry[] = [];\n\nconst getCachedResolvedLayouts = ({\n components,\n data,\n model,\n schema,\n schemas,\n}: Omit<ResolvedLayoutCacheEntry, 'value'>) => {\n return resolvedLayoutCache.find(\n (entry) =>\n entry.components === components &&\n entry.data === data &&\n entry.model === model &&\n entry.schema === schema &&\n entry.schemas === schemas\n )?.value;\n};\n\nconst setCachedResolvedLayouts = (entry: ResolvedLayoutCacheEntry) => {\n resolvedLayoutCache.unshift(entry);\n\n if (resolvedLayoutCache.length > RESOLVED_LAYOUT_CACHE_LIMIT) {\n resolvedLayoutCache.pop();\n }\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocumentLayout\n * -----------------------------------------------------------------------------------------------*/\n\nconst DEFAULT_SETTINGS = {\n bulkable: false,\n filterable: false,\n searchable: false,\n pagination: false,\n defaultSortBy: '',\n defaultSortOrder: 'asc',\n mainField: 'id',\n pageSize: 10,\n relationOpenMode: 'modal' as const,\n};\n\n/**\n * @alpha\n * @description This hook is used to get the layouts for either the edit view or list view of a specific content-type\n * including the layouts for the components used in the content-type. It also runs the mutation hook waterfall so the data\n * is consistent wherever it is used. It's a light wrapper around the `useDocument` hook, but provides the `skip` option a document\n * is not fetched, however, it does fetch the schemas & components if they do not already exist in the cache.\n *\n * If the fetch fails, it will display a notification to the user.\n *\n * @example\n * ```tsx\n * const { model } = useParams<{ model: string }>();\n * const { edit: { schema: layout } } = useDocumentLayout(model);\n *\n * return layout.map(panel => panel.map(row => row.map(field => <Field.Root {...field} />)))\n * ```\n *\n */\nconst useDocumentLayout: UseDocumentLayout = (model) => {\n const { schema, components } = useDocument({ model, collectionType: '' }, { skip: true });\n const [{ query }] = useQueryParams();\n const runHookWaterfall = useStrapiApp('useDocumentLayout', (state) => state.runHookWaterfall);\n const { toggleNotification } = useNotification();\n const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();\n const { isLoading: isLoadingSchemas, schemas } = useContentTypeSchema();\n\n const {\n currentData: data,\n isLoading: isLoadingConfigs,\n error,\n } = useGetContentTypeConfigurationQuery(model);\n\n const isConfigResolvedForModel = data?.contentType?.uid === model;\n const isLoading = isLoadingSchemas || isLoadingConfigs || (!error && !isConfigResolvedForModel);\n const stableLayoutsByModelRef = React.useRef(\n new Map<\n string,\n {\n edit: EditLayout;\n list: ListLayout;\n listViewConversionContext: ListViewConversionContext | null;\n }\n >()\n );\n\n React.useEffect(() => {\n if (error) {\n toggleNotification({\n type: 'danger',\n message: formatAPIError(error),\n });\n }\n }, [error, formatAPIError, toggleNotification]);\n\n const resolvedLayouts = React.useMemo(() => {\n if (!data || isLoading) {\n return null;\n }\n\n const cachedLayouts = getCachedResolvedLayouts({ components, data, model, schema, schemas });\n\n if (cachedLayouts) {\n return cachedLayouts;\n }\n\n const normalizedData = normalizeContentManagerLayout(data, { schemas, schema, components });\n const edit = formatEditLayout(normalizedData, { schemas, schema, components });\n const list = formatListLayout(normalizedData, { schemas, schema, components });\n const listViewConversionContext: ListViewConversionContext = {\n componentConfigurations: normalizedData.components,\n componentSchemas: components,\n contentTypeSchemas: schemas,\n };\n\n const layouts = { edit, list, listViewConversionContext };\n\n setCachedResolvedLayouts({ components, data, model, schema, schemas, value: layouts });\n\n return layouts;\n }, [data, isLoading, model, schemas, schema, components]);\n\n React.useEffect(() => {\n if (resolvedLayouts) {\n stableLayoutsByModelRef.current.set(model, resolvedLayouts);\n }\n }, [model, resolvedLayouts]);\n\n const stableLayouts = resolvedLayouts ?? stableLayoutsByModelRef.current.get(model) ?? null;\n\n const editLayout = React.useMemo(\n () =>\n stableLayouts?.edit ??\n ({\n layout: [],\n components: {},\n metadatas: {},\n options: {},\n settings: DEFAULT_SETTINGS,\n } as EditLayout),\n [stableLayouts]\n );\n\n const listLayout = React.useMemo(\n () =>\n stableLayouts?.list ??\n ({\n layout: [],\n metadatas: {},\n options: {},\n settings: DEFAULT_SETTINGS,\n } as ListLayout),\n [stableLayouts]\n );\n\n const { layout: edit } = React.useMemo(\n () =>\n runHookWaterfall(HOOKS.MUTATE_EDIT_VIEW_LAYOUT, {\n layout: editLayout,\n query,\n }),\n [editLayout, query, runHookWaterfall]\n );\n\n const listViewConversionContext = stableLayouts?.listViewConversionContext ?? null;\n\n return {\n error,\n isLoading,\n edit,\n list: listLayout,\n listViewConversionContext,\n } satisfies ReturnType<UseDocumentLayout>;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocLayout\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal this hook uses the internal useDoc hook, as such it shouldn't be used outside of the\n * content-manager because it won't work as intended.\n */\nconst useDocLayout = () => {\n const { model } = useDoc();\n return useDocumentLayout(model);\n};\n\n/* -------------------------------------------------------------------------------------------------\n * formatEditLayout\n * -----------------------------------------------------------------------------------------------*/\ntype LayoutData = FindContentTypeConfiguration.Response['data'];\n\n/**\n * @internal\n * @description takes the configuration data, the schema & the components used in the schema and formats the edit view\n * versions of the schema & components. This is then used to render the edit view of the content-type.\n */\nconst formatEditLayout = (\n data: LayoutData,\n {\n schemas,\n schema,\n components,\n }: { schemas: Schema[]; schema?: Schema; components: ComponentsDictionary }\n): EditLayout => {\n let currentPanelIndex = 0;\n /**\n * The fields arranged by the panels, new panels are made for dynamic zones only.\n */\n const panelledEditAttributes = convertEditLayoutToFieldLayouts(\n data.contentType.layouts.edit,\n schema?.attributes,\n data.contentType.metadatas,\n { configurations: data.components, schemas: components },\n schemas\n ).reduce<Array<EditFieldLayout[][]>>((panels, row) => {\n if (row.some((field) => field.type === 'dynamiczone')) {\n panels.push([row]);\n currentPanelIndex += 2;\n } else {\n if (!panels[currentPanelIndex]) {\n panels.push([row]);\n } else {\n panels[currentPanelIndex].push(row);\n }\n }\n\n return panels;\n }, []);\n\n const componentEditAttributes = Object.entries(data.components).reduce<EditLayout['components']>(\n (acc, [uid, configuration]) => {\n const componentSchema = components[uid];\n\n // Persisted configuration can reference component UIDs absent from `/init`.\n if (!componentSchema) {\n return acc;\n }\n\n acc[uid] = {\n layout: convertEditLayoutToFieldLayouts(\n configuration.layouts.edit,\n componentSchema.attributes,\n configuration.metadatas,\n { configurations: data.components, schemas: components }\n ),\n settings: {\n ...configuration.settings,\n icon: componentSchema.info.icon,\n displayName: componentSchema.info.displayName,\n },\n };\n return acc;\n },\n {}\n );\n\n const editMetadatas = Object.entries(data.contentType.metadatas).reduce<EditLayout['metadatas']>(\n (acc, [attribute, metadata]) => {\n return {\n ...acc,\n [attribute]: metadata.edit,\n };\n },\n {}\n );\n\n return {\n layout: panelledEditAttributes,\n components: componentEditAttributes,\n metadatas: editMetadatas,\n settings: {\n ...data.contentType.settings,\n displayName: schema?.info?.displayName,\n },\n options: {\n ...schema?.options,\n ...schema?.pluginOptions,\n ...data.contentType.options,\n },\n };\n};\n\n/* -------------------------------------------------------------------------------------------------\n * convertEditLayoutToFieldLayouts\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description takes the edit layout from either a content-type or a component\n * and formats it into a generic object that can be used to correctly render\n * the form fields.\n */\nconst convertEditLayoutToFieldLayouts = (\n rows: LayoutData['contentType']['layouts']['edit'],\n attributes: Schema['attributes'] = {},\n metadatas: Metadatas,\n components?: {\n configurations: Record<string, ComponentConfiguration>;\n schemas: ComponentsDictionary;\n },\n schemas: Schema[] = []\n) => {\n return rows.map((row) =>\n row\n .map((field) => {\n const attribute = attributes[field.name];\n\n if (!attribute) {\n return null;\n }\n\n const fieldMetadata = metadatas[field.name];\n if (!fieldMetadata) {\n return null;\n }\n\n const { edit: metadata } = fieldMetadata;\n\n const settings: Partial<Settings> =\n attribute.type === 'component' && components\n ? (components.configurations[attribute.component]?.settings ?? {})\n : {};\n\n return {\n attribute,\n disabled: !metadata.editable,\n hint: metadata.description,\n label: metadata.label ?? '',\n name: field.name,\n // @ts-expect-error – mainField does exist on the metadata for a relation.\n mainField: getMainField(attribute, metadata.mainField || settings.mainField, {\n schemas,\n components: components?.schemas ?? {},\n }),\n placeholder: metadata.placeholder ?? '',\n required: attribute.required ?? false,\n size: field.size,\n unique: 'unique' in attribute ? attribute.unique : false,\n visible: metadata.visible ?? true,\n type: attribute.type,\n };\n })\n .filter((field) => field !== null)\n ) as EditFieldLayout[][];\n};\n\n/* -------------------------------------------------------------------------------------------------\n * formatListLayout\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description takes the complete configuration data, the schema & the components used in the schema and\n * formats a list view layout for the content-type. This is much simpler than the edit view layout as there\n * are less options to consider.\n */\nconst formatListLayout = (\n data: LayoutData,\n {\n schemas,\n schema,\n components,\n }: { schemas: Schema[]; schema?: Schema; components: ComponentsDictionary }\n): ListLayout => {\n const listMetadatas = Object.entries(data.contentType.metadatas).reduce<ListLayout['metadatas']>(\n (acc, [attribute, metadata]) => {\n return {\n ...acc,\n [attribute]: metadata.list,\n };\n },\n {}\n );\n /**\n * The fields arranged by the panels, new panels are made for dynamic zones only.\n */\n const listAttributes = convertListLayoutToFieldLayouts(\n data.contentType.layouts.list,\n schema?.attributes,\n listMetadatas,\n { configurations: data.components, schemas: components },\n schemas\n );\n\n return {\n layout: listAttributes,\n settings: { ...data.contentType.settings, displayName: schema?.info?.displayName },\n metadatas: listMetadatas,\n options: {\n ...schema?.options,\n ...schema?.pluginOptions,\n ...data.contentType.options,\n },\n };\n};\n\n/* -------------------------------------------------------------------------------------------------\n * convertListLayoutToFieldLayouts\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description takes the columns from the list view configuration and formats them into a generic object\n * combinining metadata and attribute data.\n *\n * @note We do use this to reformat the list of strings when updating the displayed headers for the list view.\n */\nconst convertListLayoutToFieldLayouts = (\n columns: LayoutData['contentType']['layouts']['list'],\n attributes: Schema['attributes'] = {},\n metadatas: ListLayout['metadatas'],\n components?: {\n configurations: Record<string, ComponentConfiguration>;\n schemas: ComponentsDictionary;\n },\n schemas: Schema[] = []\n) => {\n return columns\n .map((name) => {\n const attribute = attributes[name];\n\n if (!attribute) {\n return null;\n }\n\n const metadata = metadatas[name];\n if (!metadata) {\n return null;\n }\n\n const settings: Partial<Settings> =\n attribute.type === 'component' && components\n ? (components.configurations[attribute.component]?.settings ?? {})\n : {};\n\n return {\n attribute,\n label: metadata.label ?? '',\n mainField: getMainField(attribute, metadata.mainField || settings.mainField, {\n schemas,\n components: components?.schemas ?? {},\n }),\n name: name,\n searchable: metadata.searchable ?? true,\n sortable: metadata.sortable ?? true,\n } satisfies ListFieldLayout;\n })\n .filter((field) => field !== null) as ListFieldLayout[];\n};\n\nexport {\n useDocLayout,\n useDocumentLayout,\n convertListLayoutToFieldLayouts,\n convertEditLayoutToFieldLayouts,\n DEFAULT_SETTINGS,\n};\nexport type { EditLayout, EditFieldLayout, ListLayout, ListFieldLayout, UseDocumentLayout };\n"],"names":["RESOLVED_LAYOUT_CACHE_LIMIT","resolvedLayoutCache","getCachedResolvedLayouts","components","data","model","schema","schemas","find","entry","value","setCachedResolvedLayouts","unshift","length","pop","DEFAULT_SETTINGS","bulkable","filterable","searchable","pagination","defaultSortBy","defaultSortOrder","mainField","pageSize","relationOpenMode","useDocumentLayout","useDocument","collectionType","skip","query","useQueryParams","runHookWaterfall","useStrapiApp","state","toggleNotification","useNotification","_unstableFormatAPIError","formatAPIError","useAPIErrorHandler","isLoading","isLoadingSchemas","useContentTypeSchema","currentData","isLoadingConfigs","error","useGetContentTypeConfigurationQuery","isConfigResolvedForModel","contentType","uid","stableLayoutsByModelRef","React","useRef","Map","useEffect","type","message","resolvedLayouts","useMemo","cachedLayouts","normalizedData","normalizeContentManagerLayout","edit","formatEditLayout","list","formatListLayout","listViewConversionContext","componentConfigurations","componentSchemas","contentTypeSchemas","layouts","current","set","stableLayouts","get","editLayout","layout","metadatas","options","settings","listLayout","HOOKS","MUTATE_EDIT_VIEW_LAYOUT","useDocLayout","useDoc","currentPanelIndex","panelledEditAttributes","convertEditLayoutToFieldLayouts","attributes","configurations","reduce","panels","row","some","field","push","componentEditAttributes","Object","entries","acc","configuration","componentSchema","icon","info","displayName","editMetadatas","attribute","metadata","pluginOptions","rows","map","name","fieldMetadata","component","disabled","editable","hint","description","label","getMainField","placeholder","required","size","unique","visible","filter","listMetadatas","listAttributes","convertListLayoutToFieldLayouts","columns","sortable"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqIA,MAAMA,2BAAAA,GAA8B,EAAA;AACpC;AACA;AACA,MAAMC,sBAAkD,EAAE;AAE1D,MAAMC,wBAAAA,GAA2B,CAAC,EAChCC,UAAU,EACVC,IAAI,EACJC,KAAK,EACLC,MAAM,EACNC,OAAO,EACiC,GAAA;IACxC,OAAON,mBAAAA,CAAoBO,IAAI,CAC7B,CAACC,KAAAA,GACCA,MAAMN,UAAU,KAAKA,UAAAA,IACrBM,KAAAA,CAAML,IAAI,KAAKA,QACfK,KAAAA,CAAMJ,KAAK,KAAKA,KAAAA,IAChBI,KAAAA,CAAMH,MAAM,KAAKA,MAAAA,IACjBG,KAAAA,CAAMF,OAAO,KAAKA,OAAAA,CAAAA,EACnBG,KAAAA;AACL,CAAA;AAEA,MAAMC,2BAA2B,CAACF,KAAAA,GAAAA;AAChCR,IAAAA,mBAAAA,CAAoBW,OAAO,CAACH,KAAAA,CAAAA;IAE5B,IAAIR,mBAAAA,CAAoBY,MAAM,GAAGb,2BAAAA,EAA6B;AAC5DC,QAAAA,mBAAAA,CAAoBa,GAAG,EAAA;AACzB,IAAA;A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A,GAAoB,EAAE,GAAA;IAEtB,OAAOyH,OAAAA,CACJnB,GAAG,CAAC,CAACC,IAAAA,GAAAA;QACJ,MAAML,SAAAA,GAAYlB,YAAU,CAACuB,IAAAA,CAAK;AAElC,QAAA,IAAI,CAACL,SAAAA,EAAW;YACd,OAAO,IAAA;AACT,QAAA;QAEA,MAAMC,QAAAA,GAAW9B,SAAS,CAACkC,IAAAA,CAAK;AAChC,QAAA,IAAI,CAACJ,QAAAA,EAAU;YACb,OAAO,IAAA;AACT,QAAA;AAEA,QAAA,MAAM5B,WACJ2B,SAAAA,CAAUnD,IAAI,KAAK,WAAA,IAAenD,aAC7BA,UAAAA,CAAWqF,cAAc,CAACiB,SAAAA,CAAUO,SAAS,CAAC,EAAElC,QAAAA,IAAY,KAC7D,EAAC;QAEP,OAAO;AACL2B,YAAAA,SAAAA;YACAY,KAAAA,EAAOX,QAAAA,CAASW,KAAK,IAAI,EAAA;AACzB/F,YAAAA,SAAAA,EAAWgG,wBAAab,SAAAA,EAAWC,QAAAA,CAASpF,SAAS,IAAIwD,QAAAA,CAASxD,SAAS,EAAE;AAC3Ef,gBAAAA,OAAAA;gBACAJ,UAAAA,EAAYA,UAAAA,EAAYI,WAAW;AACrC,aAAA,CAAA;YACAuG,IAAAA,EAAMA,IAAAA;YACN5F,UAAAA,EAAYwF,QAAAA,CAASxF,UAAU,IAAI,IAAA;YACnC+G,QAAAA,EAAUvB,QAAAA,CAASuB,QAAQ,IAAI;AACjC,SAAA;AACF,IAAA,CAAA,CAAA,CACCL,MAAM,CAAC,CAAC/B,KAAAA,GAAUA,KAAAA,KAAU,IAAA,CAAA;AACjC;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"useDocumentLayout.js","sources":["../../../admin/src/hooks/useDocumentLayout.ts"],"sourcesContent":["import * as React from 'react';\n\nimport { SerializedError } from '@reduxjs/toolkit';\nimport {\n useNotification,\n useStrapiApp,\n useAPIErrorHandler,\n useQueryParams,\n} from '@strapi/admin/strapi-admin';\n\nimport { HOOKS } from '../constants/hooks';\nimport { useGetContentTypeConfigurationQuery } from '../services/contentTypes';\nimport { BaseQueryError } from '../utils/api';\nimport { getMainField } from '../utils/attributes';\nimport { normalizeContentManagerLayout } from '../utils/layouts/normalizeContentManagerLayout';\n\nimport { useContentTypeSchema } from './useContentTypeSchema';\nimport {\n type ComponentsDictionary,\n type Document,\n type Schema,\n useDoc,\n useDocument,\n} from './useDocument';\n\nimport type { ComponentConfiguration } from '../../../shared/contracts/components';\nimport type {\n Metadatas,\n FindContentTypeConfiguration,\n Settings,\n} from '../../../shared/contracts/content-types';\nimport type { Filters, InputProps, Table } from '@strapi/admin/strapi-admin';\nimport type { Schema as SchemaUtils } from '@strapi/types';\n\ntype LayoutOptions = Schema['options'] & Schema['pluginOptions'] & object;\n\ninterface LayoutSettings extends Settings {\n displayName?: string;\n icon?: never;\n}\n\ninterface ListCellMeta {\n collectionType: string;\n model: string;\n}\n\ninterface ListFieldLayout\n extends Table.Header<Document, ListFieldLayout, ListCellMeta>, Pick<Filters.Filter, 'mainField'> {\n attribute: SchemaUtils.Attribute.AnyAttribute | { type: 'custom' };\n}\n\ninterface ListLayout {\n layout: ListFieldLayout[];\n components?: never;\n metadatas: {\n [K in keyof Metadatas]: Metadatas[K]['list'];\n };\n options: LayoutOptions;\n settings: LayoutSettings;\n}\ninterface EditFieldSharedProps\n extends Omit<InputProps, 'hint' | 'label' | 'type'>, Pick<Filters.Filter, 'mainField'> {\n hint?: string;\n label: string;\n size: number;\n unique?: boolean;\n visible?: boolean;\n}\n\n/**\n * Map over all the types in Attribute Types and use that to create a union of new types where the attribute type\n * is under the property attribute and the type is under the property type.\n */\ntype EditFieldLayout = {\n [K in SchemaUtils.Attribute.Kind]: EditFieldSharedProps & {\n attribute: Extract<SchemaUtils.Attribute.AnyAttribute, { type: K }>;\n type: K;\n };\n}[SchemaUtils.Attribute.Kind];\n\ninterface EditLayout {\n layout: Array<Array<EditFieldLayout[]>>;\n components: {\n [uid: string]: {\n layout: Array<EditFieldLayout[]>;\n settings: ComponentConfiguration['settings'] & {\n displayName?: string;\n icon?: string;\n };\n };\n };\n metadatas: {\n [K in keyof Metadatas]: Metadatas[K]['edit'];\n };\n options: LayoutOptions;\n settings: LayoutSettings;\n}\n\n/**\n * Data required to resolve `mainField` when converting list column names to field layouts for\n * component and relation attributes; mirrors the fourth and fifth arguments of `formatListLayout`.\n */\ntype ListViewConversionContext = {\n componentConfigurations: FindContentTypeConfiguration.Response['data']['components'];\n componentSchemas: ComponentsDictionary;\n contentTypeSchemas: Schema[];\n};\n\ntype UseDocumentLayout = (model: string) => {\n error?: BaseQueryError | SerializedError;\n isLoading: boolean;\n /**\n * This is the layout for the edit view,\n */\n edit: EditLayout;\n list: ListLayout;\n /**\n * Populated when configuration is loaded; pass into `convertListLayoutToFieldLayouts` with\n * `list.metadatas` when mapping persisted list column names (e.g. custom displayed headers).\n */\n listViewConversionContext: ListViewConversionContext | null;\n};\n\ntype ResolvedLayouts = {\n edit: EditLayout;\n list: ListLayout;\n listViewConversionContext: ListViewConversionContext;\n};\n\ntype ResolvedLayoutCacheEntry = {\n components: ComponentsDictionary;\n data: LayoutData;\n model: string;\n schema?: Schema;\n schemas: Schema[];\n value: ResolvedLayouts;\n};\n\nconst RESOLVED_LAYOUT_CACHE_LIMIT = 25;\n// Module-level cache keeps resolved layout object identities stable across hook instances\n// when RTK Query returns the same schema/configuration references.\nconst resolvedLayoutCache: ResolvedLayoutCacheEntry[] = [];\n\nconst getCachedResolvedLayouts = ({\n components,\n data,\n model,\n schema,\n schemas,\n}: Omit<ResolvedLayoutCacheEntry, 'value'>) => {\n return resolvedLayoutCache.find(\n (entry) =>\n entry.components === components &&\n entry.data === data &&\n entry.model === model &&\n entry.schema === schema &&\n entry.schemas === schemas\n )?.value;\n};\n\nconst setCachedResolvedLayouts = (entry: ResolvedLayoutCacheEntry) => {\n resolvedLayoutCache.unshift(entry);\n\n if (resolvedLayoutCache.length > RESOLVED_LAYOUT_CACHE_LIMIT) {\n resolvedLayoutCache.pop();\n }\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocumentLayout\n * -----------------------------------------------------------------------------------------------*/\n\nconst DEFAULT_SETTINGS = {\n bulkable: false,\n filterable: false,\n searchable: false,\n pagination: false,\n defaultSortBy: '',\n defaultSortOrder: 'asc',\n mainField: 'id',\n pageSize: 10,\n relationOpenMode: 'modal' as const,\n};\n\n/**\n * @alpha\n * @description This hook is used to get the layouts for either the edit view or list view of a specific content-type\n * including the layouts for the components used in the content-type. It also runs the mutation hook waterfall so the data\n * is consistent wherever it is used. It's a light wrapper around the `useDocument` hook, but provides the `skip` option a document\n * is not fetched, however, it does fetch the schemas & components if they do not already exist in the cache.\n *\n * If the fetch fails, it will display a notification to the user.\n *\n * @example\n * ```tsx\n * const { model } = useParams<{ model: string }>();\n * const { edit: { schema: layout } } = useDocumentLayout(model);\n *\n * return layout.map(panel => panel.map(row => row.map(field => <Field.Root {...field} />)))\n * ```\n *\n */\nconst useDocumentLayout: UseDocumentLayout = (model) => {\n const { schema, components } = useDocument({ model, collectionType: '' }, { skip: true });\n const [{ query }] = useQueryParams();\n const runHookWaterfall = useStrapiApp('useDocumentLayout', (state) => state.runHookWaterfall);\n const { toggleNotification } = useNotification();\n const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();\n const { isLoading: isLoadingSchemas, schemas } = useContentTypeSchema();\n\n const {\n currentData: data,\n isLoading: isLoadingConfigs,\n error,\n } = useGetContentTypeConfigurationQuery(model);\n\n const isConfigResolvedForModel = data?.contentType?.uid === model;\n const isLoading = isLoadingSchemas || isLoadingConfigs || (!error && !isConfigResolvedForModel);\n const stableLayoutsByModelRef = React.useRef(\n new Map<\n string,\n {\n edit: EditLayout;\n list: ListLayout;\n listViewConversionContext: ListViewConversionContext | null;\n }\n >()\n );\n\n React.useEffect(() => {\n if (error) {\n toggleNotification({\n type: 'danger',\n message: formatAPIError(error),\n });\n }\n }, [error, formatAPIError, toggleNotification]);\n\n const resolvedLayouts = React.useMemo(() => {\n if (!data || isLoading) {\n return null;\n }\n\n const cachedLayouts = getCachedResolvedLayouts({ components, data, model, schema, schemas });\n\n if (cachedLayouts) {\n return cachedLayouts;\n }\n\n const normalizedData = normalizeContentManagerLayout(data, { schemas, schema, components });\n const edit = formatEditLayout(normalizedData, { schemas, schema, components });\n const list = formatListLayout(normalizedData, { schemas, schema, components });\n const listViewConversionContext: ListViewConversionContext = {\n componentConfigurations: normalizedData.components,\n componentSchemas: components,\n contentTypeSchemas: schemas,\n };\n\n const layouts = { edit, list, listViewConversionContext };\n\n setCachedResolvedLayouts({ components, data, model, schema, schemas, value: layouts });\n\n return layouts;\n }, [data, isLoading, model, schemas, schema, components]);\n\n React.useEffect(() => {\n if (resolvedLayouts) {\n stableLayoutsByModelRef.current.set(model, resolvedLayouts);\n }\n }, [model, resolvedLayouts]);\n\n const stableLayouts = resolvedLayouts ?? stableLayoutsByModelRef.current.get(model) ?? null;\n\n const editLayout = React.useMemo(\n () =>\n stableLayouts?.edit ??\n ({\n layout: [],\n components: {},\n metadatas: {},\n options: {},\n settings: DEFAULT_SETTINGS,\n } as EditLayout),\n [stableLayouts]\n );\n\n const listLayout = React.useMemo(\n () =>\n stableLayouts?.list ??\n ({\n layout: [],\n metadatas: {},\n options: {},\n settings: DEFAULT_SETTINGS,\n } as ListLayout),\n [stableLayouts]\n );\n\n const { layout: edit } = React.useMemo(\n () =>\n runHookWaterfall(HOOKS.MUTATE_EDIT_VIEW_LAYOUT, {\n layout: editLayout,\n query,\n }),\n [editLayout, query, runHookWaterfall]\n );\n\n const listViewConversionContext = stableLayouts?.listViewConversionContext ?? null;\n\n return {\n error,\n isLoading,\n edit,\n list: listLayout,\n listViewConversionContext,\n } satisfies ReturnType<UseDocumentLayout>;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * useDocLayout\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal this hook uses the internal useDoc hook, as such it shouldn't be used outside of the\n * content-manager because it won't work as intended.\n */\nconst useDocLayout = () => {\n const { model } = useDoc();\n return useDocumentLayout(model);\n};\n\n/* -------------------------------------------------------------------------------------------------\n * formatEditLayout\n * -----------------------------------------------------------------------------------------------*/\ntype LayoutData = FindContentTypeConfiguration.Response['data'];\n\n/**\n * @internal\n * @description takes the configuration data, the schema & the components used in the schema and formats the edit view\n * versions of the schema & components. This is then used to render the edit view of the content-type.\n */\nconst formatEditLayout = (\n data: LayoutData,\n {\n schemas,\n schema,\n components,\n }: { schemas: Schema[]; schema?: Schema; components: ComponentsDictionary }\n): EditLayout => {\n let currentPanelIndex = 0;\n /**\n * The fields arranged by the panels, new panels are made for dynamic zones only.\n */\n const panelledEditAttributes = convertEditLayoutToFieldLayouts(\n data.contentType.layouts.edit,\n schema?.attributes,\n data.contentType.metadatas,\n { configurations: data.components, schemas: components },\n schemas\n ).reduce<Array<EditFieldLayout[][]>>((panels, row) => {\n if (row.some((field) => field.type === 'dynamiczone')) {\n panels.push([row]);\n currentPanelIndex += 2;\n } else {\n if (!panels[currentPanelIndex]) {\n panels.push([row]);\n } else {\n panels[currentPanelIndex].push(row);\n }\n }\n\n return panels;\n }, []);\n\n const componentEditAttributes = Object.entries(data.components).reduce<EditLayout['components']>(\n (acc, [uid, configuration]) => {\n const componentSchema = components[uid];\n\n // Persisted configuration can reference component UIDs absent from `/init`.\n if (!componentSchema) {\n return acc;\n }\n\n acc[uid] = {\n layout: convertEditLayoutToFieldLayouts(\n configuration.layouts.edit,\n componentSchema.attributes,\n configuration.metadatas,\n { configurations: data.components, schemas: components }\n ),\n settings: {\n ...configuration.settings,\n icon: componentSchema.info.icon,\n displayName: componentSchema.info.displayName,\n },\n };\n return acc;\n },\n {}\n );\n\n const editMetadatas = Object.entries(data.contentType.metadatas).reduce<EditLayout['metadatas']>(\n (acc, [attribute, metadata]) => {\n return {\n ...acc,\n [attribute]: metadata.edit,\n };\n },\n {}\n );\n\n return {\n layout: panelledEditAttributes,\n components: componentEditAttributes,\n metadatas: editMetadatas,\n settings: {\n ...data.contentType.settings,\n displayName: schema?.info?.displayName,\n },\n options: {\n ...schema?.options,\n ...schema?.pluginOptions,\n ...data.contentType.options,\n },\n };\n};\n\n/* -------------------------------------------------------------------------------------------------\n * convertEditLayoutToFieldLayouts\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description takes the edit layout from either a content-type or a component\n * and formats it into a generic object that can be used to correctly render\n * the form fields.\n */\nconst convertEditLayoutToFieldLayouts = (\n rows: LayoutData['contentType']['layouts']['edit'],\n attributes: Schema['attributes'] = {},\n metadatas: Metadatas,\n components?: {\n configurations: Record<string, ComponentConfiguration>;\n schemas: ComponentsDictionary;\n },\n schemas: Schema[] = []\n) => {\n return rows.map((row) =>\n row\n .map((field) => {\n const attribute = attributes[field.name];\n\n if (!attribute) {\n return null;\n }\n\n const fieldMetadata = metadatas[field.name];\n if (!fieldMetadata) {\n return null;\n }\n\n const { edit: metadata } = fieldMetadata;\n\n const settings: Partial<Settings> =\n attribute.type === 'component' && components\n ? (components.configurations[attribute.component]?.settings ?? {})\n : {};\n\n return {\n attribute,\n disabled: !metadata.editable,\n hint: metadata.description,\n label: metadata.label ?? '',\n name: field.name,\n // @ts-expect-error – mainField does exist on the metadata for a relation.\n mainField: getMainField(attribute, metadata.mainField || settings.mainField, {\n schemas,\n components: components?.schemas ?? {},\n }),\n placeholder: metadata.placeholder ?? '',\n required: attribute.required ?? false,\n size: field.size,\n unique: 'unique' in attribute ? attribute.unique : false,\n visible: metadata.visible ?? true,\n type: attribute.type,\n };\n })\n .filter((field) => field !== null)\n ) as EditFieldLayout[][];\n};\n\n/* -------------------------------------------------------------------------------------------------\n * formatListLayout\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description takes the complete configuration data, the schema & the components used in the schema and\n * formats a list view layout for the content-type. This is much simpler than the edit view layout as there\n * are less options to consider.\n */\nconst formatListLayout = (\n data: LayoutData,\n {\n schemas,\n schema,\n components,\n }: { schemas: Schema[]; schema?: Schema; components: ComponentsDictionary }\n): ListLayout => {\n const listMetadatas = Object.entries(data.contentType.metadatas).reduce<ListLayout['metadatas']>(\n (acc, [attribute, metadata]) => {\n return {\n ...acc,\n [attribute]: metadata.list,\n };\n },\n {}\n );\n /**\n * The fields arranged by the panels, new panels are made for dynamic zones only.\n */\n const listAttributes = convertListLayoutToFieldLayouts(\n data.contentType.layouts.list,\n schema?.attributes,\n listMetadatas,\n { configurations: data.components, schemas: components },\n schemas\n );\n\n return {\n layout: listAttributes,\n settings: { ...data.contentType.settings, displayName: schema?.info?.displayName },\n metadatas: listMetadatas,\n options: {\n ...schema?.options,\n ...schema?.pluginOptions,\n ...data.contentType.options,\n },\n };\n};\n\n/* -------------------------------------------------------------------------------------------------\n * convertListLayoutToFieldLayouts\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description takes the columns from the list view configuration and formats them into a generic object\n * combinining metadata and attribute data.\n *\n * @note We do use this to reformat the list of strings when updating the displayed headers for the list view.\n */\nconst convertListLayoutToFieldLayouts = (\n columns: LayoutData['contentType']['layouts']['list'],\n attributes: Schema['attributes'] = {},\n metadatas: ListLayout['metadatas'],\n components?: {\n configurations: Record<string, ComponentConfiguration>;\n schemas: ComponentsDictionary;\n },\n schemas: Schema[] = []\n) => {\n return columns\n .map((name) => {\n const attribute = attributes[name];\n\n if (!attribute) {\n return null;\n }\n\n const metadata = metadatas[name];\n if (!metadata) {\n return null;\n }\n\n const settings: Partial<Settings> =\n attribute.type === 'component' && components\n ? (components.configurations[attribute.component]?.settings ?? {})\n : {};\n\n return {\n attribute,\n label: metadata.label ?? '',\n mainField: getMainField(attribute, metadata.mainField || settings.mainField, {\n schemas,\n components: components?.schemas ?? {},\n }),\n name: name,\n searchable: metadata.searchable ?? true,\n sortable: metadata.sortable ?? true,\n } satisfies ListFieldLayout;\n })\n .filter((field) => field !== null) as ListFieldLayout[];\n};\n\nexport {\n useDocLayout,\n useDocumentLayout,\n convertListLayoutToFieldLayouts,\n convertEditLayoutToFieldLayouts,\n DEFAULT_SETTINGS,\n};\nexport type {\n EditLayout,\n EditFieldLayout,\n ListCellMeta,\n ListLayout,\n ListFieldLayout,\n UseDocumentLayout,\n};\n"],"names":["RESOLVED_LAYOUT_CACHE_LIMIT","resolvedLayoutCache","getCachedResolvedLayouts","components","data","model","schema","schemas","find","entry","value","setCachedResolvedLayouts","unshift","length","pop","DEFAULT_SETTINGS","bulkable","filterable","searchable","pagination","defaultSortBy","defaultSortOrder","mainField","pageSize","relationOpenMode","useDocumentLayout","useDocument","collectionType","skip","query","useQueryParams","runHookWaterfall","useStrapiApp","state","toggleNotification","useNotification","_unstableFormatAPIError","formatAPIError","useAPIErrorHandler","isLoading","isLoadingSchemas","useContentTypeSchema","currentData","isLoadingConfigs","error","useGetContentTypeConfigurationQuery","isConfigResolvedForModel","contentType","uid","stableLayoutsByModelRef","React","useRef","Map","useEffect","type","message","resolvedLayouts","useMemo","cachedLayouts","normalizedData","normalizeContentManagerLayout","edit","formatEditLayout","list","formatListLayout","listViewConversionContext","componentConfigurations","componentSchemas","contentTypeSchemas","layouts","current","set","stableLayouts","get","editLayout","layout","metadatas","options","settings","listLayout","HOOKS","MUTATE_EDIT_VIEW_LAYOUT","useDocLayout","useDoc","currentPanelIndex","panelledEditAttributes","convertEditLayoutToFieldLayouts","attributes","configurations","reduce","panels","row","some","field","push","componentEditAttributes","Object","entries","acc","configuration","componentSchema","icon","info","displayName","editMetadatas","attribute","metadata","pluginOptions","rows","map","name","fieldMetadata","component","disabled","editable","hint","description","label","getMainField","placeholder","required","size","unique","visible","filter","listMetadatas","listAttributes","convertListLayoutToFieldLayouts","columns","sortable"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0IA,MAAMA,2BAAAA,GAA8B,EAAA;AACpC;AACA;AACA,MAAMC,sBAAkD,EAAE;AAE1D,MAAMC,wBAAAA,GAA2B,CAAC,EAChCC,UAAU,EACVC,IAAI,EACJC,KAAK,EACLC,MAAM,EACNC,OAAO,EACiC,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