@strapi/content-manager 0.0.0-experimental.81dfdf02b1367004c7deed9e01afa9d3a15d0fa5 → 0.0.0-experimental.8f5736f39974781dca58cef1d1dea9d54580fbf1

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.
Files changed (103) hide show
  1. package/dist/_chunks/{ComponentConfigurationPage-qemkOlnj.mjs → ComponentConfigurationPage-DfFSZQxe.mjs} +3 -3
  2. package/dist/_chunks/{ComponentConfigurationPage-qemkOlnj.mjs.map → ComponentConfigurationPage-DfFSZQxe.mjs.map} +1 -1
  3. package/dist/_chunks/{ComponentConfigurationPage-D_M8iBw5.js → ComponentConfigurationPage-FqfsxQ1j.js} +3 -3
  4. package/dist/_chunks/{ComponentConfigurationPage-D_M8iBw5.js.map → ComponentConfigurationPage-FqfsxQ1j.js.map} +1 -1
  5. package/dist/_chunks/{EditConfigurationPage-BePwPuHy.js → EditConfigurationPage-Cn0e8t3I.js} +3 -3
  6. package/dist/_chunks/{EditConfigurationPage-BePwPuHy.js.map → EditConfigurationPage-Cn0e8t3I.js.map} +1 -1
  7. package/dist/_chunks/{EditConfigurationPage-CjUrEewK.mjs → EditConfigurationPage-DdPNAbl3.mjs} +3 -3
  8. package/dist/_chunks/{EditConfigurationPage-CjUrEewK.mjs.map → EditConfigurationPage-DdPNAbl3.mjs.map} +1 -1
  9. package/dist/_chunks/{EditViewPage-De8GyU8P.mjs → EditViewPage-B82x_x1b.mjs} +15 -5
  10. package/dist/_chunks/EditViewPage-B82x_x1b.mjs.map +1 -0
  11. package/dist/_chunks/{EditViewPage-B-RJeiJD.js → EditViewPage-DlxEHhUt.js} +15 -5
  12. package/dist/_chunks/EditViewPage-DlxEHhUt.js.map +1 -0
  13. package/dist/_chunks/{Field-dq8Tg1M_.js → Field-COL25JiC.js} +90 -84
  14. package/dist/_chunks/Field-COL25JiC.js.map +1 -0
  15. package/dist/_chunks/{Field-pb2o8uBe.mjs → Field-DufHXW17.mjs} +86 -80
  16. package/dist/_chunks/Field-DufHXW17.mjs.map +1 -0
  17. package/dist/_chunks/{Form-DGIf4jQU.js → Form-BssUwrTO.js} +16 -8
  18. package/dist/_chunks/Form-BssUwrTO.js.map +1 -0
  19. package/dist/_chunks/{Form-DJn0Dxha.mjs → Form-u_kAOhwB.mjs} +16 -8
  20. package/dist/_chunks/Form-u_kAOhwB.mjs.map +1 -0
  21. package/dist/_chunks/{History-Dh2NEHnR.js → History-C9t9UqpO.js} +23 -10
  22. package/dist/_chunks/History-C9t9UqpO.js.map +1 -0
  23. package/dist/_chunks/{History-BowL3JKP.mjs → History-DRwA3oMM.mjs} +24 -11
  24. package/dist/_chunks/History-DRwA3oMM.mjs.map +1 -0
  25. package/dist/_chunks/{ListConfigurationPage-BxYCWz9e.js → ListConfigurationPage-BXYPohh-.js} +2 -2
  26. package/dist/_chunks/{ListConfigurationPage-BxYCWz9e.js.map → ListConfigurationPage-BXYPohh-.js.map} +1 -1
  27. package/dist/_chunks/{ListConfigurationPage-BpVOB-hn.mjs → ListConfigurationPage-BxfQJzPk.mjs} +2 -2
  28. package/dist/_chunks/{ListConfigurationPage-BpVOB-hn.mjs.map → ListConfigurationPage-BxfQJzPk.mjs.map} +1 -1
  29. package/dist/_chunks/{ListViewPage-CXFUjZQC.mjs → ListViewPage-CELx2ysp.mjs} +40 -36
  30. package/dist/_chunks/ListViewPage-CELx2ysp.mjs.map +1 -0
  31. package/dist/_chunks/{ListViewPage-4XsciqHZ.js → ListViewPage-D2VD8Szg.js} +43 -39
  32. package/dist/_chunks/ListViewPage-D2VD8Szg.js.map +1 -0
  33. package/dist/_chunks/{NoContentTypePage-C8OpoHeU.js → NoContentTypePage-BV9IjJSM.js} +2 -2
  34. package/dist/_chunks/{NoContentTypePage-C8OpoHeU.js.map → NoContentTypePage-BV9IjJSM.js.map} +1 -1
  35. package/dist/_chunks/{NoContentTypePage-DuhOTp3x.mjs → NoContentTypePage-DtJ9jcfk.mjs} +2 -2
  36. package/dist/_chunks/{NoContentTypePage-DuhOTp3x.mjs.map → NoContentTypePage-DtJ9jcfk.mjs.map} +1 -1
  37. package/dist/_chunks/{NoPermissionsPage-DVz3mzDz.mjs → NoPermissionsPage-DWleVYK7.mjs} +2 -2
  38. package/dist/_chunks/{NoPermissionsPage-DVz3mzDz.mjs.map → NoPermissionsPage-DWleVYK7.mjs.map} +1 -1
  39. package/dist/_chunks/{NoPermissionsPage-y_r7DVA2.js → NoPermissionsPage-Dp8NpF9I.js} +2 -2
  40. package/dist/_chunks/{NoPermissionsPage-y_r7DVA2.js.map → NoPermissionsPage-Dp8NpF9I.js.map} +1 -1
  41. package/dist/_chunks/{Relations-CVNLrn1Y.mjs → Relations-BTcf5xaw.mjs} +32 -23
  42. package/dist/_chunks/Relations-BTcf5xaw.mjs.map +1 -0
  43. package/dist/_chunks/{Relations-DPFCAa7b.js → Relations-DR7EUgyC.js} +32 -23
  44. package/dist/_chunks/Relations-DR7EUgyC.js.map +1 -0
  45. package/dist/_chunks/{en-uOUIxfcQ.js → en-Bm0D0IWz.js} +13 -12
  46. package/dist/_chunks/{en-uOUIxfcQ.js.map → en-Bm0D0IWz.js.map} +1 -1
  47. package/dist/_chunks/{en-BrCTWlZv.mjs → en-DKV44jRb.mjs} +13 -12
  48. package/dist/_chunks/{en-BrCTWlZv.mjs.map → en-DKV44jRb.mjs.map} +1 -1
  49. package/dist/_chunks/{index-C3fJE-1-.js → index-BdMf2lfT.js} +1877 -1767
  50. package/dist/_chunks/index-BdMf2lfT.js.map +1 -0
  51. package/dist/_chunks/{index-DiMrfcfy.mjs → index-wnqzm4Q8.mjs} +1881 -1771
  52. package/dist/_chunks/index-wnqzm4Q8.mjs.map +1 -0
  53. package/dist/_chunks/{layout-ls3gxfpH.mjs → layout-2CfjL0T9.mjs} +5 -4
  54. package/dist/_chunks/{layout-ls3gxfpH.mjs.map → layout-2CfjL0T9.mjs.map} +1 -1
  55. package/dist/_chunks/{layout-C788OmNr.js → layout-B2MyZU-_.js} +5 -4
  56. package/dist/_chunks/{layout-C788OmNr.js.map → layout-B2MyZU-_.js.map} +1 -1
  57. package/dist/_chunks/{relations-DYeotliT.js → relations-BH7JJGGe.js} +2 -2
  58. package/dist/_chunks/{relations-DYeotliT.js.map → relations-BH7JJGGe.js.map} +1 -1
  59. package/dist/_chunks/{relations-CLcOmGO0.mjs → relations-C0w0GcXi.mjs} +2 -2
  60. package/dist/_chunks/{relations-CLcOmGO0.mjs.map → relations-C0w0GcXi.mjs.map} +1 -1
  61. package/dist/_chunks/{usePrev-B9w_-eYc.js → useDebounce-CtcjDB3L.js} +14 -1
  62. package/dist/_chunks/useDebounce-CtcjDB3L.js.map +1 -0
  63. package/dist/_chunks/useDebounce-DmuSJIF3.mjs +29 -0
  64. package/dist/_chunks/useDebounce-DmuSJIF3.mjs.map +1 -0
  65. package/dist/admin/index.js +2 -1
  66. package/dist/admin/index.js.map +1 -1
  67. package/dist/admin/index.mjs +3 -2
  68. package/dist/admin/src/exports.d.ts +1 -1
  69. package/dist/admin/src/hooks/useDocument.d.ts +32 -1
  70. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/WysiwygStyles.d.ts +0 -32
  71. package/dist/admin/src/pages/EditView/components/Header.d.ts +11 -11
  72. package/dist/admin/src/services/documents.d.ts +3 -1
  73. package/dist/server/index.js +48 -21
  74. package/dist/server/index.js.map +1 -1
  75. package/dist/server/index.mjs +48 -21
  76. package/dist/server/index.mjs.map +1 -1
  77. package/dist/server/src/controllers/collection-types.d.ts.map +1 -1
  78. package/dist/server/src/controllers/relations.d.ts.map +1 -1
  79. package/dist/server/src/history/services/history.d.ts.map +1 -1
  80. package/dist/server/src/history/services/lifecycles.d.ts.map +1 -1
  81. package/dist/server/src/history/services/utils.d.ts +1 -0
  82. package/dist/server/src/history/services/utils.d.ts.map +1 -1
  83. package/dist/shared/contracts/collection-types.d.ts +3 -1
  84. package/dist/shared/contracts/collection-types.d.ts.map +1 -1
  85. package/package.json +12 -12
  86. package/dist/_chunks/EditViewPage-B-RJeiJD.js.map +0 -1
  87. package/dist/_chunks/EditViewPage-De8GyU8P.mjs.map +0 -1
  88. package/dist/_chunks/Field-dq8Tg1M_.js.map +0 -1
  89. package/dist/_chunks/Field-pb2o8uBe.mjs.map +0 -1
  90. package/dist/_chunks/Form-DGIf4jQU.js.map +0 -1
  91. package/dist/_chunks/Form-DJn0Dxha.mjs.map +0 -1
  92. package/dist/_chunks/History-BowL3JKP.mjs.map +0 -1
  93. package/dist/_chunks/History-Dh2NEHnR.js.map +0 -1
  94. package/dist/_chunks/ListViewPage-4XsciqHZ.js.map +0 -1
  95. package/dist/_chunks/ListViewPage-CXFUjZQC.mjs.map +0 -1
  96. package/dist/_chunks/Relations-CVNLrn1Y.mjs.map +0 -1
  97. package/dist/_chunks/Relations-DPFCAa7b.js.map +0 -1
  98. package/dist/_chunks/index-C3fJE-1-.js.map +0 -1
  99. package/dist/_chunks/index-DiMrfcfy.mjs.map +0 -1
  100. package/dist/_chunks/usePrev-B9w_-eYc.js.map +0 -1
  101. package/dist/_chunks/usePrev-DH6iah0A.mjs +0 -16
  102. package/dist/_chunks/usePrev-DH6iah0A.mjs.map +0 -1
  103. package/strapi-server.js +0 -3
@@ -6,10 +6,10 @@ const React = require("react");
6
6
  const designSystem = require("@strapi/design-system");
7
7
  const reactIntl = require("react-intl");
8
8
  const reactRouterDom = require("react-router-dom");
9
- const styledComponents = require("styled-components");
10
9
  const yup = require("yup");
11
10
  const pipe = require("lodash/fp/pipe");
12
11
  const dateFns = require("date-fns");
12
+ const styledComponents = require("styled-components");
13
13
  const qs = require("qs");
14
14
  const toolkit = require("@reduxjs/toolkit");
15
15
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
@@ -121,6 +121,7 @@ const DocumentRBAC = ({ children, permissions }) => {
121
121
  if (!slug) {
122
122
  throw new Error("Cannot find the slug param in the URL");
123
123
  }
124
+ const [{ rawQuery }] = strapiAdmin.useQueryParams();
124
125
  const userPermissions = strapiAdmin.useAuth("DocumentRBAC", (state) => state.permissions);
125
126
  const contentTypePermissions = React__namespace.useMemo(() => {
126
127
  const contentTypePermissions2 = userPermissions.filter(
@@ -131,7 +132,14 @@ const DocumentRBAC = ({ children, permissions }) => {
131
132
  return { ...acc, [action]: [permission] };
132
133
  }, {});
133
134
  }, [slug, userPermissions]);
134
- const { isLoading, allowedActions } = strapiAdmin.useRBAC(contentTypePermissions, permissions ?? void 0);
135
+ const { isLoading, allowedActions } = strapiAdmin.useRBAC(
136
+ contentTypePermissions,
137
+ permissions ?? void 0,
138
+ // TODO: useRBAC context should be typed and built differently
139
+ // We are passing raw query as context to the hook so that it can
140
+ // rely on the locale provided from DocumentRBAC for its permission calculations.
141
+ rawQuery
142
+ );
135
143
  const canCreateFields = !isLoading && allowedActions.canCreate ? extractAndDedupeFields(contentTypePermissions.create) : [];
136
144
  const canReadFields = !isLoading && allowedActions.canRead ? extractAndDedupeFields(contentTypePermissions.read) : [];
137
145
  const canUpdateFields = !isLoading && allowedActions.canUpdate ? extractAndDedupeFields(contentTypePermissions.update) : [];
@@ -482,6 +490,24 @@ const buildValidParams = (query) => {
482
490
  const isBaseQueryError = (error) => {
483
491
  return error.name !== void 0;
484
492
  };
493
+ const arrayValidator = (attribute, options) => ({
494
+ message: strapiAdmin.translatedErrors.required,
495
+ test(value) {
496
+ if (options.status === "draft") {
497
+ return true;
498
+ }
499
+ if (!attribute.required) {
500
+ return true;
501
+ }
502
+ if (!value) {
503
+ return false;
504
+ }
505
+ if (Array.isArray(value) && value.length === 0) {
506
+ return false;
507
+ }
508
+ return true;
509
+ }
510
+ });
485
511
  const createYupSchema = (attributes = {}, components = {}, options = { status: null }) => {
486
512
  const createModelSchema = (attributes2) => yup__namespace.object().shape(
487
513
  Object.entries(attributes2).reduce((acc, [name, attribute]) => {
@@ -489,6 +515,7 @@ const createYupSchema = (attributes = {}, components = {}, options = { status: n
489
515
  return acc;
490
516
  }
491
517
  const validations = [
518
+ addNullableValidation,
492
519
  addRequiredValidation,
493
520
  addMinLengthValidation,
494
521
  addMaxLengthValidation,
@@ -505,12 +532,12 @@ const createYupSchema = (attributes = {}, components = {}, options = { status: n
505
532
  ...acc,
506
533
  [name]: transformSchema(
507
534
  yup__namespace.array().of(createModelSchema(attributes3).nullable(false))
508
- )
535
+ ).test(arrayValidator(attribute, options))
509
536
  };
510
537
  } else {
511
538
  return {
512
539
  ...acc,
513
- [name]: transformSchema(createModelSchema(attributes3))
540
+ [name]: transformSchema(createModelSchema(attributes3).nullable())
514
541
  };
515
542
  }
516
543
  }
@@ -532,7 +559,7 @@ const createYupSchema = (attributes = {}, components = {}, options = { status: n
532
559
  }
533
560
  )
534
561
  )
535
- )
562
+ ).test(arrayValidator(attribute, options))
536
563
  };
537
564
  case "relation":
538
565
  return {
@@ -544,7 +571,7 @@ const createYupSchema = (attributes = {}, components = {}, options = { status: n
544
571
  } else if (Array.isArray(value)) {
545
572
  return yup__namespace.array().of(
546
573
  yup__namespace.object().shape({
547
- id: yup__namespace.string().required()
574
+ id: yup__namespace.number().required()
548
575
  })
549
576
  );
550
577
  } else if (typeof value === "object") {
@@ -630,17 +657,17 @@ const nullableSchema = (schema) => {
630
657
  schema
631
658
  );
632
659
  };
660
+ const addNullableValidation = () => (schema) => {
661
+ return nullableSchema(schema);
662
+ };
633
663
  const addRequiredValidation = (attribute, options) => (schema) => {
634
- if (options.status === "draft") {
635
- return nullableSchema(schema);
636
- }
637
- if ((attribute.type === "component" && attribute.repeatable || attribute.type === "dynamiczone") && attribute.required && "min" in schema) {
638
- return schema.min(1, strapiAdmin.translatedErrors.required);
664
+ if (options.status === "draft" || !attribute.required) {
665
+ return schema;
639
666
  }
640
- if (attribute.required && attribute.type !== "relation") {
667
+ if (attribute.required && "required" in schema) {
641
668
  return schema.required(strapiAdmin.translatedErrors.required);
642
669
  }
643
- return nullableSchema(schema);
670
+ return schema;
644
671
  };
645
672
  const addMinLengthValidation = (attribute, options) => (schema) => {
646
673
  if (options.status === "draft") {
@@ -668,31 +695,12 @@ const addMaxLengthValidation = (attribute) => (schema) => {
668
695
  return schema;
669
696
  };
670
697
  const addMinValidation = (attribute, options) => (schema) => {
671
- if ("min" in attribute) {
698
+ if (options.status === "draft") {
699
+ return schema;
700
+ }
701
+ if ("min" in attribute && "min" in schema) {
672
702
  const min = toInteger(attribute.min);
673
- if (attribute.type === "component" && attribute.repeatable || attribute.type === "dynamiczone") {
674
- if (options.status !== "draft" && !attribute.required && "test" in schema && min) {
675
- return schema.test(
676
- "custom-min",
677
- {
678
- ...strapiAdmin.translatedErrors.min,
679
- values: {
680
- min: attribute.min
681
- }
682
- },
683
- (value) => {
684
- if (!value) {
685
- return true;
686
- }
687
- if (Array.isArray(value) && value.length === 0) {
688
- return true;
689
- }
690
- return value.length >= min;
691
- }
692
- );
693
- }
694
- }
695
- if ("min" in schema && min) {
703
+ if (min) {
696
704
  return schema.min(min, {
697
705
  ...strapiAdmin.translatedErrors.min,
698
706
  values: {
@@ -810,19 +818,115 @@ const extractContentTypeComponents = (attributes = {}, allComponents = {}) => {
810
818
  }, {});
811
819
  return componentsByKey;
812
820
  };
813
- const useDocument = (args, opts) => {
821
+ const HOOKS = {
822
+ /**
823
+ * Hook that allows to mutate the displayed headers of the list view table
824
+ * @constant
825
+ * @type {string}
826
+ */
827
+ INJECT_COLUMN_IN_TABLE: "Admin/CM/pages/ListView/inject-column-in-table",
828
+ /**
829
+ * Hook that allows to mutate the CM's collection types links pre-set filters
830
+ * @constant
831
+ * @type {string}
832
+ */
833
+ MUTATE_COLLECTION_TYPES_LINKS: "Admin/CM/pages/App/mutate-collection-types-links",
834
+ /**
835
+ * Hook that allows to mutate the CM's edit view layout
836
+ * @constant
837
+ * @type {string}
838
+ */
839
+ MUTATE_EDIT_VIEW_LAYOUT: "Admin/CM/pages/EditView/mutate-edit-view-layout",
840
+ /**
841
+ * Hook that allows to mutate the CM's single types links pre-set filters
842
+ * @constant
843
+ * @type {string}
844
+ */
845
+ MUTATE_SINGLE_TYPES_LINKS: "Admin/CM/pages/App/mutate-single-types-links"
846
+ };
847
+ const contentTypesApi = contentManagerApi.injectEndpoints({
848
+ endpoints: (builder) => ({
849
+ getContentTypeConfiguration: builder.query({
850
+ query: (uid) => ({
851
+ url: `/content-manager/content-types/${uid}/configuration`,
852
+ method: "GET"
853
+ }),
854
+ transformResponse: (response) => response.data,
855
+ providesTags: (_result, _error, uid) => [
856
+ { type: "ContentTypesConfiguration", id: uid },
857
+ { type: "ContentTypeSettings", id: "LIST" }
858
+ ]
859
+ }),
860
+ getAllContentTypeSettings: builder.query({
861
+ query: () => "/content-manager/content-types-settings",
862
+ transformResponse: (response) => response.data,
863
+ providesTags: [{ type: "ContentTypeSettings", id: "LIST" }]
864
+ }),
865
+ updateContentTypeConfiguration: builder.mutation({
866
+ query: ({ uid, ...body }) => ({
867
+ url: `/content-manager/content-types/${uid}/configuration`,
868
+ method: "PUT",
869
+ data: body
870
+ }),
871
+ transformResponse: (response) => response.data,
872
+ invalidatesTags: (_result, _error, { uid }) => [
873
+ { type: "ContentTypesConfiguration", id: uid },
874
+ { type: "ContentTypeSettings", id: "LIST" },
875
+ // Is this necessary?
876
+ { type: "InitialData" }
877
+ ]
878
+ })
879
+ })
880
+ });
881
+ const {
882
+ useGetContentTypeConfigurationQuery,
883
+ useGetAllContentTypeSettingsQuery,
884
+ useUpdateContentTypeConfigurationMutation
885
+ } = contentTypesApi;
886
+ const checkIfAttributeIsDisplayable = (attribute) => {
887
+ const { type } = attribute;
888
+ if (type === "relation") {
889
+ return !attribute.relation.toLowerCase().includes("morph");
890
+ }
891
+ return !["json", "dynamiczone", "richtext", "password", "blocks"].includes(type) && !!type;
892
+ };
893
+ const getMainField = (attribute, mainFieldName, { schemas, components }) => {
894
+ if (!mainFieldName) {
895
+ return void 0;
896
+ }
897
+ const mainFieldType = attribute.type === "component" ? components[attribute.component].attributes[mainFieldName].type : (
898
+ // @ts-expect-error – `targetModel` does exist on the attribute for a relation.
899
+ schemas.find((schema) => schema.uid === attribute.targetModel)?.attributes[mainFieldName].type
900
+ );
901
+ return {
902
+ name: mainFieldName,
903
+ type: mainFieldType ?? "string"
904
+ };
905
+ };
906
+ const DEFAULT_SETTINGS = {
907
+ bulkable: false,
908
+ filterable: false,
909
+ searchable: false,
910
+ pagination: false,
911
+ defaultSortBy: "",
912
+ defaultSortOrder: "asc",
913
+ mainField: "id",
914
+ pageSize: 10
915
+ };
916
+ const useDocumentLayout = (model) => {
917
+ const { schema, components } = useDocument({ model, collectionType: "" }, { skip: true });
918
+ const [{ query }] = strapiAdmin.useQueryParams();
919
+ const runHookWaterfall = strapiAdmin.useStrapiApp("useDocumentLayout", (state) => state.runHookWaterfall);
814
920
  const { toggleNotification } = strapiAdmin.useNotification();
815
921
  const { _unstableFormatAPIError: formatAPIError } = strapiAdmin.useAPIErrorHandler();
922
+ const { isLoading: isLoadingSchemas, schemas } = useContentTypeSchema();
816
923
  const {
817
- currentData: data,
818
- isLoading: isLoadingDocument,
819
- isFetching: isFetchingDocument,
820
- error
821
- } = useGetDocumentQuery(args, {
822
- ...opts,
823
- skip: !args.documentId && args.collectionType !== SINGLE_TYPES || opts?.skip
824
- });
825
- const { components, schema, isLoading: isLoadingSchema } = useContentTypeSchema(args.model);
924
+ data,
925
+ isLoading: isLoadingConfigs,
926
+ error,
927
+ isFetching: isFetchingConfigs
928
+ } = useGetContentTypeConfigurationQuery(model);
929
+ const isLoading = isLoadingSchemas || isFetchingConfigs || isLoadingConfigs;
826
930
  React__namespace.useEffect(() => {
827
931
  if (error) {
828
932
  toggleNotification({
@@ -830,398 +934,656 @@ const useDocument = (args, opts) => {
830
934
  message: formatAPIError(error)
831
935
  });
832
936
  }
833
- }, [toggleNotification, error, formatAPIError, args.collectionType]);
834
- const validationSchema = React__namespace.useMemo(() => {
835
- if (!schema) {
836
- return null;
837
- }
838
- return createYupSchema(schema.attributes, components);
839
- }, [schema, components]);
840
- const validate = React__namespace.useCallback(
841
- (document) => {
842
- if (!validationSchema) {
843
- throw new Error(
844
- "There is no validation schema generated, this is likely due to the schema not being loaded yet."
845
- );
846
- }
847
- try {
848
- validationSchema.validateSync(document, { abortEarly: false, strict: true });
849
- return null;
850
- } catch (error2) {
851
- if (error2 instanceof yup.ValidationError) {
852
- return strapiAdmin.getYupValidationErrors(error2);
853
- }
854
- throw error2;
855
- }
937
+ }, [error, formatAPIError, toggleNotification]);
938
+ const editLayout = React__namespace.useMemo(
939
+ () => data && !isLoading ? formatEditLayout(data, { schemas, schema, components }) : {
940
+ layout: [],
941
+ components: {},
942
+ metadatas: {},
943
+ options: {},
944
+ settings: DEFAULT_SETTINGS
856
945
  },
857
- [validationSchema]
946
+ [data, isLoading, schemas, schema, components]
947
+ );
948
+ const listLayout = React__namespace.useMemo(() => {
949
+ return data && !isLoading ? formatListLayout(data, { schemas, schema, components }) : {
950
+ layout: [],
951
+ metadatas: {},
952
+ options: {},
953
+ settings: DEFAULT_SETTINGS
954
+ };
955
+ }, [data, isLoading, schemas, schema, components]);
956
+ const { layout: edit } = React__namespace.useMemo(
957
+ () => runHookWaterfall(HOOKS.MUTATE_EDIT_VIEW_LAYOUT, {
958
+ layout: editLayout,
959
+ query
960
+ }),
961
+ [editLayout, query, runHookWaterfall]
858
962
  );
859
- const isLoading = isLoadingDocument || isFetchingDocument || isLoadingSchema;
860
963
  return {
861
- components,
862
- document: data?.data,
863
- meta: data?.meta,
964
+ error,
864
965
  isLoading,
865
- schema,
866
- validate
867
- };
868
- };
869
- const useDoc = () => {
870
- const { id, slug, collectionType, origin } = reactRouterDom.useParams();
871
- const [{ query }] = strapiAdmin.useQueryParams();
872
- const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
873
- if (!collectionType) {
874
- throw new Error("Could not find collectionType in url params");
875
- }
876
- if (!slug) {
877
- throw new Error("Could not find model in url params");
878
- }
879
- return {
880
- collectionType,
881
- model: slug,
882
- id: origin || id === "create" ? void 0 : id,
883
- ...useDocument(
884
- { documentId: origin || id, model: slug, collectionType, params },
885
- {
886
- skip: id === "create" || !origin && !id && collectionType !== SINGLE_TYPES
887
- }
888
- )
966
+ edit,
967
+ list: listLayout
889
968
  };
890
969
  };
891
- const prefixPluginTranslations = (trad, pluginId) => {
892
- if (!pluginId) {
893
- throw new TypeError("pluginId can't be empty");
894
- }
895
- return Object.keys(trad).reduce((acc, current) => {
896
- acc[`${pluginId}.${current}`] = trad[current];
897
- return acc;
898
- }, {});
899
- };
900
- const getTranslation = (id) => `content-manager.${id}`;
901
- const DEFAULT_UNEXPECTED_ERROR_MSG = {
902
- id: "notification.error",
903
- defaultMessage: "An error occurred, please try again"
970
+ const useDocLayout = () => {
971
+ const { model } = useDoc();
972
+ return useDocumentLayout(model);
904
973
  };
905
- const useDocumentActions = () => {
906
- const { toggleNotification } = strapiAdmin.useNotification();
907
- const { formatMessage } = reactIntl.useIntl();
908
- const { trackUsage } = strapiAdmin.useTracking();
909
- const { _unstableFormatAPIError: formatAPIError } = strapiAdmin.useAPIErrorHandler();
910
- const navigate = reactRouterDom.useNavigate();
911
- const [deleteDocument] = useDeleteDocumentMutation();
912
- const _delete = React__namespace.useCallback(
913
- async ({ collectionType, model, documentId, params }, trackerProperty) => {
914
- try {
915
- trackUsage("willDeleteEntry", trackerProperty);
916
- const res = await deleteDocument({
917
- collectionType,
918
- model,
919
- documentId,
920
- params
921
- });
922
- if ("error" in res) {
923
- toggleNotification({
924
- type: "danger",
925
- message: formatAPIError(res.error)
926
- });
927
- return { error: res.error };
928
- }
929
- toggleNotification({
930
- type: "success",
931
- message: formatMessage({
932
- id: getTranslation("success.record.delete"),
933
- defaultMessage: "Deleted document"
934
- })
935
- });
936
- trackUsage("didDeleteEntry", trackerProperty);
937
- return res.data;
938
- } catch (err) {
939
- toggleNotification({
940
- type: "danger",
941
- message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
942
- });
943
- trackUsage("didNotDeleteEntry", { error: err, ...trackerProperty });
944
- throw err;
974
+ const formatEditLayout = (data, {
975
+ schemas,
976
+ schema,
977
+ components
978
+ }) => {
979
+ let currentPanelIndex = 0;
980
+ const panelledEditAttributes = convertEditLayoutToFieldLayouts(
981
+ data.contentType.layouts.edit,
982
+ schema?.attributes,
983
+ data.contentType.metadatas,
984
+ { configurations: data.components, schemas: components },
985
+ schemas
986
+ ).reduce((panels, row) => {
987
+ if (row.some((field) => field.type === "dynamiczone")) {
988
+ panels.push([row]);
989
+ currentPanelIndex += 2;
990
+ } else {
991
+ if (!panels[currentPanelIndex]) {
992
+ panels.push([]);
945
993
  }
946
- },
947
- [trackUsage, deleteDocument, toggleNotification, formatMessage, formatAPIError]
948
- );
949
- const [deleteManyDocuments] = useDeleteManyDocumentsMutation();
950
- const deleteMany = React__namespace.useCallback(
951
- async ({ model, documentIds, params }) => {
952
- try {
953
- trackUsage("willBulkDeleteEntries");
954
- const res = await deleteManyDocuments({
955
- model,
956
- documentIds,
957
- params
958
- });
959
- if ("error" in res) {
960
- toggleNotification({
961
- type: "danger",
962
- message: formatAPIError(res.error)
963
- });
964
- return { error: res.error };
994
+ panels[currentPanelIndex].push(row);
995
+ }
996
+ return panels;
997
+ }, []);
998
+ const componentEditAttributes = Object.entries(data.components).reduce(
999
+ (acc, [uid, configuration]) => {
1000
+ acc[uid] = {
1001
+ layout: convertEditLayoutToFieldLayouts(
1002
+ configuration.layouts.edit,
1003
+ components[uid].attributes,
1004
+ configuration.metadatas,
1005
+ { configurations: data.components, schemas: components }
1006
+ ),
1007
+ settings: {
1008
+ ...configuration.settings,
1009
+ icon: components[uid].info.icon,
1010
+ displayName: components[uid].info.displayName
965
1011
  }
966
- toggleNotification({
967
- type: "success",
968
- title: formatMessage({
969
- id: getTranslation("success.records.delete"),
970
- defaultMessage: "Successfully deleted."
971
- }),
972
- message: ""
973
- });
974
- trackUsage("didBulkDeleteEntries");
975
- return res.data;
976
- } catch (err) {
977
- toggleNotification({
978
- type: "danger",
979
- message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
980
- });
981
- trackUsage("didNotBulkDeleteEntries");
982
- throw err;
983
- }
1012
+ };
1013
+ return acc;
984
1014
  },
985
- [trackUsage, deleteManyDocuments, toggleNotification, formatMessage, formatAPIError]
1015
+ {}
986
1016
  );
987
- const [discardDocument] = useDiscardDocumentMutation();
988
- const discard = React__namespace.useCallback(
989
- async ({ collectionType, model, documentId, params }) => {
990
- try {
991
- const res = await discardDocument({
992
- collectionType,
993
- model,
994
- documentId,
995
- params
996
- });
997
- if ("error" in res) {
998
- toggleNotification({
999
- type: "danger",
1000
- message: formatAPIError(res.error)
1001
- });
1002
- return { error: res.error };
1003
- }
1004
- toggleNotification({
1005
- type: "success",
1006
- message: formatMessage({
1007
- id: "content-manager.success.record.discard",
1008
- defaultMessage: "Changes discarded"
1009
- })
1010
- });
1011
- return res.data;
1012
- } catch (err) {
1013
- toggleNotification({
1014
- type: "danger",
1015
- message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1016
- });
1017
- throw err;
1018
- }
1017
+ const editMetadatas = Object.entries(data.contentType.metadatas).reduce(
1018
+ (acc, [attribute, metadata]) => {
1019
+ return {
1020
+ ...acc,
1021
+ [attribute]: metadata.edit
1022
+ };
1019
1023
  },
1020
- [discardDocument, formatAPIError, formatMessage, toggleNotification]
1024
+ {}
1021
1025
  );
1022
- const [publishDocument] = usePublishDocumentMutation();
1023
- const publish = React__namespace.useCallback(
1024
- async ({ collectionType, model, documentId, params }, data) => {
1025
- try {
1026
- trackUsage("willPublishEntry");
1027
- const res = await publishDocument({
1028
- collectionType,
1029
- model,
1030
- documentId,
1031
- data,
1032
- params
1033
- });
1034
- if ("error" in res) {
1035
- toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1036
- return { error: res.error };
1037
- }
1038
- trackUsage("didPublishEntry");
1039
- toggleNotification({
1040
- type: "success",
1041
- message: formatMessage({
1042
- id: getTranslation("success.record.publish"),
1043
- defaultMessage: "Published document"
1044
- })
1045
- });
1046
- return res.data;
1047
- } catch (err) {
1048
- toggleNotification({
1049
- type: "danger",
1050
- message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1051
- });
1052
- throw err;
1053
- }
1026
+ return {
1027
+ layout: panelledEditAttributes,
1028
+ components: componentEditAttributes,
1029
+ metadatas: editMetadatas,
1030
+ settings: {
1031
+ ...data.contentType.settings,
1032
+ displayName: schema?.info.displayName
1054
1033
  },
1055
- [trackUsage, publishDocument, toggleNotification, formatMessage, formatAPIError]
1056
- );
1057
- const [publishManyDocuments] = usePublishManyDocumentsMutation();
1058
- const publishMany = React__namespace.useCallback(
1059
- async ({ model, documentIds, params }) => {
1060
- try {
1061
- const res = await publishManyDocuments({
1062
- model,
1063
- documentIds,
1064
- params
1065
- });
1066
- if ("error" in res) {
1067
- toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1068
- return { error: res.error };
1069
- }
1070
- toggleNotification({
1071
- type: "success",
1072
- message: formatMessage({
1073
- id: getTranslation("success.record.publish"),
1074
- defaultMessage: "Published document"
1075
- })
1076
- });
1077
- return res.data;
1078
- } catch (err) {
1079
- toggleNotification({
1080
- type: "danger",
1081
- message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1082
- });
1083
- throw err;
1034
+ options: {
1035
+ ...schema?.options,
1036
+ ...schema?.pluginOptions,
1037
+ ...data.contentType.options
1038
+ }
1039
+ };
1040
+ };
1041
+ const convertEditLayoutToFieldLayouts = (rows, attributes = {}, metadatas, components, schemas = []) => {
1042
+ return rows.map(
1043
+ (row) => row.map((field) => {
1044
+ const attribute = attributes[field.name];
1045
+ if (!attribute) {
1046
+ return null;
1084
1047
  }
1085
- },
1086
- [
1087
- // trackUsage,
1088
- publishManyDocuments,
1089
- toggleNotification,
1090
- formatMessage,
1091
- formatAPIError
1092
- ]
1048
+ const { edit: metadata } = metadatas[field.name];
1049
+ const settings = attribute.type === "component" && components ? components.configurations[attribute.component].settings : {};
1050
+ return {
1051
+ attribute,
1052
+ disabled: !metadata.editable,
1053
+ hint: metadata.description,
1054
+ label: metadata.label ?? "",
1055
+ name: field.name,
1056
+ // @ts-expect-error – mainField does exist on the metadata for a relation.
1057
+ mainField: getMainField(attribute, metadata.mainField || settings.mainField, {
1058
+ schemas,
1059
+ components: components?.schemas ?? {}
1060
+ }),
1061
+ placeholder: metadata.placeholder ?? "",
1062
+ required: attribute.required ?? false,
1063
+ size: field.size,
1064
+ unique: "unique" in attribute ? attribute.unique : false,
1065
+ visible: metadata.visible ?? true,
1066
+ type: attribute.type
1067
+ };
1068
+ }).filter((field) => field !== null)
1093
1069
  );
1094
- const [updateDocument] = useUpdateDocumentMutation();
1095
- const update = React__namespace.useCallback(
1096
- async ({ collectionType, model, documentId, params }, data, trackerProperty) => {
1097
- try {
1098
- trackUsage("willEditEntry", trackerProperty);
1099
- const res = await updateDocument({
1100
- collectionType,
1101
- model,
1102
- documentId,
1103
- data,
1104
- params
1105
- });
1106
- if ("error" in res) {
1107
- toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1108
- trackUsage("didNotEditEntry", { error: res.error, ...trackerProperty });
1109
- return { error: res.error };
1070
+ };
1071
+ const formatListLayout = (data, {
1072
+ schemas,
1073
+ schema,
1074
+ components
1075
+ }) => {
1076
+ const listMetadatas = Object.entries(data.contentType.metadatas).reduce(
1077
+ (acc, [attribute, metadata]) => {
1078
+ return {
1079
+ ...acc,
1080
+ [attribute]: metadata.list
1081
+ };
1082
+ },
1083
+ {}
1084
+ );
1085
+ const listAttributes = convertListLayoutToFieldLayouts(
1086
+ data.contentType.layouts.list,
1087
+ schema?.attributes,
1088
+ listMetadatas,
1089
+ { configurations: data.components, schemas: components },
1090
+ schemas
1091
+ );
1092
+ return {
1093
+ layout: listAttributes,
1094
+ settings: { ...data.contentType.settings, displayName: schema?.info.displayName },
1095
+ metadatas: listMetadatas,
1096
+ options: {
1097
+ ...schema?.options,
1098
+ ...schema?.pluginOptions,
1099
+ ...data.contentType.options
1100
+ }
1101
+ };
1102
+ };
1103
+ const convertListLayoutToFieldLayouts = (columns, attributes = {}, metadatas, components, schemas = []) => {
1104
+ return columns.map((name) => {
1105
+ const attribute = attributes[name];
1106
+ if (!attribute) {
1107
+ return null;
1108
+ }
1109
+ const metadata = metadatas[name];
1110
+ const settings = attribute.type === "component" && components ? components.configurations[attribute.component].settings : {};
1111
+ return {
1112
+ attribute,
1113
+ label: metadata.label ?? "",
1114
+ mainField: getMainField(attribute, metadata.mainField || settings.mainField, {
1115
+ schemas,
1116
+ components: components?.schemas ?? {}
1117
+ }),
1118
+ name,
1119
+ searchable: metadata.searchable ?? true,
1120
+ sortable: metadata.sortable ?? true
1121
+ };
1122
+ }).filter((field) => field !== null);
1123
+ };
1124
+ const useDocument = (args, opts) => {
1125
+ const { toggleNotification } = strapiAdmin.useNotification();
1126
+ const { _unstableFormatAPIError: formatAPIError } = strapiAdmin.useAPIErrorHandler();
1127
+ const {
1128
+ currentData: data,
1129
+ isLoading: isLoadingDocument,
1130
+ isFetching: isFetchingDocument,
1131
+ error
1132
+ } = useGetDocumentQuery(args, {
1133
+ ...opts,
1134
+ skip: !args.documentId && args.collectionType !== SINGLE_TYPES || opts?.skip
1135
+ });
1136
+ const {
1137
+ components,
1138
+ schema,
1139
+ schemas,
1140
+ isLoading: isLoadingSchema
1141
+ } = useContentTypeSchema(args.model);
1142
+ React__namespace.useEffect(() => {
1143
+ if (error) {
1144
+ toggleNotification({
1145
+ type: "danger",
1146
+ message: formatAPIError(error)
1147
+ });
1148
+ }
1149
+ }, [toggleNotification, error, formatAPIError, args.collectionType]);
1150
+ const validationSchema = React__namespace.useMemo(() => {
1151
+ if (!schema) {
1152
+ return null;
1153
+ }
1154
+ return createYupSchema(schema.attributes, components);
1155
+ }, [schema, components]);
1156
+ const validate = React__namespace.useCallback(
1157
+ (document) => {
1158
+ if (!validationSchema) {
1159
+ throw new Error(
1160
+ "There is no validation schema generated, this is likely due to the schema not being loaded yet."
1161
+ );
1162
+ }
1163
+ try {
1164
+ validationSchema.validateSync(document, { abortEarly: false, strict: true });
1165
+ return null;
1166
+ } catch (error2) {
1167
+ if (error2 instanceof yup.ValidationError) {
1168
+ return strapiAdmin.getYupValidationErrors(error2);
1110
1169
  }
1111
- trackUsage("didEditEntry", trackerProperty);
1112
- toggleNotification({
1113
- type: "success",
1114
- message: formatMessage({
1115
- id: getTranslation("success.record.save"),
1116
- defaultMessage: "Saved document"
1117
- })
1118
- });
1119
- return res.data;
1120
- } catch (err) {
1121
- trackUsage("didNotEditEntry", { error: err, ...trackerProperty });
1122
- toggleNotification({
1123
- type: "danger",
1124
- message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1125
- });
1126
- throw err;
1170
+ throw error2;
1127
1171
  }
1128
1172
  },
1129
- [trackUsage, updateDocument, toggleNotification, formatMessage, formatAPIError]
1173
+ [validationSchema]
1130
1174
  );
1131
- const [unpublishDocument] = useUnpublishDocumentMutation();
1132
- const unpublish = React__namespace.useCallback(
1133
- async ({ collectionType, model, documentId, params }, discardDraft = false) => {
1175
+ const isLoading = isLoadingDocument || isFetchingDocument || isLoadingSchema;
1176
+ const hasError = !!error;
1177
+ return {
1178
+ components,
1179
+ document: data?.data,
1180
+ meta: data?.meta,
1181
+ isLoading,
1182
+ hasError,
1183
+ schema,
1184
+ schemas,
1185
+ validate
1186
+ };
1187
+ };
1188
+ const useDoc = () => {
1189
+ const { id, slug, collectionType, origin } = reactRouterDom.useParams();
1190
+ const [{ query }] = strapiAdmin.useQueryParams();
1191
+ const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
1192
+ if (!collectionType) {
1193
+ throw new Error("Could not find collectionType in url params");
1194
+ }
1195
+ if (!slug) {
1196
+ throw new Error("Could not find model in url params");
1197
+ }
1198
+ const document = useDocument(
1199
+ { documentId: origin || id, model: slug, collectionType, params },
1200
+ {
1201
+ skip: id === "create" || !origin && !id && collectionType !== SINGLE_TYPES
1202
+ }
1203
+ );
1204
+ const returnId = origin || id === "create" ? void 0 : id;
1205
+ return {
1206
+ collectionType,
1207
+ model: slug,
1208
+ id: returnId,
1209
+ ...document
1210
+ };
1211
+ };
1212
+ const useContentManagerContext = () => {
1213
+ const {
1214
+ collectionType,
1215
+ model,
1216
+ id,
1217
+ components,
1218
+ isLoading: isLoadingDoc,
1219
+ schema,
1220
+ schemas
1221
+ } = useDoc();
1222
+ const layout = useDocumentLayout(model);
1223
+ const form = strapiAdmin.useForm("useContentManagerContext", (state) => state);
1224
+ const isSingleType = collectionType === SINGLE_TYPES;
1225
+ const slug = model;
1226
+ const isCreatingEntry = id === "create";
1227
+ useContentTypeSchema();
1228
+ const isLoading = isLoadingDoc || layout.isLoading;
1229
+ const error = layout.error;
1230
+ return {
1231
+ error,
1232
+ isLoading,
1233
+ // Base metadata
1234
+ model,
1235
+ collectionType,
1236
+ id,
1237
+ slug,
1238
+ isCreatingEntry,
1239
+ isSingleType,
1240
+ hasDraftAndPublish: schema?.options?.draftAndPublish ?? false,
1241
+ // All schema infos
1242
+ components,
1243
+ contentType: schema,
1244
+ contentTypes: schemas,
1245
+ // Form state
1246
+ form,
1247
+ // layout infos
1248
+ layout
1249
+ };
1250
+ };
1251
+ const prefixPluginTranslations = (trad, pluginId) => {
1252
+ if (!pluginId) {
1253
+ throw new TypeError("pluginId can't be empty");
1254
+ }
1255
+ return Object.keys(trad).reduce((acc, current) => {
1256
+ acc[`${pluginId}.${current}`] = trad[current];
1257
+ return acc;
1258
+ }, {});
1259
+ };
1260
+ const getTranslation = (id) => `content-manager.${id}`;
1261
+ const DEFAULT_UNEXPECTED_ERROR_MSG = {
1262
+ id: "notification.error",
1263
+ defaultMessage: "An error occurred, please try again"
1264
+ };
1265
+ const useDocumentActions = () => {
1266
+ const { toggleNotification } = strapiAdmin.useNotification();
1267
+ const { formatMessage } = reactIntl.useIntl();
1268
+ const { trackUsage } = strapiAdmin.useTracking();
1269
+ const { _unstableFormatAPIError: formatAPIError } = strapiAdmin.useAPIErrorHandler();
1270
+ const navigate = reactRouterDom.useNavigate();
1271
+ const setCurrentStep = strapiAdmin.useGuidedTour("useDocumentActions", (state) => state.setCurrentStep);
1272
+ const [deleteDocument] = useDeleteDocumentMutation();
1273
+ const _delete = React__namespace.useCallback(
1274
+ async ({ collectionType, model, documentId, params }, trackerProperty) => {
1134
1275
  try {
1135
- trackUsage("willUnpublishEntry");
1136
- const res = await unpublishDocument({
1276
+ trackUsage("willDeleteEntry", trackerProperty);
1277
+ const res = await deleteDocument({
1137
1278
  collectionType,
1138
1279
  model,
1139
1280
  documentId,
1140
- params,
1141
- data: {
1142
- discardDraft
1143
- }
1281
+ params
1144
1282
  });
1145
1283
  if ("error" in res) {
1146
- toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1284
+ toggleNotification({
1285
+ type: "danger",
1286
+ message: formatAPIError(res.error)
1287
+ });
1147
1288
  return { error: res.error };
1148
1289
  }
1149
- trackUsage("didUnpublishEntry");
1150
1290
  toggleNotification({
1151
1291
  type: "success",
1152
1292
  message: formatMessage({
1153
- id: getTranslation("success.record.unpublish"),
1154
- defaultMessage: "Unpublished document"
1293
+ id: getTranslation("success.record.delete"),
1294
+ defaultMessage: "Deleted document"
1155
1295
  })
1156
1296
  });
1297
+ trackUsage("didDeleteEntry", trackerProperty);
1157
1298
  return res.data;
1158
1299
  } catch (err) {
1159
1300
  toggleNotification({
1160
1301
  type: "danger",
1161
1302
  message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1162
1303
  });
1304
+ trackUsage("didNotDeleteEntry", { error: err, ...trackerProperty });
1163
1305
  throw err;
1164
1306
  }
1165
1307
  },
1166
- [trackUsage, unpublishDocument, toggleNotification, formatMessage, formatAPIError]
1308
+ [trackUsage, deleteDocument, toggleNotification, formatMessage, formatAPIError]
1167
1309
  );
1168
- const [unpublishManyDocuments] = useUnpublishManyDocumentsMutation();
1169
- const unpublishMany = React__namespace.useCallback(
1310
+ const [deleteManyDocuments] = useDeleteManyDocumentsMutation();
1311
+ const deleteMany = React__namespace.useCallback(
1170
1312
  async ({ model, documentIds, params }) => {
1171
1313
  try {
1172
- trackUsage("willBulkUnpublishEntries");
1173
- const res = await unpublishManyDocuments({
1314
+ trackUsage("willBulkDeleteEntries");
1315
+ const res = await deleteManyDocuments({
1174
1316
  model,
1175
1317
  documentIds,
1176
1318
  params
1177
1319
  });
1178
1320
  if ("error" in res) {
1179
- toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1321
+ toggleNotification({
1322
+ type: "danger",
1323
+ message: formatAPIError(res.error)
1324
+ });
1180
1325
  return { error: res.error };
1181
1326
  }
1182
- trackUsage("didBulkUnpublishEntries");
1183
1327
  toggleNotification({
1184
1328
  type: "success",
1185
1329
  title: formatMessage({
1186
- id: getTranslation("success.records.unpublish"),
1187
- defaultMessage: "Successfully unpublished."
1330
+ id: getTranslation("success.records.delete"),
1331
+ defaultMessage: "Successfully deleted."
1188
1332
  }),
1189
1333
  message: ""
1190
1334
  });
1335
+ trackUsage("didBulkDeleteEntries");
1191
1336
  return res.data;
1192
1337
  } catch (err) {
1193
1338
  toggleNotification({
1194
1339
  type: "danger",
1195
1340
  message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1196
1341
  });
1197
- trackUsage("didNotBulkUnpublishEntries");
1342
+ trackUsage("didNotBulkDeleteEntries");
1198
1343
  throw err;
1199
1344
  }
1200
1345
  },
1201
- [trackUsage, unpublishManyDocuments, toggleNotification, formatMessage, formatAPIError]
1346
+ [trackUsage, deleteManyDocuments, toggleNotification, formatMessage, formatAPIError]
1202
1347
  );
1203
- const [createDocument] = useCreateDocumentMutation();
1204
- const create = React__namespace.useCallback(
1205
- async ({ model, params }, data, trackerProperty) => {
1348
+ const [discardDocument] = useDiscardDocumentMutation();
1349
+ const discard = React__namespace.useCallback(
1350
+ async ({ collectionType, model, documentId, params }) => {
1206
1351
  try {
1207
- const res = await createDocument({
1352
+ const res = await discardDocument({
1353
+ collectionType,
1208
1354
  model,
1209
- data,
1355
+ documentId,
1210
1356
  params
1211
1357
  });
1212
1358
  if ("error" in res) {
1213
- toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1214
- trackUsage("didNotCreateEntry", { error: res.error, ...trackerProperty });
1359
+ toggleNotification({
1360
+ type: "danger",
1361
+ message: formatAPIError(res.error)
1362
+ });
1215
1363
  return { error: res.error };
1216
1364
  }
1217
- trackUsage("didCreateEntry", trackerProperty);
1218
1365
  toggleNotification({
1219
1366
  type: "success",
1220
1367
  message: formatMessage({
1221
- id: getTranslation("success.record.save"),
1222
- defaultMessage: "Saved document"
1368
+ id: "content-manager.success.record.discard",
1369
+ defaultMessage: "Changes discarded"
1370
+ })
1371
+ });
1372
+ return res.data;
1373
+ } catch (err) {
1374
+ toggleNotification({
1375
+ type: "danger",
1376
+ message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1377
+ });
1378
+ throw err;
1379
+ }
1380
+ },
1381
+ [discardDocument, formatAPIError, formatMessage, toggleNotification]
1382
+ );
1383
+ const [publishDocument] = usePublishDocumentMutation();
1384
+ const publish = React__namespace.useCallback(
1385
+ async ({ collectionType, model, documentId, params }, data) => {
1386
+ try {
1387
+ trackUsage("willPublishEntry");
1388
+ const res = await publishDocument({
1389
+ collectionType,
1390
+ model,
1391
+ documentId,
1392
+ data,
1393
+ params
1394
+ });
1395
+ if ("error" in res) {
1396
+ toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1397
+ return { error: res.error };
1398
+ }
1399
+ trackUsage("didPublishEntry");
1400
+ toggleNotification({
1401
+ type: "success",
1402
+ message: formatMessage({
1403
+ id: getTranslation("success.record.publish"),
1404
+ defaultMessage: "Published document"
1405
+ })
1406
+ });
1407
+ return res.data;
1408
+ } catch (err) {
1409
+ toggleNotification({
1410
+ type: "danger",
1411
+ message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1412
+ });
1413
+ throw err;
1414
+ }
1415
+ },
1416
+ [trackUsage, publishDocument, toggleNotification, formatMessage, formatAPIError]
1417
+ );
1418
+ const [publishManyDocuments] = usePublishManyDocumentsMutation();
1419
+ const publishMany = React__namespace.useCallback(
1420
+ async ({ model, documentIds, params }) => {
1421
+ try {
1422
+ const res = await publishManyDocuments({
1423
+ model,
1424
+ documentIds,
1425
+ params
1426
+ });
1427
+ if ("error" in res) {
1428
+ toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1429
+ return { error: res.error };
1430
+ }
1431
+ toggleNotification({
1432
+ type: "success",
1433
+ message: formatMessage({
1434
+ id: getTranslation("success.record.publish"),
1435
+ defaultMessage: "Published document"
1436
+ })
1437
+ });
1438
+ return res.data;
1439
+ } catch (err) {
1440
+ toggleNotification({
1441
+ type: "danger",
1442
+ message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1443
+ });
1444
+ throw err;
1445
+ }
1446
+ },
1447
+ [
1448
+ // trackUsage,
1449
+ publishManyDocuments,
1450
+ toggleNotification,
1451
+ formatMessage,
1452
+ formatAPIError
1453
+ ]
1454
+ );
1455
+ const [updateDocument] = useUpdateDocumentMutation();
1456
+ const update = React__namespace.useCallback(
1457
+ async ({ collectionType, model, documentId, params }, data, trackerProperty) => {
1458
+ try {
1459
+ trackUsage("willEditEntry", trackerProperty);
1460
+ const res = await updateDocument({
1461
+ collectionType,
1462
+ model,
1463
+ documentId,
1464
+ data,
1465
+ params
1466
+ });
1467
+ if ("error" in res) {
1468
+ toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1469
+ trackUsage("didNotEditEntry", { error: res.error, ...trackerProperty });
1470
+ return { error: res.error };
1471
+ }
1472
+ trackUsage("didEditEntry", trackerProperty);
1473
+ toggleNotification({
1474
+ type: "success",
1475
+ message: formatMessage({
1476
+ id: getTranslation("success.record.save"),
1477
+ defaultMessage: "Saved document"
1478
+ })
1479
+ });
1480
+ return res.data;
1481
+ } catch (err) {
1482
+ trackUsage("didNotEditEntry", { error: err, ...trackerProperty });
1483
+ toggleNotification({
1484
+ type: "danger",
1485
+ message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1486
+ });
1487
+ throw err;
1488
+ }
1489
+ },
1490
+ [trackUsage, updateDocument, toggleNotification, formatMessage, formatAPIError]
1491
+ );
1492
+ const [unpublishDocument] = useUnpublishDocumentMutation();
1493
+ const unpublish = React__namespace.useCallback(
1494
+ async ({ collectionType, model, documentId, params }, discardDraft = false) => {
1495
+ try {
1496
+ trackUsage("willUnpublishEntry");
1497
+ const res = await unpublishDocument({
1498
+ collectionType,
1499
+ model,
1500
+ documentId,
1501
+ params,
1502
+ data: {
1503
+ discardDraft
1504
+ }
1505
+ });
1506
+ if ("error" in res) {
1507
+ toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1508
+ return { error: res.error };
1509
+ }
1510
+ trackUsage("didUnpublishEntry");
1511
+ toggleNotification({
1512
+ type: "success",
1513
+ message: formatMessage({
1514
+ id: getTranslation("success.record.unpublish"),
1515
+ defaultMessage: "Unpublished document"
1516
+ })
1517
+ });
1518
+ return res.data;
1519
+ } catch (err) {
1520
+ toggleNotification({
1521
+ type: "danger",
1522
+ message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1523
+ });
1524
+ throw err;
1525
+ }
1526
+ },
1527
+ [trackUsage, unpublishDocument, toggleNotification, formatMessage, formatAPIError]
1528
+ );
1529
+ const [unpublishManyDocuments] = useUnpublishManyDocumentsMutation();
1530
+ const unpublishMany = React__namespace.useCallback(
1531
+ async ({ model, documentIds, params }) => {
1532
+ try {
1533
+ trackUsage("willBulkUnpublishEntries");
1534
+ const res = await unpublishManyDocuments({
1535
+ model,
1536
+ documentIds,
1537
+ params
1538
+ });
1539
+ if ("error" in res) {
1540
+ toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1541
+ return { error: res.error };
1542
+ }
1543
+ trackUsage("didBulkUnpublishEntries");
1544
+ toggleNotification({
1545
+ type: "success",
1546
+ title: formatMessage({
1547
+ id: getTranslation("success.records.unpublish"),
1548
+ defaultMessage: "Successfully unpublished."
1549
+ }),
1550
+ message: ""
1551
+ });
1552
+ return res.data;
1553
+ } catch (err) {
1554
+ toggleNotification({
1555
+ type: "danger",
1556
+ message: formatMessage(DEFAULT_UNEXPECTED_ERROR_MSG)
1557
+ });
1558
+ trackUsage("didNotBulkUnpublishEntries");
1559
+ throw err;
1560
+ }
1561
+ },
1562
+ [trackUsage, unpublishManyDocuments, toggleNotification, formatMessage, formatAPIError]
1563
+ );
1564
+ const [createDocument] = useCreateDocumentMutation();
1565
+ const create = React__namespace.useCallback(
1566
+ async ({ model, params }, data, trackerProperty) => {
1567
+ try {
1568
+ const res = await createDocument({
1569
+ model,
1570
+ data,
1571
+ params
1572
+ });
1573
+ if ("error" in res) {
1574
+ toggleNotification({ type: "danger", message: formatAPIError(res.error) });
1575
+ trackUsage("didNotCreateEntry", { error: res.error, ...trackerProperty });
1576
+ return { error: res.error };
1577
+ }
1578
+ trackUsage("didCreateEntry", trackerProperty);
1579
+ toggleNotification({
1580
+ type: "success",
1581
+ message: formatMessage({
1582
+ id: getTranslation("success.record.save"),
1583
+ defaultMessage: "Saved document"
1223
1584
  })
1224
1585
  });
1586
+ setCurrentStep("contentManager.success");
1225
1587
  return res.data;
1226
1588
  } catch (err) {
1227
1589
  toggleNotification({
@@ -1324,7 +1686,7 @@ const useDocumentActions = () => {
1324
1686
  };
1325
1687
  };
1326
1688
  const ProtectedHistoryPage = React.lazy(
1327
- () => Promise.resolve().then(() => require("./History-Dh2NEHnR.js")).then((mod) => ({ default: mod.ProtectedHistoryPage }))
1689
+ () => Promise.resolve().then(() => require("./History-C9t9UqpO.js")).then((mod) => ({ default: mod.ProtectedHistoryPage }))
1328
1690
  );
1329
1691
  const routes$1 = [
1330
1692
  {
@@ -1337,31 +1699,31 @@ const routes$1 = [
1337
1699
  }
1338
1700
  ];
1339
1701
  const ProtectedEditViewPage = React.lazy(
1340
- () => Promise.resolve().then(() => require("./EditViewPage-B-RJeiJD.js")).then((mod) => ({ default: mod.ProtectedEditViewPage }))
1702
+ () => Promise.resolve().then(() => require("./EditViewPage-DlxEHhUt.js")).then((mod) => ({ default: mod.ProtectedEditViewPage }))
1341
1703
  );
1342
1704
  const ProtectedListViewPage = React.lazy(
1343
- () => Promise.resolve().then(() => require("./ListViewPage-4XsciqHZ.js")).then((mod) => ({ default: mod.ProtectedListViewPage }))
1705
+ () => Promise.resolve().then(() => require("./ListViewPage-D2VD8Szg.js")).then((mod) => ({ default: mod.ProtectedListViewPage }))
1344
1706
  );
1345
1707
  const ProtectedListConfiguration = React.lazy(
1346
- () => Promise.resolve().then(() => require("./ListConfigurationPage-BxYCWz9e.js")).then((mod) => ({
1708
+ () => Promise.resolve().then(() => require("./ListConfigurationPage-BXYPohh-.js")).then((mod) => ({
1347
1709
  default: mod.ProtectedListConfiguration
1348
1710
  }))
1349
1711
  );
1350
1712
  const ProtectedEditConfigurationPage = React.lazy(
1351
- () => Promise.resolve().then(() => require("./EditConfigurationPage-BePwPuHy.js")).then((mod) => ({
1713
+ () => Promise.resolve().then(() => require("./EditConfigurationPage-Cn0e8t3I.js")).then((mod) => ({
1352
1714
  default: mod.ProtectedEditConfigurationPage
1353
1715
  }))
1354
1716
  );
1355
1717
  const ProtectedComponentConfigurationPage = React.lazy(
1356
- () => Promise.resolve().then(() => require("./ComponentConfigurationPage-D_M8iBw5.js")).then((mod) => ({
1718
+ () => Promise.resolve().then(() => require("./ComponentConfigurationPage-FqfsxQ1j.js")).then((mod) => ({
1357
1719
  default: mod.ProtectedComponentConfigurationPage
1358
1720
  }))
1359
1721
  );
1360
1722
  const NoPermissions = React.lazy(
1361
- () => Promise.resolve().then(() => require("./NoPermissionsPage-y_r7DVA2.js")).then((mod) => ({ default: mod.NoPermissions }))
1723
+ () => Promise.resolve().then(() => require("./NoPermissionsPage-Dp8NpF9I.js")).then((mod) => ({ default: mod.NoPermissions }))
1362
1724
  );
1363
1725
  const NoContentType = React.lazy(
1364
- () => Promise.resolve().then(() => require("./NoContentTypePage-C8OpoHeU.js")).then((mod) => ({ default: mod.NoContentType }))
1726
+ () => Promise.resolve().then(() => require("./NoContentTypePage-BV9IjJSM.js")).then((mod) => ({ default: mod.NoContentType }))
1365
1727
  );
1366
1728
  const CollectionTypePages = () => {
1367
1729
  const { collectionType } = reactRouterDom.useParams();
@@ -1417,1065 +1779,735 @@ const DocumentActions = ({ actions: actions2 }) => {
1417
1779
  }
1418
1780
  const positions = Array.isArray(action.position) ? action.position : [action.position];
1419
1781
  return positions.includes("panel");
1420
- });
1421
- if (!primaryAction) {
1422
- return null;
1423
- }
1424
- return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, alignItems: "stretch", width: "100%", children: [
1425
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
1426
- /* @__PURE__ */ jsxRuntime.jsx(DocumentActionButton, { ...primaryAction, variant: primaryAction.variant || "default" }),
1427
- restActions.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
1428
- DocumentActionsMenu,
1429
- {
1430
- actions: restActions,
1431
- label: formatMessage({
1432
- id: "content-manager.containers.edit.panels.default.more-actions",
1433
- defaultMessage: "More document actions"
1434
- })
1435
- }
1436
- ) : null
1437
- ] }),
1438
- secondaryAction ? /* @__PURE__ */ jsxRuntime.jsx(
1439
- DocumentActionButton,
1440
- {
1441
- ...secondaryAction,
1442
- variant: secondaryAction.variant || "secondary"
1443
- }
1444
- ) : null
1445
- ] });
1446
- };
1447
- const DocumentActionButton = (action) => {
1448
- const [dialogId, setDialogId] = React__namespace.useState(null);
1449
- const { toggleNotification } = strapiAdmin.useNotification();
1450
- const handleClick = (action2) => async (e) => {
1451
- const { onClick = () => false, dialog, id } = action2;
1452
- const muteDialog = await onClick(e);
1453
- if (dialog && !muteDialog) {
1454
- switch (dialog.type) {
1455
- case "notification":
1456
- toggleNotification({
1457
- title: dialog.title,
1458
- message: dialog.content,
1459
- type: dialog.status,
1460
- timeout: dialog.timeout,
1461
- onClose: dialog.onClose
1462
- });
1463
- break;
1464
- case "dialog":
1465
- case "modal":
1466
- e.preventDefault();
1467
- setDialogId(id);
1468
- }
1469
- }
1470
- };
1471
- const handleClose = () => {
1472
- setDialogId(null);
1473
- };
1474
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1475
- /* @__PURE__ */ jsxRuntime.jsx(
1476
- designSystem.Button,
1477
- {
1478
- flex: "auto",
1479
- startIcon: action.icon,
1480
- disabled: action.disabled,
1481
- onClick: handleClick(action),
1482
- justifyContent: "center",
1483
- variant: action.variant || "default",
1484
- paddingTop: "7px",
1485
- paddingBottom: "7px",
1486
- children: action.label
1487
- }
1488
- ),
1489
- action.dialog?.type === "dialog" ? /* @__PURE__ */ jsxRuntime.jsx(
1490
- DocumentActionConfirmDialog,
1491
- {
1492
- ...action.dialog,
1493
- variant: action.dialog?.variant ?? action.variant,
1494
- isOpen: dialogId === action.id,
1495
- onClose: handleClose
1496
- }
1497
- ) : null,
1498
- action.dialog?.type === "modal" ? /* @__PURE__ */ jsxRuntime.jsx(
1499
- DocumentActionModal,
1500
- {
1501
- ...action.dialog,
1502
- onModalClose: handleClose,
1503
- isOpen: dialogId === action.id
1504
- }
1505
- ) : null
1506
- ] });
1507
- };
1508
- const DocumentActionsMenu = ({
1509
- actions: actions2,
1510
- children,
1511
- label,
1512
- variant = "tertiary"
1513
- }) => {
1514
- const [isOpen, setIsOpen] = React__namespace.useState(false);
1515
- const [dialogId, setDialogId] = React__namespace.useState(null);
1516
- const { formatMessage } = reactIntl.useIntl();
1517
- const { toggleNotification } = strapiAdmin.useNotification();
1518
- const isDisabled = actions2.every((action) => action.disabled) || actions2.length === 0;
1519
- const handleClick = (action) => async (e) => {
1520
- const { onClick = () => false, dialog, id } = action;
1521
- const muteDialog = await onClick(e);
1522
- if (dialog && !muteDialog) {
1523
- switch (dialog.type) {
1524
- case "notification":
1525
- toggleNotification({
1526
- title: dialog.title,
1527
- message: dialog.content,
1528
- type: dialog.status,
1529
- timeout: dialog.timeout,
1530
- onClose: dialog.onClose
1531
- });
1532
- break;
1533
- case "dialog":
1534
- case "modal":
1535
- setDialogId(id);
1536
- }
1537
- }
1538
- };
1539
- const handleClose = () => {
1540
- setDialogId(null);
1541
- setIsOpen(false);
1542
- };
1543
- return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Menu.Root, { open: isOpen, onOpenChange: setIsOpen, children: [
1544
- /* @__PURE__ */ jsxRuntime.jsxs(
1545
- StyledMoreButton,
1546
- {
1547
- disabled: isDisabled,
1548
- size: "S",
1549
- endIcon: null,
1550
- paddingTop: "4px",
1551
- paddingLeft: "7px",
1552
- paddingRight: "7px",
1553
- variant,
1554
- children: [
1555
- /* @__PURE__ */ jsxRuntime.jsx(Icons.More, { "aria-hidden": true, focusable: false }),
1556
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { tag: "span", children: label || formatMessage({
1557
- id: "content-manager.containers.edit.panels.default.more-actions",
1558
- defaultMessage: "More document actions"
1559
- }) })
1560
- ]
1561
- }
1562
- ),
1563
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Menu.Content, { top: "4px", maxHeight: void 0, popoverPlacement: "bottom-end", children: [
1564
- actions2.map((action) => {
1565
- return /* @__PURE__ */ jsxRuntime.jsx(
1566
- designSystem.Menu.Item,
1567
- {
1568
- disabled: action.disabled,
1569
- onSelect: handleClick(action),
1570
- display: "block",
1571
- children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", gap: 4, children: [
1572
- /* @__PURE__ */ jsxRuntime.jsxs(
1573
- designSystem.Flex,
1574
- {
1575
- color: !action.disabled ? convertActionVariantToColor(action.variant) : "inherit",
1576
- gap: 2,
1577
- tag: "span",
1578
- children: [
1579
- /* @__PURE__ */ jsxRuntime.jsx(
1580
- designSystem.Flex,
1581
- {
1582
- tag: "span",
1583
- color: !action.disabled ? convertActionVariantToIconColor(action.variant) : "inherit",
1584
- children: action.icon
1585
- }
1586
- ),
1587
- action.label
1588
- ]
1589
- }
1590
- ),
1591
- action.id.startsWith("HistoryAction") && /* @__PURE__ */ jsxRuntime.jsx(
1592
- designSystem.Flex,
1593
- {
1594
- alignItems: "center",
1595
- background: "alternative100",
1596
- borderStyle: "solid",
1597
- borderColor: "alternative200",
1598
- borderWidth: "1px",
1599
- height: 5,
1600
- paddingLeft: 2,
1601
- paddingRight: 2,
1602
- hasRadius: true,
1603
- color: "alternative600",
1604
- children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", fontWeight: "bold", lineHeight: 1, children: formatMessage({ id: "global.new", defaultMessage: "New" }) })
1605
- }
1606
- )
1607
- ] })
1608
- },
1609
- action.id
1610
- );
1611
- }),
1612
- children
1613
- ] }),
1614
- actions2.map((action) => {
1615
- return /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Fragment, { children: [
1616
- action.dialog?.type === "dialog" ? /* @__PURE__ */ jsxRuntime.jsx(
1617
- DocumentActionConfirmDialog,
1618
- {
1619
- ...action.dialog,
1620
- variant: action.variant,
1621
- isOpen: dialogId === action.id,
1622
- onClose: handleClose
1623
- }
1624
- ) : null,
1625
- action.dialog?.type === "modal" ? /* @__PURE__ */ jsxRuntime.jsx(
1626
- DocumentActionModal,
1627
- {
1628
- ...action.dialog,
1629
- onModalClose: handleClose,
1630
- isOpen: dialogId === action.id
1631
- }
1632
- ) : null
1633
- ] }, action.id);
1634
- })
1635
- ] });
1636
- };
1637
- const convertActionVariantToColor = (variant = "secondary") => {
1638
- switch (variant) {
1639
- case "danger":
1640
- return "danger600";
1641
- case "secondary":
1642
- return void 0;
1643
- case "success":
1644
- return "success600";
1645
- default:
1646
- return "primary600";
1647
- }
1648
- };
1649
- const convertActionVariantToIconColor = (variant = "secondary") => {
1650
- switch (variant) {
1651
- case "danger":
1652
- return "danger600";
1653
- case "secondary":
1654
- return "neutral500";
1655
- case "success":
1656
- return "success600";
1657
- default:
1658
- return "primary600";
1659
- }
1660
- };
1661
- const StyledMoreButton = styledComponents.styled(designSystem.Menu.Trigger)`
1662
- & > span {
1663
- display: flex;
1664
- }
1665
- `;
1666
- const DocumentActionConfirmDialog = ({
1667
- onClose,
1668
- onCancel,
1669
- onConfirm,
1670
- title,
1671
- content,
1672
- isOpen,
1673
- variant = "secondary"
1674
- }) => {
1675
- const { formatMessage } = reactIntl.useIntl();
1676
- const handleClose = async () => {
1677
- if (onCancel) {
1678
- await onCancel();
1679
- }
1680
- onClose();
1681
- };
1682
- const handleConfirm = async () => {
1683
- if (onConfirm) {
1684
- await onConfirm();
1685
- }
1686
- onClose();
1687
- };
1688
- return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Root, { open: isOpen, onOpenChange: handleClose, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Dialog.Content, { children: [
1689
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Header, { children: title }),
1690
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Body, { children: content }),
1691
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Dialog.Footer, { children: [
1692
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Cancel, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: formatMessage({
1693
- id: "app.components.Button.cancel",
1694
- defaultMessage: "Cancel"
1695
- }) }) }),
1696
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { onClick: handleConfirm, variant, children: formatMessage({
1697
- id: "app.components.Button.confirm",
1698
- defaultMessage: "Confirm"
1699
- }) })
1700
- ] })
1701
- ] }) });
1702
- };
1703
- const DocumentActionModal = ({
1704
- isOpen,
1705
- title,
1706
- onClose,
1707
- footer: Footer,
1708
- content: Content,
1709
- onModalClose
1710
- }) => {
1711
- const handleClose = () => {
1712
- if (onClose) {
1713
- onClose();
1714
- }
1715
- onModalClose();
1716
- };
1717
- return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Root, { open: isOpen, onOpenChange: handleClose, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { children: [
1718
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: title }) }),
1719
- typeof Content === "function" ? /* @__PURE__ */ jsxRuntime.jsx(Content, { onClose: handleClose }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: Content }),
1720
- typeof Footer === "function" ? /* @__PURE__ */ jsxRuntime.jsx(Footer, { onClose: handleClose }) : Footer
1721
- ] }) });
1722
- };
1723
- const PublishAction$1 = ({
1724
- activeTab,
1725
- documentId,
1726
- model,
1727
- collectionType,
1728
- meta,
1729
- document
1730
- }) => {
1731
- const { schema } = useDoc();
1732
- const navigate = reactRouterDom.useNavigate();
1733
- const { toggleNotification } = strapiAdmin.useNotification();
1734
- const { _unstableFormatValidationErrors: formatValidationErrors } = strapiAdmin.useAPIErrorHandler();
1735
- const isListView = reactRouterDom.useMatch(LIST_PATH) !== null;
1736
- const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
1737
- const { formatMessage } = reactIntl.useIntl();
1738
- const canPublish = useDocumentRBAC("PublishAction", ({ canPublish: canPublish2 }) => canPublish2);
1739
- const { publish } = useDocumentActions();
1740
- const [
1741
- countDraftRelations,
1742
- { isLoading: isLoadingDraftRelations, isError: isErrorDraftRelations }
1743
- ] = useLazyGetDraftRelationCountQuery();
1744
- const [localCountOfDraftRelations, setLocalCountOfDraftRelations] = React__namespace.useState(0);
1745
- const [serverCountOfDraftRelations, setServerCountOfDraftRelations] = React__namespace.useState(0);
1746
- const [{ query, rawQuery }] = strapiAdmin.useQueryParams();
1747
- const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
1748
- const modified = strapiAdmin.useForm("PublishAction", ({ modified: modified2 }) => modified2);
1749
- const setSubmitting = strapiAdmin.useForm("PublishAction", ({ setSubmitting: setSubmitting2 }) => setSubmitting2);
1750
- const isSubmitting = strapiAdmin.useForm("PublishAction", ({ isSubmitting: isSubmitting2 }) => isSubmitting2);
1751
- const validate = strapiAdmin.useForm("PublishAction", (state) => state.validate);
1752
- const setErrors = strapiAdmin.useForm("PublishAction", (state) => state.setErrors);
1753
- const formValues = strapiAdmin.useForm("PublishAction", ({ values }) => values);
1754
- React__namespace.useEffect(() => {
1755
- if (isErrorDraftRelations) {
1756
- toggleNotification({
1757
- type: "danger",
1758
- message: formatMessage({
1759
- id: getTranslation("error.records.fetch-draft-relatons"),
1760
- defaultMessage: "An error occurred while fetching draft relations on this document."
1761
- })
1762
- });
1763
- }
1764
- }, [isErrorDraftRelations, toggleNotification, formatMessage]);
1765
- React__namespace.useEffect(() => {
1766
- const localDraftRelations = /* @__PURE__ */ new Set();
1767
- const extractDraftRelations = (data) => {
1768
- const relations = data.connect || [];
1769
- relations.forEach((relation) => {
1770
- if (relation.status === "draft") {
1771
- localDraftRelations.add(relation.id);
1772
- }
1773
- });
1774
- };
1775
- const traverseAndExtract = (data) => {
1776
- Object.entries(data).forEach(([key, value]) => {
1777
- if (key === "connect" && Array.isArray(value)) {
1778
- extractDraftRelations({ connect: value });
1779
- } else if (typeof value === "object" && value !== null) {
1780
- traverseAndExtract(value);
1781
- }
1782
- });
1783
- };
1784
- if (!documentId || modified) {
1785
- traverseAndExtract(formValues);
1786
- setLocalCountOfDraftRelations(localDraftRelations.size);
1787
- }
1788
- }, [documentId, modified, formValues, setLocalCountOfDraftRelations]);
1789
- React__namespace.useEffect(() => {
1790
- if (documentId && !isListView) {
1791
- const fetchDraftRelationsCount = async () => {
1792
- const { data, error } = await countDraftRelations({
1793
- collectionType,
1794
- model,
1795
- documentId,
1796
- params
1797
- });
1798
- if (error) {
1799
- throw error;
1800
- }
1801
- if (data) {
1802
- setServerCountOfDraftRelations(data.data);
1803
- }
1804
- };
1805
- fetchDraftRelationsCount();
1806
- }
1807
- }, [isListView, documentId, countDraftRelations, collectionType, model, params]);
1808
- const isDocumentPublished = (document?.[PUBLISHED_AT_ATTRIBUTE_NAME] || meta?.availableStatus.some((doc) => doc[PUBLISHED_AT_ATTRIBUTE_NAME] !== null)) && document?.status !== "modified";
1809
- if (!schema?.options?.draftAndPublish) {
1782
+ });
1783
+ if (!primaryAction) {
1810
1784
  return null;
1811
1785
  }
1812
- const performPublish = async () => {
1813
- setSubmitting(true);
1814
- try {
1815
- const { errors } = await validate();
1816
- if (errors) {
1817
- toggleNotification({
1818
- type: "danger",
1819
- message: formatMessage({
1820
- id: "content-manager.validation.error",
1821
- defaultMessage: "There are validation errors in your document. Please fix them before saving."
1822
- })
1823
- });
1824
- return;
1825
- }
1826
- const res = await publish(
1827
- {
1828
- collectionType,
1829
- model,
1830
- documentId,
1831
- params
1832
- },
1833
- formValues
1834
- );
1835
- if ("data" in res && collectionType !== SINGLE_TYPES) {
1836
- navigate({
1837
- pathname: `../${collectionType}/${model}/${res.data.documentId}`,
1838
- search: rawQuery
1839
- });
1840
- } else if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
1841
- setErrors(formatValidationErrors(res.error));
1842
- }
1843
- } finally {
1844
- setSubmitting(false);
1845
- }
1846
- };
1847
- const totalDraftRelations = localCountOfDraftRelations + serverCountOfDraftRelations;
1848
- const hasDraftRelations = totalDraftRelations > 0;
1849
- return {
1850
- /**
1851
- * Disabled when:
1852
- * - currently if you're cloning a document we don't support publish & clone at the same time.
1853
- * - the form is submitting
1854
- * - the active tab is the published tab
1855
- * - the document is already published & not modified
1856
- * - the document is being created & not modified
1857
- * - the user doesn't have the permission to publish
1858
- */
1859
- disabled: isCloning || isSubmitting || isLoadingDraftRelations || activeTab === "published" || !modified && isDocumentPublished || !modified && !document?.documentId || !canPublish,
1860
- label: formatMessage({
1861
- id: "app.utils.publish",
1862
- defaultMessage: "Publish"
1863
- }),
1864
- onClick: async () => {
1865
- if (hasDraftRelations) {
1866
- return;
1867
- }
1868
- await performPublish();
1869
- },
1870
- dialog: hasDraftRelations ? {
1871
- type: "dialog",
1872
- variant: "danger",
1873
- footer: null,
1874
- title: formatMessage({
1875
- id: getTranslation(`popUpwarning.warning.bulk-has-draft-relations.title`),
1876
- defaultMessage: "Confirmation"
1877
- }),
1878
- content: formatMessage(
1879
- {
1880
- id: getTranslation(`popUpwarning.warning.bulk-has-draft-relations.message`),
1881
- defaultMessage: "This entry is related to {count, plural, one {# draft entry} other {# draft entries}}. Publishing it could leave broken links in your app."
1882
- },
1786
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, alignItems: "stretch", width: "100%", children: [
1787
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
1788
+ /* @__PURE__ */ jsxRuntime.jsx(DocumentActionButton, { ...primaryAction, variant: primaryAction.variant || "default" }),
1789
+ restActions.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
1790
+ DocumentActionsMenu,
1883
1791
  {
1884
- count: totalDraftRelations
1792
+ actions: restActions,
1793
+ label: formatMessage({
1794
+ id: "content-manager.containers.edit.panels.default.more-actions",
1795
+ defaultMessage: "More document actions"
1796
+ })
1885
1797
  }
1886
- ),
1887
- onConfirm: async () => {
1888
- await performPublish();
1798
+ ) : null
1799
+ ] }),
1800
+ secondaryAction ? /* @__PURE__ */ jsxRuntime.jsx(
1801
+ DocumentActionButton,
1802
+ {
1803
+ ...secondaryAction,
1804
+ variant: secondaryAction.variant || "secondary"
1889
1805
  }
1890
- } : void 0
1891
- };
1806
+ ) : null
1807
+ ] });
1892
1808
  };
1893
- PublishAction$1.type = "publish";
1894
- const UpdateAction = ({
1895
- activeTab,
1896
- documentId,
1897
- model,
1898
- collectionType
1899
- }) => {
1900
- const navigate = reactRouterDom.useNavigate();
1809
+ const DocumentActionButton = (action) => {
1810
+ const [dialogId, setDialogId] = React__namespace.useState(null);
1901
1811
  const { toggleNotification } = strapiAdmin.useNotification();
1902
- const { _unstableFormatValidationErrors: formatValidationErrors } = strapiAdmin.useAPIErrorHandler();
1903
- const cloneMatch = reactRouterDom.useMatch(CLONE_PATH);
1904
- const isCloning = cloneMatch !== null;
1905
- const { formatMessage } = reactIntl.useIntl();
1906
- const { create, update, clone } = useDocumentActions();
1907
- const [{ query, rawQuery }] = strapiAdmin.useQueryParams();
1908
- const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
1909
- const isSubmitting = strapiAdmin.useForm("UpdateAction", ({ isSubmitting: isSubmitting2 }) => isSubmitting2);
1910
- const modified = strapiAdmin.useForm("UpdateAction", ({ modified: modified2 }) => modified2);
1911
- const setSubmitting = strapiAdmin.useForm("UpdateAction", ({ setSubmitting: setSubmitting2 }) => setSubmitting2);
1912
- const document = strapiAdmin.useForm("UpdateAction", ({ values }) => values);
1913
- const validate = strapiAdmin.useForm("UpdateAction", (state) => state.validate);
1914
- const setErrors = strapiAdmin.useForm("UpdateAction", (state) => state.setErrors);
1915
- const resetForm = strapiAdmin.useForm("PublishAction", ({ resetForm: resetForm2 }) => resetForm2);
1916
- return {
1917
- /**
1918
- * Disabled when:
1919
- * - the form is submitting
1920
- * - the document is not modified & we're not cloning (you can save a clone entity straight away)
1921
- * - the active tab is the published tab
1922
- */
1923
- disabled: isSubmitting || !modified && !isCloning || activeTab === "published",
1924
- label: formatMessage({
1925
- id: "content-manager.containers.Edit.save",
1926
- defaultMessage: "Save"
1927
- }),
1928
- onClick: async () => {
1929
- setSubmitting(true);
1930
- try {
1931
- if (activeTab !== "draft") {
1932
- const { errors } = await validate();
1933
- if (errors) {
1934
- toggleNotification({
1935
- type: "danger",
1936
- message: formatMessage({
1937
- id: "content-manager.validation.error",
1938
- defaultMessage: "There are validation errors in your document. Please fix them before saving."
1939
- })
1940
- });
1941
- return;
1942
- }
1943
- }
1944
- if (isCloning) {
1945
- const res = await clone(
1946
- {
1947
- model,
1948
- documentId: cloneMatch.params.origin,
1949
- params
1950
- },
1951
- document
1952
- );
1953
- if ("data" in res) {
1954
- navigate(
1955
- {
1956
- pathname: `../${res.data.documentId}`,
1957
- search: rawQuery
1958
- },
1959
- { relative: "path" }
1960
- );
1961
- } else if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
1962
- setErrors(formatValidationErrors(res.error));
1963
- }
1964
- } else if (documentId || collectionType === SINGLE_TYPES) {
1965
- const res = await update(
1966
- {
1967
- collectionType,
1968
- model,
1969
- documentId,
1970
- params
1971
- },
1972
- document
1973
- );
1974
- if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
1975
- setErrors(formatValidationErrors(res.error));
1976
- } else {
1977
- resetForm();
1978
- }
1979
- } else {
1980
- const res = await create(
1981
- {
1982
- model,
1983
- params
1984
- },
1985
- document
1986
- );
1987
- if ("data" in res && collectionType !== SINGLE_TYPES) {
1988
- navigate(
1989
- {
1990
- pathname: `../${res.data.documentId}`,
1991
- search: rawQuery
1992
- },
1993
- { replace: true, relative: "path" }
1994
- );
1995
- } else if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
1996
- setErrors(formatValidationErrors(res.error));
1997
- }
1998
- }
1999
- } finally {
2000
- setSubmitting(false);
1812
+ const handleClick = (action2) => async (e) => {
1813
+ const { onClick = () => false, dialog, id } = action2;
1814
+ const muteDialog = await onClick(e);
1815
+ if (dialog && !muteDialog) {
1816
+ switch (dialog.type) {
1817
+ case "notification":
1818
+ toggleNotification({
1819
+ title: dialog.title,
1820
+ message: dialog.content,
1821
+ type: dialog.status,
1822
+ timeout: dialog.timeout,
1823
+ onClose: dialog.onClose
1824
+ });
1825
+ break;
1826
+ case "dialog":
1827
+ case "modal":
1828
+ e.preventDefault();
1829
+ setDialogId(id);
2001
1830
  }
2002
1831
  }
2003
1832
  };
1833
+ const handleClose = () => {
1834
+ setDialogId(null);
1835
+ };
1836
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1837
+ /* @__PURE__ */ jsxRuntime.jsx(
1838
+ designSystem.Button,
1839
+ {
1840
+ flex: "auto",
1841
+ startIcon: action.icon,
1842
+ disabled: action.disabled,
1843
+ onClick: handleClick(action),
1844
+ justifyContent: "center",
1845
+ variant: action.variant || "default",
1846
+ paddingTop: "7px",
1847
+ paddingBottom: "7px",
1848
+ children: action.label
1849
+ }
1850
+ ),
1851
+ action.dialog?.type === "dialog" ? /* @__PURE__ */ jsxRuntime.jsx(
1852
+ DocumentActionConfirmDialog,
1853
+ {
1854
+ ...action.dialog,
1855
+ variant: action.dialog?.variant ?? action.variant,
1856
+ isOpen: dialogId === action.id,
1857
+ onClose: handleClose
1858
+ }
1859
+ ) : null,
1860
+ action.dialog?.type === "modal" ? /* @__PURE__ */ jsxRuntime.jsx(
1861
+ DocumentActionModal,
1862
+ {
1863
+ ...action.dialog,
1864
+ onModalClose: handleClose,
1865
+ isOpen: dialogId === action.id
1866
+ }
1867
+ ) : null
1868
+ ] });
2004
1869
  };
2005
- UpdateAction.type = "update";
2006
- const UNPUBLISH_DRAFT_OPTIONS = {
2007
- KEEP: "keep",
2008
- DISCARD: "discard"
2009
- };
2010
- const UnpublishAction$1 = ({
2011
- activeTab,
2012
- documentId,
2013
- model,
2014
- collectionType,
2015
- document
1870
+ const DocumentActionsMenu = ({
1871
+ actions: actions2,
1872
+ children,
1873
+ label,
1874
+ variant = "tertiary"
2016
1875
  }) => {
1876
+ const [isOpen, setIsOpen] = React__namespace.useState(false);
1877
+ const [dialogId, setDialogId] = React__namespace.useState(null);
2017
1878
  const { formatMessage } = reactIntl.useIntl();
2018
- const { schema } = useDoc();
2019
- const canPublish = useDocumentRBAC("UnpublishAction", ({ canPublish: canPublish2 }) => canPublish2);
2020
- const { unpublish } = useDocumentActions();
2021
- const [{ query }] = strapiAdmin.useQueryParams();
2022
- const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
2023
1879
  const { toggleNotification } = strapiAdmin.useNotification();
2024
- const [shouldKeepDraft, setShouldKeepDraft] = React__namespace.useState(true);
2025
- const isDocumentModified = document?.status === "modified";
2026
- const handleChange = (value) => {
2027
- setShouldKeepDraft(value === UNPUBLISH_DRAFT_OPTIONS.KEEP);
2028
- };
2029
- if (!schema?.options?.draftAndPublish) {
2030
- return null;
2031
- }
2032
- return {
2033
- disabled: !canPublish || activeTab === "published" || document?.status !== "published" && document?.status !== "modified",
2034
- label: formatMessage({
2035
- id: "app.utils.unpublish",
2036
- defaultMessage: "Unpublish"
2037
- }),
2038
- icon: /* @__PURE__ */ jsxRuntime.jsx(StyledCrossCircle, {}),
2039
- onClick: async () => {
2040
- if (!documentId && collectionType !== SINGLE_TYPES || isDocumentModified) {
2041
- if (!documentId) {
2042
- console.error(
2043
- "You're trying to unpublish a document without an id, this is likely a bug with Strapi. Please open an issue."
2044
- );
1880
+ const isDisabled = actions2.every((action) => action.disabled) || actions2.length === 0;
1881
+ const handleClick = (action) => async (e) => {
1882
+ const { onClick = () => false, dialog, id } = action;
1883
+ const muteDialog = await onClick(e);
1884
+ if (dialog && !muteDialog) {
1885
+ switch (dialog.type) {
1886
+ case "notification":
2045
1887
  toggleNotification({
2046
- message: formatMessage({
2047
- id: "content-manager.actions.unpublish.error",
2048
- defaultMessage: "An error occurred while trying to unpublish the document."
2049
- }),
2050
- type: "danger"
1888
+ title: dialog.title,
1889
+ message: dialog.content,
1890
+ type: dialog.status,
1891
+ timeout: dialog.timeout,
1892
+ onClose: dialog.onClose
2051
1893
  });
2052
- }
2053
- return;
1894
+ break;
1895
+ case "dialog":
1896
+ case "modal":
1897
+ setDialogId(id);
2054
1898
  }
2055
- await unpublish({
2056
- collectionType,
2057
- model,
2058
- documentId,
2059
- params
2060
- });
2061
- },
2062
- dialog: isDocumentModified ? {
2063
- type: "dialog",
2064
- title: formatMessage({
2065
- id: "app.components.ConfirmDialog.title",
2066
- defaultMessage: "Confirmation"
2067
- }),
2068
- content: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { alignItems: "flex-start", direction: "column", gap: 6, children: [
2069
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { width: "100%", direction: "column", gap: 2, children: [
2070
- /* @__PURE__ */ jsxRuntime.jsx(Icons.WarningCircle, { width: "24px", height: "24px", fill: "danger600" }),
2071
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "p", variant: "omega", textAlign: "center", children: formatMessage({
2072
- id: "content-manager.actions.unpublish.dialog.body",
2073
- defaultMessage: "Are you sure?"
1899
+ }
1900
+ };
1901
+ const handleClose = () => {
1902
+ setDialogId(null);
1903
+ setIsOpen(false);
1904
+ };
1905
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Menu.Root, { open: isOpen, onOpenChange: setIsOpen, children: [
1906
+ /* @__PURE__ */ jsxRuntime.jsxs(
1907
+ designSystem.Menu.Trigger,
1908
+ {
1909
+ disabled: isDisabled,
1910
+ size: "S",
1911
+ endIcon: null,
1912
+ paddingTop: "4px",
1913
+ paddingLeft: "7px",
1914
+ paddingRight: "7px",
1915
+ variant,
1916
+ children: [
1917
+ /* @__PURE__ */ jsxRuntime.jsx(Icons.More, { "aria-hidden": true, focusable: false }),
1918
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { tag: "span", children: label || formatMessage({
1919
+ id: "content-manager.containers.edit.panels.default.more-actions",
1920
+ defaultMessage: "More document actions"
2074
1921
  }) })
2075
- ] }),
2076
- /* @__PURE__ */ jsxRuntime.jsxs(
2077
- designSystem.Radio.Group,
2078
- {
2079
- defaultValue: UNPUBLISH_DRAFT_OPTIONS.KEEP,
2080
- name: "discard-options",
2081
- "aria-label": formatMessage({
2082
- id: "content-manager.actions.unpublish.dialog.radio-label",
2083
- defaultMessage: "Choose an option to unpublish the document."
2084
- }),
2085
- onValueChange: handleChange,
2086
- children: [
2087
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { checked: shouldKeepDraft, value: UNPUBLISH_DRAFT_OPTIONS.KEEP, children: formatMessage({
2088
- id: "content-manager.actions.unpublish.dialog.option.keep-draft",
2089
- defaultMessage: "Keep draft"
2090
- }) }),
2091
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { checked: !shouldKeepDraft, value: UNPUBLISH_DRAFT_OPTIONS.DISCARD, children: formatMessage({
2092
- id: "content-manager.actions.unpublish.dialog.option.replace-draft",
2093
- defaultMessage: "Replace draft"
2094
- }) })
2095
- ]
2096
- }
2097
- )
2098
- ] }),
2099
- onConfirm: async () => {
2100
- if (!documentId && collectionType !== SINGLE_TYPES) {
2101
- console.error(
2102
- "You're trying to unpublish a document without an id, this is likely a bug with Strapi. Please open an issue."
2103
- );
2104
- toggleNotification({
2105
- message: formatMessage({
2106
- id: "content-manager.actions.unpublish.error",
2107
- defaultMessage: "An error occurred while trying to unpublish the document."
2108
- }),
2109
- type: "danger"
2110
- });
2111
- }
2112
- await unpublish(
1922
+ ]
1923
+ }
1924
+ ),
1925
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Menu.Content, { maxHeight: void 0, popoverPlacement: "bottom-end", children: [
1926
+ actions2.map((action) => {
1927
+ return /* @__PURE__ */ jsxRuntime.jsx(
1928
+ designSystem.Menu.Item,
2113
1929
  {
2114
- collectionType,
2115
- model,
2116
- documentId,
2117
- params
1930
+ disabled: action.disabled,
1931
+ onSelect: handleClick(action),
1932
+ display: "block",
1933
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", gap: 4, children: [
1934
+ /* @__PURE__ */ jsxRuntime.jsxs(
1935
+ designSystem.Flex,
1936
+ {
1937
+ color: !action.disabled ? convertActionVariantToColor(action.variant) : "inherit",
1938
+ gap: 2,
1939
+ tag: "span",
1940
+ children: [
1941
+ /* @__PURE__ */ jsxRuntime.jsx(
1942
+ designSystem.Flex,
1943
+ {
1944
+ tag: "span",
1945
+ color: !action.disabled ? convertActionVariantToIconColor(action.variant) : "inherit",
1946
+ children: action.icon
1947
+ }
1948
+ ),
1949
+ action.label
1950
+ ]
1951
+ }
1952
+ ),
1953
+ action.id.startsWith("HistoryAction") && /* @__PURE__ */ jsxRuntime.jsx(
1954
+ designSystem.Flex,
1955
+ {
1956
+ alignItems: "center",
1957
+ background: "alternative100",
1958
+ borderStyle: "solid",
1959
+ borderColor: "alternative200",
1960
+ borderWidth: "1px",
1961
+ height: 5,
1962
+ paddingLeft: 2,
1963
+ paddingRight: 2,
1964
+ hasRadius: true,
1965
+ color: "alternative600",
1966
+ children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", fontWeight: "bold", lineHeight: 1, children: formatMessage({ id: "global.new", defaultMessage: "New" }) })
1967
+ }
1968
+ )
1969
+ ] })
2118
1970
  },
2119
- !shouldKeepDraft
1971
+ action.id
2120
1972
  );
2121
- }
2122
- } : void 0,
2123
- variant: "danger",
2124
- position: ["panel", "table-row"]
1973
+ }),
1974
+ children
1975
+ ] }),
1976
+ actions2.map((action) => {
1977
+ return /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Fragment, { children: [
1978
+ action.dialog?.type === "dialog" ? /* @__PURE__ */ jsxRuntime.jsx(
1979
+ DocumentActionConfirmDialog,
1980
+ {
1981
+ ...action.dialog,
1982
+ variant: action.variant,
1983
+ isOpen: dialogId === action.id,
1984
+ onClose: handleClose
1985
+ }
1986
+ ) : null,
1987
+ action.dialog?.type === "modal" ? /* @__PURE__ */ jsxRuntime.jsx(
1988
+ DocumentActionModal,
1989
+ {
1990
+ ...action.dialog,
1991
+ onModalClose: handleClose,
1992
+ isOpen: dialogId === action.id
1993
+ }
1994
+ ) : null
1995
+ ] }, action.id);
1996
+ })
1997
+ ] });
1998
+ };
1999
+ const convertActionVariantToColor = (variant = "secondary") => {
2000
+ switch (variant) {
2001
+ case "danger":
2002
+ return "danger600";
2003
+ case "secondary":
2004
+ return void 0;
2005
+ case "success":
2006
+ return "success600";
2007
+ default:
2008
+ return "primary600";
2009
+ }
2010
+ };
2011
+ const convertActionVariantToIconColor = (variant = "secondary") => {
2012
+ switch (variant) {
2013
+ case "danger":
2014
+ return "danger600";
2015
+ case "secondary":
2016
+ return "neutral500";
2017
+ case "success":
2018
+ return "success600";
2019
+ default:
2020
+ return "primary600";
2021
+ }
2022
+ };
2023
+ const DocumentActionConfirmDialog = ({
2024
+ onClose,
2025
+ onCancel,
2026
+ onConfirm,
2027
+ title,
2028
+ content,
2029
+ isOpen,
2030
+ variant = "secondary"
2031
+ }) => {
2032
+ const { formatMessage } = reactIntl.useIntl();
2033
+ const handleClose = async () => {
2034
+ if (onCancel) {
2035
+ await onCancel();
2036
+ }
2037
+ onClose();
2038
+ };
2039
+ const handleConfirm = async () => {
2040
+ if (onConfirm) {
2041
+ await onConfirm();
2042
+ }
2043
+ onClose();
2125
2044
  };
2045
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Root, { open: isOpen, onOpenChange: handleClose, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Dialog.Content, { children: [
2046
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Header, { children: title }),
2047
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Body, { children: content }),
2048
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Dialog.Footer, { children: [
2049
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Cancel, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", fullWidth: true, children: formatMessage({
2050
+ id: "app.components.Button.cancel",
2051
+ defaultMessage: "Cancel"
2052
+ }) }) }),
2053
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { onClick: handleConfirm, variant, fullWidth: true, children: formatMessage({
2054
+ id: "app.components.Button.confirm",
2055
+ defaultMessage: "Confirm"
2056
+ }) })
2057
+ ] })
2058
+ ] }) });
2126
2059
  };
2127
- UnpublishAction$1.type = "unpublish";
2128
- const DiscardAction = ({
2060
+ const DocumentActionModal = ({
2061
+ isOpen,
2062
+ title,
2063
+ onClose,
2064
+ footer: Footer,
2065
+ content: Content,
2066
+ onModalClose
2067
+ }) => {
2068
+ const handleClose = () => {
2069
+ if (onClose) {
2070
+ onClose();
2071
+ }
2072
+ onModalClose();
2073
+ };
2074
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Root, { open: isOpen, onOpenChange: handleClose, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { children: [
2075
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: title }) }),
2076
+ typeof Content === "function" ? /* @__PURE__ */ jsxRuntime.jsx(Content, { onClose: handleClose }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: Content }),
2077
+ typeof Footer === "function" ? /* @__PURE__ */ jsxRuntime.jsx(Footer, { onClose: handleClose }) : Footer
2078
+ ] }) });
2079
+ };
2080
+ const PublishAction$1 = ({
2129
2081
  activeTab,
2130
2082
  documentId,
2131
2083
  model,
2132
2084
  collectionType,
2085
+ meta,
2133
2086
  document
2134
2087
  }) => {
2135
- const { formatMessage } = reactIntl.useIntl();
2136
2088
  const { schema } = useDoc();
2137
- const canUpdate = useDocumentRBAC("DiscardAction", ({ canUpdate: canUpdate2 }) => canUpdate2);
2138
- const { discard } = useDocumentActions();
2139
- const [{ query }] = strapiAdmin.useQueryParams();
2140
- const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
2141
- if (!schema?.options?.draftAndPublish) {
2142
- return null;
2143
- }
2144
- return {
2145
- disabled: !canUpdate || activeTab === "published" || document?.status !== "modified",
2146
- label: formatMessage({
2147
- id: "content-manager.actions.discard.label",
2148
- defaultMessage: "Discard changes"
2149
- }),
2150
- icon: /* @__PURE__ */ jsxRuntime.jsx(StyledCrossCircle, {}),
2151
- position: ["panel", "table-row"],
2152
- variant: "danger",
2153
- dialog: {
2154
- type: "dialog",
2155
- title: formatMessage({
2156
- id: "app.components.ConfirmDialog.title",
2157
- defaultMessage: "Confirmation"
2158
- }),
2159
- content: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, children: [
2160
- /* @__PURE__ */ jsxRuntime.jsx(Icons.WarningCircle, { width: "24px", height: "24px", fill: "danger600" }),
2161
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "p", variant: "omega", textAlign: "center", children: formatMessage({
2162
- id: "content-manager.actions.discard.dialog.body",
2163
- defaultMessage: "Are you sure?"
2164
- }) })
2165
- ] }),
2166
- onConfirm: async () => {
2167
- await discard({
2168
- collectionType,
2169
- model,
2170
- documentId,
2171
- params
2172
- });
2173
- }
2174
- }
2175
- };
2176
- };
2177
- DiscardAction.type = "discard";
2178
- const StyledCrossCircle = styledComponents.styled(Icons.CrossCircle)`
2179
- path {
2180
- fill: currentColor;
2181
- }
2182
- `;
2183
- const DEFAULT_ACTIONS = [PublishAction$1, UpdateAction, UnpublishAction$1, DiscardAction];
2184
- const intervals = ["years", "months", "days", "hours", "minutes", "seconds"];
2185
- const RelativeTime = React__namespace.forwardRef(
2186
- ({ timestamp, customIntervals = [], ...restProps }, forwardedRef) => {
2187
- const { formatRelativeTime, formatDate, formatTime } = reactIntl.useIntl();
2188
- const interval = dateFns.intervalToDuration({
2189
- start: timestamp,
2190
- end: Date.now()
2191
- // see https://github.com/date-fns/date-fns/issues/2891 – No idea why it's all partial it returns it every time.
2192
- });
2193
- const unit = intervals.find((intervalUnit) => {
2194
- return interval[intervalUnit] > 0 && Object.keys(interval).includes(intervalUnit);
2195
- });
2196
- const relativeTime = dateFns.isPast(timestamp) ? -interval[unit] : interval[unit];
2197
- const customInterval = customIntervals.find(
2198
- (custom) => interval[custom.unit] < custom.threshold
2199
- );
2200
- const displayText = customInterval ? customInterval.text : formatRelativeTime(relativeTime, unit, { numeric: "auto" });
2201
- return /* @__PURE__ */ jsxRuntime.jsx(
2202
- "time",
2203
- {
2204
- ref: forwardedRef,
2205
- dateTime: timestamp.toISOString(),
2206
- role: "time",
2207
- title: `${formatDate(timestamp)} ${formatTime(timestamp)}`,
2208
- ...restProps,
2209
- children: displayText
2210
- }
2211
- );
2212
- }
2213
- );
2214
- const getDisplayName = ({
2215
- firstname,
2216
- lastname,
2217
- username,
2218
- email
2219
- } = {}) => {
2220
- if (username) {
2221
- return username;
2222
- }
2223
- if (firstname) {
2224
- return `${firstname} ${lastname ?? ""}`.trim();
2225
- }
2226
- return email ?? "";
2227
- };
2228
- const capitalise = (str) => str.charAt(0).toUpperCase() + str.slice(1);
2229
- const DocumentStatus = ({ status = "draft", ...restProps }) => {
2230
- const statusVariant = status === "draft" ? "primary" : status === "published" ? "success" : "alternative";
2231
- return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Status, { ...restProps, showBullet: false, size: "S", variant: statusVariant, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "span", variant: "omega", fontWeight: "bold", children: capitalise(status) }) });
2232
- };
2233
- const Header = ({ isCreating, status, title: documentTitle = "Untitled" }) => {
2234
- const { formatMessage } = reactIntl.useIntl();
2089
+ const navigate = reactRouterDom.useNavigate();
2090
+ const { toggleNotification } = strapiAdmin.useNotification();
2091
+ const { _unstableFormatValidationErrors: formatValidationErrors } = strapiAdmin.useAPIErrorHandler();
2092
+ const isListView = reactRouterDom.useMatch(LIST_PATH) !== null;
2235
2093
  const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
2236
- const title = isCreating ? formatMessage({
2237
- id: "content-manager.containers.edit.title.new",
2238
- defaultMessage: "Create an entry"
2239
- }) : documentTitle;
2240
- return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", paddingTop: 6, paddingBottom: 4, gap: 2, children: [
2241
- /* @__PURE__ */ jsxRuntime.jsx(strapiAdmin.BackButton, {}),
2242
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { width: "100%", justifyContent: "space-between", gap: "80px", alignItems: "flex-start", children: [
2243
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "alpha", tag: "h1", children: title }),
2244
- /* @__PURE__ */ jsxRuntime.jsx(HeaderToolbar, {})
2245
- ] }),
2246
- status ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { marginTop: 1, children: /* @__PURE__ */ jsxRuntime.jsx(DocumentStatus, { status: isCloning ? "draft" : status }) }) : null
2247
- ] });
2248
- };
2249
- const HeaderToolbar = () => {
2250
2094
  const { formatMessage } = reactIntl.useIntl();
2251
- const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
2095
+ const canPublish = useDocumentRBAC("PublishAction", ({ canPublish: canPublish2 }) => canPublish2);
2096
+ const { publish } = useDocumentActions();
2252
2097
  const [
2253
- {
2254
- query: { status = "draft" }
2098
+ countDraftRelations,
2099
+ { isLoading: isLoadingDraftRelations, isError: isErrorDraftRelations }
2100
+ ] = useLazyGetDraftRelationCountQuery();
2101
+ const [localCountOfDraftRelations, setLocalCountOfDraftRelations] = React__namespace.useState(0);
2102
+ const [serverCountOfDraftRelations, setServerCountOfDraftRelations] = React__namespace.useState(0);
2103
+ const [{ query, rawQuery }] = strapiAdmin.useQueryParams();
2104
+ const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
2105
+ const modified = strapiAdmin.useForm("PublishAction", ({ modified: modified2 }) => modified2);
2106
+ const setSubmitting = strapiAdmin.useForm("PublishAction", ({ setSubmitting: setSubmitting2 }) => setSubmitting2);
2107
+ const isSubmitting = strapiAdmin.useForm("PublishAction", ({ isSubmitting: isSubmitting2 }) => isSubmitting2);
2108
+ const validate = strapiAdmin.useForm("PublishAction", (state) => state.validate);
2109
+ const setErrors = strapiAdmin.useForm("PublishAction", (state) => state.setErrors);
2110
+ const formValues = strapiAdmin.useForm("PublishAction", ({ values }) => values);
2111
+ React__namespace.useEffect(() => {
2112
+ if (isErrorDraftRelations) {
2113
+ toggleNotification({
2114
+ type: "danger",
2115
+ message: formatMessage({
2116
+ id: getTranslation("error.records.fetch-draft-relatons"),
2117
+ defaultMessage: "An error occurred while fetching draft relations on this document."
2118
+ })
2119
+ });
2255
2120
  }
2256
- ] = strapiAdmin.useQueryParams();
2257
- const { model, id, document, meta, collectionType } = useDoc();
2258
- const plugins = strapiAdmin.useStrapiApp("HeaderToolbar", (state) => state.plugins);
2259
- return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
2260
- /* @__PURE__ */ jsxRuntime.jsx(
2261
- strapiAdmin.DescriptionComponentRenderer,
2262
- {
2263
- props: {
2264
- activeTab: status,
2265
- model,
2266
- documentId: id,
2267
- document: isCloning ? void 0 : document,
2268
- meta: isCloning ? void 0 : meta,
2269
- collectionType
2270
- },
2271
- descriptions: plugins["content-manager"].apis.getHeaderActions(),
2272
- children: (actions2) => {
2273
- if (actions2.length > 0) {
2274
- return /* @__PURE__ */ jsxRuntime.jsx(HeaderActions, { actions: actions2 });
2275
- } else {
2276
- return null;
2277
- }
2121
+ }, [isErrorDraftRelations, toggleNotification, formatMessage]);
2122
+ React__namespace.useEffect(() => {
2123
+ const localDraftRelations = /* @__PURE__ */ new Set();
2124
+ const extractDraftRelations = (data) => {
2125
+ const relations = data.connect || [];
2126
+ relations.forEach((relation) => {
2127
+ if (relation.status === "draft") {
2128
+ localDraftRelations.add(relation.id);
2278
2129
  }
2279
- }
2280
- ),
2281
- /* @__PURE__ */ jsxRuntime.jsx(
2282
- strapiAdmin.DescriptionComponentRenderer,
2283
- {
2284
- props: {
2285
- activeTab: status,
2286
- model,
2287
- documentId: id,
2288
- document: isCloning ? void 0 : document,
2289
- meta: isCloning ? void 0 : meta,
2290
- collectionType
2291
- },
2292
- descriptions: plugins["content-manager"].apis.getDocumentActions(),
2293
- children: (actions2) => {
2294
- const headerActions = actions2.filter((action) => {
2295
- const positions = Array.isArray(action.position) ? action.position : [action.position];
2296
- return positions.includes("header");
2297
- });
2298
- return /* @__PURE__ */ jsxRuntime.jsx(
2299
- DocumentActionsMenu,
2300
- {
2301
- actions: headerActions,
2302
- label: formatMessage({
2303
- id: "content-manager.containers.edit.header.more-actions",
2304
- defaultMessage: "More actions"
2305
- }),
2306
- children: /* @__PURE__ */ jsxRuntime.jsx(Information, { activeTab: status })
2307
- }
2308
- );
2130
+ });
2131
+ };
2132
+ const traverseAndExtract = (data) => {
2133
+ Object.entries(data).forEach(([key, value]) => {
2134
+ if (key === "connect" && Array.isArray(value)) {
2135
+ extractDraftRelations({ connect: value });
2136
+ } else if (typeof value === "object" && value !== null) {
2137
+ traverseAndExtract(value);
2309
2138
  }
2139
+ });
2140
+ };
2141
+ if (!documentId || modified) {
2142
+ traverseAndExtract(formValues);
2143
+ setLocalCountOfDraftRelations(localDraftRelations.size);
2144
+ }
2145
+ }, [documentId, modified, formValues, setLocalCountOfDraftRelations]);
2146
+ React__namespace.useEffect(() => {
2147
+ if (!document || !document.documentId || isListView) {
2148
+ return;
2149
+ }
2150
+ const fetchDraftRelationsCount = async () => {
2151
+ const { data, error } = await countDraftRelations({
2152
+ collectionType,
2153
+ model,
2154
+ documentId,
2155
+ params
2156
+ });
2157
+ if (error) {
2158
+ throw error;
2310
2159
  }
2311
- )
2312
- ] });
2313
- };
2314
- const Information = ({ activeTab }) => {
2315
- const { formatMessage } = reactIntl.useIntl();
2316
- const { document, meta } = useDoc();
2317
- if (!document || !document.id) {
2160
+ if (data) {
2161
+ setServerCountOfDraftRelations(data.data);
2162
+ }
2163
+ };
2164
+ fetchDraftRelationsCount();
2165
+ }, [isListView, document, documentId, countDraftRelations, collectionType, model, params]);
2166
+ const isDocumentPublished = (document?.[PUBLISHED_AT_ATTRIBUTE_NAME] || meta?.availableStatus.some((doc) => doc[PUBLISHED_AT_ATTRIBUTE_NAME] !== null)) && document?.status !== "modified";
2167
+ if (!schema?.options?.draftAndPublish) {
2318
2168
  return null;
2319
2169
  }
2320
- const createAndUpdateDocument = activeTab === "draft" ? document : meta?.availableStatus.find((status) => status.publishedAt === null);
2321
- const publishDocument = activeTab === "published" ? document : meta?.availableStatus.find((status) => status.publishedAt !== null);
2322
- const creator = createAndUpdateDocument?.[CREATED_BY_ATTRIBUTE_NAME] ? getDisplayName(createAndUpdateDocument[CREATED_BY_ATTRIBUTE_NAME]) : null;
2323
- const updator = createAndUpdateDocument?.[UPDATED_BY_ATTRIBUTE_NAME] ? getDisplayName(createAndUpdateDocument[UPDATED_BY_ATTRIBUTE_NAME]) : null;
2324
- const information = [
2325
- {
2326
- isDisplayed: !!publishDocument?.[PUBLISHED_AT_ATTRIBUTE_NAME],
2327
- label: formatMessage({
2328
- id: "content-manager.containers.edit.information.last-published.label",
2329
- defaultMessage: "Last published"
2330
- }),
2331
- value: formatMessage(
2170
+ const performPublish = async () => {
2171
+ setSubmitting(true);
2172
+ try {
2173
+ const { errors } = await validate(true, {
2174
+ status: "published"
2175
+ });
2176
+ if (errors) {
2177
+ toggleNotification({
2178
+ type: "danger",
2179
+ message: formatMessage({
2180
+ id: "content-manager.validation.error",
2181
+ defaultMessage: "There are validation errors in your document. Please fix them before saving."
2182
+ })
2183
+ });
2184
+ return;
2185
+ }
2186
+ const res = await publish(
2332
2187
  {
2333
- id: "content-manager.containers.edit.information.last-published.value",
2334
- defaultMessage: `Published {time}{isAnonymous, select, true {} other { by {author}}}`
2188
+ collectionType,
2189
+ model,
2190
+ documentId,
2191
+ params
2335
2192
  },
2336
- {
2337
- time: /* @__PURE__ */ jsxRuntime.jsx(RelativeTime, { timestamp: new Date(publishDocument?.[PUBLISHED_AT_ATTRIBUTE_NAME]) }),
2338
- isAnonymous: !publishDocument?.[PUBLISHED_BY_ATTRIBUTE_NAME],
2339
- author: publishDocument?.[PUBLISHED_BY_ATTRIBUTE_NAME] ? getDisplayName(publishDocument?.[PUBLISHED_BY_ATTRIBUTE_NAME]) : null
2340
- }
2341
- )
2193
+ formValues
2194
+ );
2195
+ if ("data" in res && collectionType !== SINGLE_TYPES) {
2196
+ navigate({
2197
+ pathname: `../${collectionType}/${model}/${res.data.documentId}`,
2198
+ search: rawQuery
2199
+ });
2200
+ } else if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
2201
+ setErrors(formatValidationErrors(res.error));
2202
+ }
2203
+ } finally {
2204
+ setSubmitting(false);
2205
+ }
2206
+ };
2207
+ const totalDraftRelations = localCountOfDraftRelations + serverCountOfDraftRelations;
2208
+ const enableDraftRelationsCount = false;
2209
+ const hasDraftRelations = enableDraftRelationsCount;
2210
+ return {
2211
+ /**
2212
+ * Disabled when:
2213
+ * - currently if you're cloning a document we don't support publish & clone at the same time.
2214
+ * - the form is submitting
2215
+ * - the active tab is the published tab
2216
+ * - the document is already published & not modified
2217
+ * - the document is being created & not modified
2218
+ * - the user doesn't have the permission to publish
2219
+ */
2220
+ disabled: isCloning || isSubmitting || isLoadingDraftRelations || activeTab === "published" || !modified && isDocumentPublished || !modified && !document?.documentId || !canPublish,
2221
+ label: formatMessage({
2222
+ id: "app.utils.publish",
2223
+ defaultMessage: "Publish"
2224
+ }),
2225
+ onClick: async () => {
2226
+ await performPublish();
2342
2227
  },
2343
- {
2344
- isDisplayed: !!createAndUpdateDocument?.[UPDATED_AT_ATTRIBUTE_NAME],
2345
- label: formatMessage({
2346
- id: "content-manager.containers.edit.information.last-draft.label",
2347
- defaultMessage: "Last draft"
2228
+ dialog: hasDraftRelations ? {
2229
+ type: "dialog",
2230
+ variant: "danger",
2231
+ footer: null,
2232
+ title: formatMessage({
2233
+ id: getTranslation(`popUpwarning.warning.bulk-has-draft-relations.title`),
2234
+ defaultMessage: "Confirmation"
2348
2235
  }),
2349
- value: formatMessage(
2236
+ content: formatMessage(
2350
2237
  {
2351
- id: "content-manager.containers.edit.information.last-draft.value",
2352
- defaultMessage: `Modified {time}{isAnonymous, select, true {} other { by {author}}}`
2238
+ id: getTranslation(`popUpwarning.warning.bulk-has-draft-relations.message`),
2239
+ defaultMessage: "This entry is related to {count, plural, one {# draft entry} other {# draft entries}}. Publishing it could leave broken links in your app."
2353
2240
  },
2354
2241
  {
2355
- time: /* @__PURE__ */ jsxRuntime.jsx(
2356
- RelativeTime,
2357
- {
2358
- timestamp: new Date(createAndUpdateDocument?.[UPDATED_AT_ATTRIBUTE_NAME])
2359
- }
2360
- ),
2361
- isAnonymous: !updator,
2362
- author: updator
2242
+ count: totalDraftRelations
2363
2243
  }
2364
- )
2365
- },
2366
- {
2367
- isDisplayed: !!createAndUpdateDocument?.[CREATED_AT_ATTRIBUTE_NAME],
2368
- label: formatMessage({
2369
- id: "content-manager.containers.edit.information.document.label",
2370
- defaultMessage: "Document"
2371
- }),
2372
- value: formatMessage(
2373
- {
2374
- id: "content-manager.containers.edit.information.document.value",
2375
- defaultMessage: `Created {time}{isAnonymous, select, true {} other { by {author}}}`
2376
- },
2377
- {
2378
- time: /* @__PURE__ */ jsxRuntime.jsx(
2379
- RelativeTime,
2380
- {
2381
- timestamp: new Date(createAndUpdateDocument?.[CREATED_AT_ATTRIBUTE_NAME])
2382
- }
2383
- ),
2384
- isAnonymous: !creator,
2385
- author: creator
2244
+ ),
2245
+ onConfirm: async () => {
2246
+ await performPublish();
2247
+ }
2248
+ } : void 0
2249
+ };
2250
+ };
2251
+ PublishAction$1.type = "publish";
2252
+ const UpdateAction = ({
2253
+ activeTab,
2254
+ documentId,
2255
+ model,
2256
+ collectionType
2257
+ }) => {
2258
+ const navigate = reactRouterDom.useNavigate();
2259
+ const { toggleNotification } = strapiAdmin.useNotification();
2260
+ const { _unstableFormatValidationErrors: formatValidationErrors } = strapiAdmin.useAPIErrorHandler();
2261
+ const cloneMatch = reactRouterDom.useMatch(CLONE_PATH);
2262
+ const isCloning = cloneMatch !== null;
2263
+ const { formatMessage } = reactIntl.useIntl();
2264
+ const { create, update, clone } = useDocumentActions();
2265
+ const [{ query, rawQuery }] = strapiAdmin.useQueryParams();
2266
+ const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
2267
+ const isSubmitting = strapiAdmin.useForm("UpdateAction", ({ isSubmitting: isSubmitting2 }) => isSubmitting2);
2268
+ const modified = strapiAdmin.useForm("UpdateAction", ({ modified: modified2 }) => modified2);
2269
+ const setSubmitting = strapiAdmin.useForm("UpdateAction", ({ setSubmitting: setSubmitting2 }) => setSubmitting2);
2270
+ const document = strapiAdmin.useForm("UpdateAction", ({ values }) => values);
2271
+ const validate = strapiAdmin.useForm("UpdateAction", (state) => state.validate);
2272
+ const setErrors = strapiAdmin.useForm("UpdateAction", (state) => state.setErrors);
2273
+ const resetForm = strapiAdmin.useForm("PublishAction", ({ resetForm: resetForm2 }) => resetForm2);
2274
+ return {
2275
+ /**
2276
+ * Disabled when:
2277
+ * - the form is submitting
2278
+ * - the document is not modified & we're not cloning (you can save a clone entity straight away)
2279
+ * - the active tab is the published tab
2280
+ */
2281
+ disabled: isSubmitting || !modified && !isCloning || activeTab === "published",
2282
+ label: formatMessage({
2283
+ id: "content-manager.containers.Edit.save",
2284
+ defaultMessage: "Save"
2285
+ }),
2286
+ onClick: async () => {
2287
+ setSubmitting(true);
2288
+ try {
2289
+ const { errors } = await validate(true, {
2290
+ status: "draft"
2291
+ });
2292
+ if (errors) {
2293
+ toggleNotification({
2294
+ type: "danger",
2295
+ message: formatMessage({
2296
+ id: "content-manager.validation.error",
2297
+ defaultMessage: "There are validation errors in your document. Please fix them before saving."
2298
+ })
2299
+ });
2300
+ return;
2386
2301
  }
2387
- )
2388
- }
2389
- ].filter((info) => info.isDisplayed);
2390
- return /* @__PURE__ */ jsxRuntime.jsx(
2391
- designSystem.Flex,
2392
- {
2393
- borderWidth: "1px 0 0 0",
2394
- borderStyle: "solid",
2395
- borderColor: "neutral150",
2396
- direction: "column",
2397
- marginTop: 2,
2398
- tag: "dl",
2399
- padding: 5,
2400
- gap: 3,
2401
- alignItems: "flex-start",
2402
- marginLeft: "-0.4rem",
2403
- marginRight: "-0.4rem",
2404
- width: "calc(100% + 8px)",
2405
- children: information.map((info) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, direction: "column", alignItems: "flex-start", children: [
2406
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "dt", variant: "pi", fontWeight: "bold", children: info.label }),
2407
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "dd", variant: "pi", textColor: "neutral600", children: info.value })
2408
- ] }, info.label))
2302
+ if (isCloning) {
2303
+ const res = await clone(
2304
+ {
2305
+ model,
2306
+ documentId: cloneMatch.params.origin,
2307
+ params
2308
+ },
2309
+ document
2310
+ );
2311
+ if ("data" in res) {
2312
+ navigate(
2313
+ {
2314
+ pathname: `../${res.data.documentId}`,
2315
+ search: rawQuery
2316
+ },
2317
+ { relative: "path" }
2318
+ );
2319
+ } else if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
2320
+ setErrors(formatValidationErrors(res.error));
2321
+ }
2322
+ } else if (documentId || collectionType === SINGLE_TYPES) {
2323
+ const res = await update(
2324
+ {
2325
+ collectionType,
2326
+ model,
2327
+ documentId,
2328
+ params
2329
+ },
2330
+ document
2331
+ );
2332
+ if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
2333
+ setErrors(formatValidationErrors(res.error));
2334
+ } else {
2335
+ resetForm();
2336
+ }
2337
+ } else {
2338
+ const res = await create(
2339
+ {
2340
+ model,
2341
+ params
2342
+ },
2343
+ document
2344
+ );
2345
+ if ("data" in res && collectionType !== SINGLE_TYPES) {
2346
+ navigate(
2347
+ {
2348
+ pathname: `../${res.data.documentId}`,
2349
+ search: rawQuery
2350
+ },
2351
+ { replace: true, relative: "path" }
2352
+ );
2353
+ } else if ("error" in res && isBaseQueryError(res.error) && res.error.name === "ValidationError") {
2354
+ setErrors(formatValidationErrors(res.error));
2355
+ }
2356
+ }
2357
+ } finally {
2358
+ setSubmitting(false);
2359
+ }
2409
2360
  }
2410
- );
2361
+ };
2411
2362
  };
2412
- const HeaderActions = ({ actions: actions2 }) => {
2413
- return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { children: actions2.map((action) => {
2414
- if ("options" in action) {
2415
- return /* @__PURE__ */ jsxRuntime.jsx(
2416
- designSystem.SingleSelect,
2417
- {
2418
- size: "S",
2419
- disabled: action.disabled,
2420
- "aria-label": action.label,
2421
- onChange: action.onSelect,
2422
- value: action.value,
2423
- children: action.options.map(({ label, ...option }) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { ...option, children: label }, option.value))
2424
- },
2425
- action.id
2426
- );
2427
- } else {
2428
- return null;
2429
- }
2430
- }) });
2363
+ UpdateAction.type = "update";
2364
+ const UNPUBLISH_DRAFT_OPTIONS = {
2365
+ KEEP: "keep",
2366
+ DISCARD: "discard"
2431
2367
  };
2432
- const ConfigureTheViewAction = ({ collectionType, model }) => {
2433
- const navigate = reactRouterDom.useNavigate();
2368
+ const UnpublishAction$1 = ({
2369
+ activeTab,
2370
+ documentId,
2371
+ model,
2372
+ collectionType,
2373
+ document
2374
+ }) => {
2434
2375
  const { formatMessage } = reactIntl.useIntl();
2435
- return {
2436
- label: formatMessage({
2437
- id: "app.links.configure-view",
2438
- defaultMessage: "Configure the view"
2439
- }),
2440
- icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.ListPlus, {}),
2441
- onClick: () => {
2442
- navigate(`../${collectionType}/${model}/configurations/edit`);
2443
- },
2444
- position: "header"
2376
+ const { schema } = useDoc();
2377
+ const canPublish = useDocumentRBAC("UnpublishAction", ({ canPublish: canPublish2 }) => canPublish2);
2378
+ const { unpublish } = useDocumentActions();
2379
+ const [{ query }] = strapiAdmin.useQueryParams();
2380
+ const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
2381
+ const { toggleNotification } = strapiAdmin.useNotification();
2382
+ const [shouldKeepDraft, setShouldKeepDraft] = React__namespace.useState(true);
2383
+ const isDocumentModified = document?.status === "modified";
2384
+ const handleChange = (value) => {
2385
+ setShouldKeepDraft(value === UNPUBLISH_DRAFT_OPTIONS.KEEP);
2445
2386
  };
2446
- };
2447
- ConfigureTheViewAction.type = "configure-the-view";
2448
- const EditTheModelAction = ({ model }) => {
2449
- const navigate = reactRouterDom.useNavigate();
2450
- const { formatMessage } = reactIntl.useIntl();
2387
+ if (!schema?.options?.draftAndPublish) {
2388
+ return null;
2389
+ }
2451
2390
  return {
2391
+ disabled: !canPublish || activeTab === "published" || document?.status !== "published" && document?.status !== "modified",
2452
2392
  label: formatMessage({
2453
- id: "content-manager.link-to-ctb",
2454
- defaultMessage: "Edit the model"
2393
+ id: "app.utils.unpublish",
2394
+ defaultMessage: "Unpublish"
2455
2395
  }),
2456
- icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Pencil, {}),
2457
- onClick: () => {
2458
- navigate(`/plugins/content-type-builder/content-types/${model}`);
2396
+ icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Cross, {}),
2397
+ onClick: async () => {
2398
+ if (!documentId && collectionType !== SINGLE_TYPES || isDocumentModified) {
2399
+ if (!documentId) {
2400
+ console.error(
2401
+ "You're trying to unpublish a document without an id, this is likely a bug with Strapi. Please open an issue."
2402
+ );
2403
+ toggleNotification({
2404
+ message: formatMessage({
2405
+ id: "content-manager.actions.unpublish.error",
2406
+ defaultMessage: "An error occurred while trying to unpublish the document."
2407
+ }),
2408
+ type: "danger"
2409
+ });
2410
+ }
2411
+ return;
2412
+ }
2413
+ await unpublish({
2414
+ collectionType,
2415
+ model,
2416
+ documentId,
2417
+ params
2418
+ });
2459
2419
  },
2460
- position: "header"
2420
+ dialog: isDocumentModified ? {
2421
+ type: "dialog",
2422
+ title: formatMessage({
2423
+ id: "app.components.ConfirmDialog.title",
2424
+ defaultMessage: "Confirmation"
2425
+ }),
2426
+ content: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { alignItems: "flex-start", direction: "column", gap: 6, children: [
2427
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { width: "100%", direction: "column", gap: 2, children: [
2428
+ /* @__PURE__ */ jsxRuntime.jsx(Icons.WarningCircle, { width: "24px", height: "24px", fill: "danger600" }),
2429
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "p", variant: "omega", textAlign: "center", children: formatMessage({
2430
+ id: "content-manager.actions.unpublish.dialog.body",
2431
+ defaultMessage: "Are you sure?"
2432
+ }) })
2433
+ ] }),
2434
+ /* @__PURE__ */ jsxRuntime.jsxs(
2435
+ designSystem.Radio.Group,
2436
+ {
2437
+ defaultValue: UNPUBLISH_DRAFT_OPTIONS.KEEP,
2438
+ name: "discard-options",
2439
+ "aria-label": formatMessage({
2440
+ id: "content-manager.actions.unpublish.dialog.radio-label",
2441
+ defaultMessage: "Choose an option to unpublish the document."
2442
+ }),
2443
+ onValueChange: handleChange,
2444
+ children: [
2445
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { checked: shouldKeepDraft, value: UNPUBLISH_DRAFT_OPTIONS.KEEP, children: formatMessage({
2446
+ id: "content-manager.actions.unpublish.dialog.option.keep-draft",
2447
+ defaultMessage: "Keep draft"
2448
+ }) }),
2449
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { checked: !shouldKeepDraft, value: UNPUBLISH_DRAFT_OPTIONS.DISCARD, children: formatMessage({
2450
+ id: "content-manager.actions.unpublish.dialog.option.replace-draft",
2451
+ defaultMessage: "Replace draft"
2452
+ }) })
2453
+ ]
2454
+ }
2455
+ )
2456
+ ] }),
2457
+ onConfirm: async () => {
2458
+ if (!documentId && collectionType !== SINGLE_TYPES) {
2459
+ console.error(
2460
+ "You're trying to unpublish a document without an id, this is likely a bug with Strapi. Please open an issue."
2461
+ );
2462
+ toggleNotification({
2463
+ message: formatMessage({
2464
+ id: "content-manager.actions.unpublish.error",
2465
+ defaultMessage: "An error occurred while trying to unpublish the document."
2466
+ }),
2467
+ type: "danger"
2468
+ });
2469
+ }
2470
+ await unpublish(
2471
+ {
2472
+ collectionType,
2473
+ model,
2474
+ documentId,
2475
+ params
2476
+ },
2477
+ !shouldKeepDraft
2478
+ );
2479
+ }
2480
+ } : void 0,
2481
+ variant: "danger",
2482
+ position: ["panel", "table-row"]
2461
2483
  };
2462
2484
  };
2463
- EditTheModelAction.type = "edit-the-model";
2464
- const DeleteAction$1 = ({ documentId, model, collectionType, document }) => {
2465
- const navigate = reactRouterDom.useNavigate();
2485
+ UnpublishAction$1.type = "unpublish";
2486
+ const DiscardAction = ({
2487
+ activeTab,
2488
+ documentId,
2489
+ model,
2490
+ collectionType,
2491
+ document
2492
+ }) => {
2466
2493
  const { formatMessage } = reactIntl.useIntl();
2467
- const listViewPathMatch = reactRouterDom.useMatch(LIST_PATH);
2468
- const canDelete = useDocumentRBAC("DeleteAction", (state) => state.canDelete);
2469
- const { delete: deleteAction } = useDocumentActions();
2470
- const { toggleNotification } = strapiAdmin.useNotification();
2471
- const setSubmitting = strapiAdmin.useForm("DeleteAction", (state) => state.setSubmitting);
2494
+ const { schema } = useDoc();
2495
+ const canUpdate = useDocumentRBAC("DiscardAction", ({ canUpdate: canUpdate2 }) => canUpdate2);
2496
+ const { discard } = useDocumentActions();
2497
+ const [{ query }] = strapiAdmin.useQueryParams();
2498
+ const params = React__namespace.useMemo(() => buildValidParams(query), [query]);
2499
+ if (!schema?.options?.draftAndPublish) {
2500
+ return null;
2501
+ }
2472
2502
  return {
2473
- disabled: !canDelete || !document,
2503
+ disabled: !canUpdate || activeTab === "published" || document?.status !== "modified",
2474
2504
  label: formatMessage({
2475
- id: "content-manager.actions.delete.label",
2476
- defaultMessage: "Delete document"
2505
+ id: "content-manager.actions.discard.label",
2506
+ defaultMessage: "Discard changes"
2477
2507
  }),
2478
- icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Trash, {}),
2508
+ icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Cross, {}),
2509
+ position: ["panel", "table-row"],
2510
+ variant: "danger",
2479
2511
  dialog: {
2480
2512
  type: "dialog",
2481
2513
  title: formatMessage({
@@ -2485,92 +2517,90 @@ const DeleteAction$1 = ({ documentId, model, collectionType, document }) => {
2485
2517
  content: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, children: [
2486
2518
  /* @__PURE__ */ jsxRuntime.jsx(Icons.WarningCircle, { width: "24px", height: "24px", fill: "danger600" }),
2487
2519
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "p", variant: "omega", textAlign: "center", children: formatMessage({
2488
- id: "content-manager.actions.delete.dialog.body",
2520
+ id: "content-manager.actions.discard.dialog.body",
2489
2521
  defaultMessage: "Are you sure?"
2490
2522
  }) })
2491
2523
  ] }),
2492
2524
  onConfirm: async () => {
2493
- if (!listViewPathMatch) {
2494
- setSubmitting(true);
2495
- }
2496
- try {
2497
- if (!documentId && collectionType !== SINGLE_TYPES) {
2498
- console.error(
2499
- "You're trying to delete a document without an id, this is likely a bug with Strapi. Please open an issue."
2500
- );
2501
- toggleNotification({
2502
- message: formatMessage({
2503
- id: "content-manager.actions.delete.error",
2504
- defaultMessage: "An error occurred while trying to delete the document."
2505
- }),
2506
- type: "danger"
2507
- });
2508
- return;
2509
- }
2510
- const res = await deleteAction({
2511
- documentId,
2512
- model,
2513
- collectionType,
2514
- params: {
2515
- locale: "*"
2516
- }
2517
- });
2518
- if (!("error" in res)) {
2519
- navigate({ pathname: `../${collectionType}/${model}` }, { replace: true });
2520
- }
2521
- } finally {
2522
- if (!listViewPathMatch) {
2523
- setSubmitting(false);
2524
- }
2525
- }
2525
+ await discard({
2526
+ collectionType,
2527
+ model,
2528
+ documentId,
2529
+ params
2530
+ });
2531
+ }
2532
+ }
2533
+ };
2534
+ };
2535
+ DiscardAction.type = "discard";
2536
+ const DEFAULT_ACTIONS = [PublishAction$1, UpdateAction, UnpublishAction$1, DiscardAction];
2537
+ const intervals = ["years", "months", "days", "hours", "minutes", "seconds"];
2538
+ const RelativeTime = React__namespace.forwardRef(
2539
+ ({ timestamp, customIntervals = [], ...restProps }, forwardedRef) => {
2540
+ const { formatRelativeTime, formatDate, formatTime } = reactIntl.useIntl();
2541
+ const interval = dateFns.intervalToDuration({
2542
+ start: timestamp,
2543
+ end: Date.now()
2544
+ // see https://github.com/date-fns/date-fns/issues/2891 – No idea why it's all partial it returns it every time.
2545
+ });
2546
+ const unit = intervals.find((intervalUnit) => {
2547
+ return interval[intervalUnit] > 0 && Object.keys(interval).includes(intervalUnit);
2548
+ });
2549
+ const relativeTime = dateFns.isPast(timestamp) ? -interval[unit] : interval[unit];
2550
+ const customInterval = customIntervals.find(
2551
+ (custom) => interval[custom.unit] < custom.threshold
2552
+ );
2553
+ const displayText = customInterval ? customInterval.text : formatRelativeTime(relativeTime, unit, { numeric: "auto" });
2554
+ return /* @__PURE__ */ jsxRuntime.jsx(
2555
+ "time",
2556
+ {
2557
+ ref: forwardedRef,
2558
+ dateTime: timestamp.toISOString(),
2559
+ role: "time",
2560
+ title: `${formatDate(timestamp)} ${formatTime(timestamp)}`,
2561
+ ...restProps,
2562
+ children: displayText
2526
2563
  }
2527
- },
2528
- variant: "danger",
2529
- position: ["header", "table-row"]
2530
- };
2564
+ );
2565
+ }
2566
+ );
2567
+ const getDisplayName = ({
2568
+ firstname,
2569
+ lastname,
2570
+ username,
2571
+ email
2572
+ } = {}) => {
2573
+ if (username) {
2574
+ return username;
2575
+ }
2576
+ if (firstname) {
2577
+ return `${firstname} ${lastname ?? ""}`.trim();
2578
+ }
2579
+ return email ?? "";
2531
2580
  };
2532
- DeleteAction$1.type = "delete";
2533
- const DEFAULT_HEADER_ACTIONS = [EditTheModelAction, ConfigureTheViewAction, DeleteAction$1];
2534
- const Panels = () => {
2535
- const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
2536
- const [
2537
- {
2538
- query: { status }
2539
- }
2540
- ] = strapiAdmin.useQueryParams({
2541
- status: "draft"
2542
- });
2543
- const { model, id, document, meta, collectionType } = useDoc();
2544
- const plugins = strapiAdmin.useStrapiApp("Panels", (state) => state.plugins);
2545
- const props = {
2546
- activeTab: status,
2547
- model,
2548
- documentId: id,
2549
- document: isCloning ? void 0 : document,
2550
- meta: isCloning ? void 0 : meta,
2551
- collectionType
2552
- };
2553
- return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, children: /* @__PURE__ */ jsxRuntime.jsx(
2554
- strapiAdmin.DescriptionComponentRenderer,
2555
- {
2556
- props,
2557
- descriptions: plugins["content-manager"].apis.getEditViewSidePanels(),
2558
- children: (panels) => panels.map(({ content, id: id2, ...description }) => /* @__PURE__ */ jsxRuntime.jsx(Panel, { ...description, children: content }, id2))
2559
- }
2560
- ) });
2581
+ const capitalise = (str) => str.charAt(0).toUpperCase() + str.slice(1);
2582
+ const DocumentStatus = ({ status = "draft", ...restProps }) => {
2583
+ const statusVariant = status === "draft" ? "secondary" : status === "published" ? "success" : "alternative";
2584
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Status, { ...restProps, showBullet: false, size: "S", variant: statusVariant, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "span", variant: "omega", fontWeight: "bold", children: capitalise(status) }) });
2561
2585
  };
2562
- const ActionsPanel = () => {
2586
+ const Header = ({ isCreating, status, title: documentTitle = "Untitled" }) => {
2563
2587
  const { formatMessage } = reactIntl.useIntl();
2564
- return {
2565
- title: formatMessage({
2566
- id: "content-manager.containers.edit.panels.default.title",
2567
- defaultMessage: "Document"
2568
- }),
2569
- content: /* @__PURE__ */ jsxRuntime.jsx(ActionsPanelContent, {})
2570
- };
2588
+ const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
2589
+ const title = isCreating ? formatMessage({
2590
+ id: "content-manager.containers.edit.title.new",
2591
+ defaultMessage: "Create an entry"
2592
+ }) : documentTitle;
2593
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", paddingTop: 6, paddingBottom: 4, gap: 2, children: [
2594
+ /* @__PURE__ */ jsxRuntime.jsx(strapiAdmin.BackButton, {}),
2595
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { width: "100%", justifyContent: "space-between", gap: "80px", alignItems: "flex-start", children: [
2596
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "alpha", tag: "h1", children: title }),
2597
+ /* @__PURE__ */ jsxRuntime.jsx(HeaderToolbar, {})
2598
+ ] }),
2599
+ status ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { marginTop: 1, children: /* @__PURE__ */ jsxRuntime.jsx(DocumentStatus, { status: isCloning ? "draft" : status }) }) : null
2600
+ ] });
2571
2601
  };
2572
- ActionsPanel.type = "actions";
2573
- const ActionsPanelContent = () => {
2602
+ const HeaderToolbar = () => {
2603
+ const { formatMessage } = reactIntl.useIntl();
2574
2604
  const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
2575
2605
  const [
2576
2606
  {
@@ -2578,355 +2608,432 @@ const ActionsPanelContent = () => {
2578
2608
  }
2579
2609
  ] = strapiAdmin.useQueryParams();
2580
2610
  const { model, id, document, meta, collectionType } = useDoc();
2581
- const plugins = strapiAdmin.useStrapiApp("ActionsPanel", (state) => state.plugins);
2582
- const props = {
2583
- activeTab: status,
2584
- model,
2585
- documentId: id,
2586
- document: isCloning ? void 0 : document,
2587
- meta: isCloning ? void 0 : meta,
2588
- collectionType
2589
- };
2590
- return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, width: "100%", children: [
2611
+ const plugins = strapiAdmin.useStrapiApp("HeaderToolbar", (state) => state.plugins);
2612
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
2591
2613
  /* @__PURE__ */ jsxRuntime.jsx(
2592
2614
  strapiAdmin.DescriptionComponentRenderer,
2593
2615
  {
2594
- props,
2595
- descriptions: plugins["content-manager"].apis.getDocumentActions(),
2596
- children: (actions2) => /* @__PURE__ */ jsxRuntime.jsx(DocumentActions, { actions: actions2 })
2616
+ props: {
2617
+ activeTab: status,
2618
+ model,
2619
+ documentId: id,
2620
+ document: isCloning ? void 0 : document,
2621
+ meta: isCloning ? void 0 : meta,
2622
+ collectionType
2623
+ },
2624
+ descriptions: plugins["content-manager"].apis.getHeaderActions(),
2625
+ children: (actions2) => {
2626
+ if (actions2.length > 0) {
2627
+ return /* @__PURE__ */ jsxRuntime.jsx(HeaderActions, { actions: actions2 });
2628
+ } else {
2629
+ return null;
2630
+ }
2631
+ }
2597
2632
  }
2598
2633
  ),
2599
- /* @__PURE__ */ jsxRuntime.jsx(InjectionZone, { area: "editView.right-links", slug: model })
2634
+ /* @__PURE__ */ jsxRuntime.jsx(
2635
+ strapiAdmin.DescriptionComponentRenderer,
2636
+ {
2637
+ props: {
2638
+ activeTab: status,
2639
+ model,
2640
+ documentId: id,
2641
+ document: isCloning ? void 0 : document,
2642
+ meta: isCloning ? void 0 : meta,
2643
+ collectionType
2644
+ },
2645
+ descriptions: plugins["content-manager"].apis.getDocumentActions(),
2646
+ children: (actions2) => {
2647
+ const headerActions = actions2.filter((action) => {
2648
+ const positions = Array.isArray(action.position) ? action.position : [action.position];
2649
+ return positions.includes("header");
2650
+ });
2651
+ return /* @__PURE__ */ jsxRuntime.jsx(
2652
+ DocumentActionsMenu,
2653
+ {
2654
+ actions: headerActions,
2655
+ label: formatMessage({
2656
+ id: "content-manager.containers.edit.header.more-actions",
2657
+ defaultMessage: "More actions"
2658
+ }),
2659
+ children: /* @__PURE__ */ jsxRuntime.jsx(Information, { activeTab: status })
2660
+ }
2661
+ );
2662
+ }
2663
+ }
2664
+ )
2600
2665
  ] });
2601
2666
  };
2602
- const Panel = React__namespace.forwardRef(({ children, title }, ref) => {
2603
- return /* @__PURE__ */ jsxRuntime.jsxs(
2604
- designSystem.Flex,
2667
+ const Information = ({ activeTab }) => {
2668
+ const { formatMessage } = reactIntl.useIntl();
2669
+ const { document, meta } = useDoc();
2670
+ if (!document || !document.id) {
2671
+ return null;
2672
+ }
2673
+ const createAndUpdateDocument = activeTab === "draft" ? document : meta?.availableStatus.find((status) => status.publishedAt === null);
2674
+ const publishDocument = activeTab === "published" ? document : meta?.availableStatus.find((status) => status.publishedAt !== null);
2675
+ const creator = createAndUpdateDocument?.[CREATED_BY_ATTRIBUTE_NAME] ? getDisplayName(createAndUpdateDocument[CREATED_BY_ATTRIBUTE_NAME]) : null;
2676
+ const updator = createAndUpdateDocument?.[UPDATED_BY_ATTRIBUTE_NAME] ? getDisplayName(createAndUpdateDocument[UPDATED_BY_ATTRIBUTE_NAME]) : null;
2677
+ const information = [
2605
2678
  {
2606
- ref,
2607
- tag: "aside",
2608
- "aria-labelledby": "additional-information",
2609
- background: "neutral0",
2610
- borderColor: "neutral150",
2611
- hasRadius: true,
2612
- paddingBottom: 4,
2613
- paddingLeft: 4,
2614
- paddingRight: 4,
2615
- paddingTop: 4,
2616
- shadow: "tableShadow",
2617
- gap: 3,
2618
- direction: "column",
2619
- justifyContent: "stretch",
2620
- alignItems: "flex-start",
2621
- children: [
2622
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "h2", variant: "sigma", textTransform: "uppercase", children: title }),
2623
- children
2624
- ]
2625
- }
2626
- );
2627
- });
2628
- const HOOKS = {
2629
- /**
2630
- * Hook that allows to mutate the displayed headers of the list view table
2631
- * @constant
2632
- * @type {string}
2633
- */
2634
- INJECT_COLUMN_IN_TABLE: "Admin/CM/pages/ListView/inject-column-in-table",
2635
- /**
2636
- * Hook that allows to mutate the CM's collection types links pre-set filters
2637
- * @constant
2638
- * @type {string}
2639
- */
2640
- MUTATE_COLLECTION_TYPES_LINKS: "Admin/CM/pages/App/mutate-collection-types-links",
2641
- /**
2642
- * Hook that allows to mutate the CM's edit view layout
2643
- * @constant
2644
- * @type {string}
2645
- */
2646
- MUTATE_EDIT_VIEW_LAYOUT: "Admin/CM/pages/EditView/mutate-edit-view-layout",
2647
- /**
2648
- * Hook that allows to mutate the CM's single types links pre-set filters
2649
- * @constant
2650
- * @type {string}
2651
- */
2652
- MUTATE_SINGLE_TYPES_LINKS: "Admin/CM/pages/App/mutate-single-types-links"
2653
- };
2654
- const contentTypesApi = contentManagerApi.injectEndpoints({
2655
- endpoints: (builder) => ({
2656
- getContentTypeConfiguration: builder.query({
2657
- query: (uid) => ({
2658
- url: `/content-manager/content-types/${uid}/configuration`,
2659
- method: "GET"
2679
+ isDisplayed: !!publishDocument?.[PUBLISHED_AT_ATTRIBUTE_NAME],
2680
+ label: formatMessage({
2681
+ id: "content-manager.containers.edit.information.last-published.label",
2682
+ defaultMessage: "Published"
2660
2683
  }),
2661
- transformResponse: (response) => response.data,
2662
- providesTags: (_result, _error, uid) => [
2663
- { type: "ContentTypesConfiguration", id: uid },
2664
- { type: "ContentTypeSettings", id: "LIST" }
2665
- ]
2666
- }),
2667
- getAllContentTypeSettings: builder.query({
2668
- query: () => "/content-manager/content-types-settings",
2669
- transformResponse: (response) => response.data,
2670
- providesTags: [{ type: "ContentTypeSettings", id: "LIST" }]
2671
- }),
2672
- updateContentTypeConfiguration: builder.mutation({
2673
- query: ({ uid, ...body }) => ({
2674
- url: `/content-manager/content-types/${uid}/configuration`,
2675
- method: "PUT",
2676
- data: body
2684
+ value: formatMessage(
2685
+ {
2686
+ id: "content-manager.containers.edit.information.last-published.value",
2687
+ defaultMessage: `{time}{isAnonymous, select, true {} other { by {author}}}`
2688
+ },
2689
+ {
2690
+ time: /* @__PURE__ */ jsxRuntime.jsx(RelativeTime, { timestamp: new Date(publishDocument?.[PUBLISHED_AT_ATTRIBUTE_NAME]) }),
2691
+ isAnonymous: !publishDocument?.[PUBLISHED_BY_ATTRIBUTE_NAME],
2692
+ author: publishDocument?.[PUBLISHED_BY_ATTRIBUTE_NAME] ? getDisplayName(publishDocument?.[PUBLISHED_BY_ATTRIBUTE_NAME]) : null
2693
+ }
2694
+ )
2695
+ },
2696
+ {
2697
+ isDisplayed: !!createAndUpdateDocument?.[UPDATED_AT_ATTRIBUTE_NAME],
2698
+ label: formatMessage({
2699
+ id: "content-manager.containers.edit.information.last-draft.label",
2700
+ defaultMessage: "Updated"
2701
+ }),
2702
+ value: formatMessage(
2703
+ {
2704
+ id: "content-manager.containers.edit.information.last-draft.value",
2705
+ defaultMessage: `{time}{isAnonymous, select, true {} other { by {author}}}`
2706
+ },
2707
+ {
2708
+ time: /* @__PURE__ */ jsxRuntime.jsx(
2709
+ RelativeTime,
2710
+ {
2711
+ timestamp: new Date(createAndUpdateDocument?.[UPDATED_AT_ATTRIBUTE_NAME])
2712
+ }
2713
+ ),
2714
+ isAnonymous: !updator,
2715
+ author: updator
2716
+ }
2717
+ )
2718
+ },
2719
+ {
2720
+ isDisplayed: !!createAndUpdateDocument?.[CREATED_AT_ATTRIBUTE_NAME],
2721
+ label: formatMessage({
2722
+ id: "content-manager.containers.edit.information.document.label",
2723
+ defaultMessage: "Created"
2677
2724
  }),
2678
- transformResponse: (response) => response.data,
2679
- invalidatesTags: (_result, _error, { uid }) => [
2680
- { type: "ContentTypesConfiguration", id: uid },
2681
- { type: "ContentTypeSettings", id: "LIST" },
2682
- // Is this necessary?
2683
- { type: "InitialData" }
2684
- ]
2685
- })
2686
- })
2687
- });
2688
- const {
2689
- useGetContentTypeConfigurationQuery,
2690
- useGetAllContentTypeSettingsQuery,
2691
- useUpdateContentTypeConfigurationMutation
2692
- } = contentTypesApi;
2693
- const checkIfAttributeIsDisplayable = (attribute) => {
2694
- const { type } = attribute;
2695
- if (type === "relation") {
2696
- return !attribute.relation.toLowerCase().includes("morph");
2697
- }
2698
- return !["json", "dynamiczone", "richtext", "password", "blocks"].includes(type) && !!type;
2699
- };
2700
- const getMainField = (attribute, mainFieldName, { schemas, components }) => {
2701
- if (!mainFieldName) {
2702
- return void 0;
2703
- }
2704
- const mainFieldType = attribute.type === "component" ? components[attribute.component].attributes[mainFieldName].type : (
2705
- // @ts-expect-error – `targetModel` does exist on the attribute for a relation.
2706
- schemas.find((schema) => schema.uid === attribute.targetModel)?.attributes[mainFieldName].type
2725
+ value: formatMessage(
2726
+ {
2727
+ id: "content-manager.containers.edit.information.document.value",
2728
+ defaultMessage: `{time}{isAnonymous, select, true {} other { by {author}}}`
2729
+ },
2730
+ {
2731
+ time: /* @__PURE__ */ jsxRuntime.jsx(
2732
+ RelativeTime,
2733
+ {
2734
+ timestamp: new Date(createAndUpdateDocument?.[CREATED_AT_ATTRIBUTE_NAME])
2735
+ }
2736
+ ),
2737
+ isAnonymous: !creator,
2738
+ author: creator
2739
+ }
2740
+ )
2741
+ }
2742
+ ].filter((info) => info.isDisplayed);
2743
+ return /* @__PURE__ */ jsxRuntime.jsx(
2744
+ designSystem.Flex,
2745
+ {
2746
+ borderWidth: "1px 0 0 0",
2747
+ borderStyle: "solid",
2748
+ borderColor: "neutral150",
2749
+ direction: "column",
2750
+ marginTop: 2,
2751
+ tag: "dl",
2752
+ padding: 5,
2753
+ gap: 3,
2754
+ alignItems: "flex-start",
2755
+ marginLeft: "-0.4rem",
2756
+ marginRight: "-0.4rem",
2757
+ width: "calc(100% + 8px)",
2758
+ children: information.map((info) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, direction: "column", alignItems: "flex-start", children: [
2759
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "dt", variant: "pi", fontWeight: "bold", children: info.label }),
2760
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "dd", variant: "pi", textColor: "neutral600", children: info.value })
2761
+ ] }, info.label))
2762
+ }
2707
2763
  );
2708
- return {
2709
- name: mainFieldName,
2710
- type: mainFieldType ?? "string"
2711
- };
2712
- };
2713
- const DEFAULT_SETTINGS = {
2714
- bulkable: false,
2715
- filterable: false,
2716
- searchable: false,
2717
- pagination: false,
2718
- defaultSortBy: "",
2719
- defaultSortOrder: "asc",
2720
- mainField: "id",
2721
- pageSize: 10
2722
2764
  };
2723
- const useDocumentLayout = (model) => {
2724
- const { schema, components } = useDocument({ model, collectionType: "" }, { skip: true });
2725
- const [{ query }] = strapiAdmin.useQueryParams();
2726
- const runHookWaterfall = strapiAdmin.useStrapiApp("useDocumentLayout", (state) => state.runHookWaterfall);
2727
- const { toggleNotification } = strapiAdmin.useNotification();
2728
- const { _unstableFormatAPIError: formatAPIError } = strapiAdmin.useAPIErrorHandler();
2729
- const { isLoading: isLoadingSchemas, schemas } = useContentTypeSchema();
2730
- const {
2731
- data,
2732
- isLoading: isLoadingConfigs,
2733
- error,
2734
- isFetching: isFetchingConfigs
2735
- } = useGetContentTypeConfigurationQuery(model);
2736
- const isLoading = isLoadingSchemas || isFetchingConfigs || isLoadingConfigs;
2737
- React__namespace.useEffect(() => {
2738
- if (error) {
2739
- toggleNotification({
2740
- type: "danger",
2741
- message: formatAPIError(error)
2742
- });
2765
+ const HeaderActions = ({ actions: actions2 }) => {
2766
+ const [dialogId, setDialogId] = React__namespace.useState(null);
2767
+ const handleClick = (action) => async (e) => {
2768
+ if (!("options" in action)) {
2769
+ const { onClick = () => false, dialog, id } = action;
2770
+ const muteDialog = await onClick(e);
2771
+ if (dialog && !muteDialog) {
2772
+ e.preventDefault();
2773
+ setDialogId(id);
2774
+ }
2743
2775
  }
2744
- }, [error, formatAPIError, toggleNotification]);
2745
- const editLayout = React__namespace.useMemo(
2746
- () => data && !isLoading ? formatEditLayout(data, { schemas, schema, components }) : {
2747
- layout: [],
2748
- components: {},
2749
- metadatas: {},
2750
- options: {},
2751
- settings: DEFAULT_SETTINGS
2752
- },
2753
- [data, isLoading, schemas, schema, components]
2754
- );
2755
- const listLayout = React__namespace.useMemo(() => {
2756
- return data && !isLoading ? formatListLayout(data, { schemas, schema, components }) : {
2757
- layout: [],
2758
- metadatas: {},
2759
- options: {},
2760
- settings: DEFAULT_SETTINGS
2761
- };
2762
- }, [data, isLoading, schemas, schema, components]);
2763
- const { layout: edit } = React__namespace.useMemo(
2764
- () => runHookWaterfall(HOOKS.MUTATE_EDIT_VIEW_LAYOUT, {
2765
- layout: editLayout,
2766
- query
2767
- }),
2768
- [editLayout, query, runHookWaterfall]
2769
- );
2770
- return {
2771
- error,
2772
- isLoading,
2773
- edit,
2774
- list: listLayout
2775
2776
  };
2776
- };
2777
- const useDocLayout = () => {
2778
- const { model } = useDoc();
2779
- return useDocumentLayout(model);
2780
- };
2781
- const formatEditLayout = (data, {
2782
- schemas,
2783
- schema,
2784
- components
2785
- }) => {
2786
- let currentPanelIndex = 0;
2787
- const panelledEditAttributes = convertEditLayoutToFieldLayouts(
2788
- data.contentType.layouts.edit,
2789
- schema?.attributes,
2790
- data.contentType.metadatas,
2791
- { configurations: data.components, schemas: components },
2792
- schemas
2793
- ).reduce((panels, row) => {
2794
- if (row.some((field) => field.type === "dynamiczone")) {
2795
- panels.push([row]);
2796
- currentPanelIndex += 2;
2777
+ const handleClose = () => {
2778
+ setDialogId(null);
2779
+ };
2780
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { gap: 1, children: actions2.map((action) => {
2781
+ if (action.options) {
2782
+ return /* @__PURE__ */ jsxRuntime.jsx(
2783
+ designSystem.SingleSelect,
2784
+ {
2785
+ size: "S",
2786
+ onChange: action.onSelect,
2787
+ "aria-label": action.label,
2788
+ ...action,
2789
+ children: action.options.map(({ label, ...option }) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { ...option, children: label }, option.value))
2790
+ },
2791
+ action.id
2792
+ );
2797
2793
  } else {
2798
- if (!panels[currentPanelIndex]) {
2799
- panels.push([]);
2794
+ if (action.type === "icon") {
2795
+ return /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Fragment, { children: [
2796
+ /* @__PURE__ */ jsxRuntime.jsx(
2797
+ designSystem.IconButton,
2798
+ {
2799
+ disabled: action.disabled,
2800
+ label: action.label,
2801
+ size: "S",
2802
+ onClick: handleClick(action),
2803
+ children: action.icon
2804
+ }
2805
+ ),
2806
+ action.dialog ? /* @__PURE__ */ jsxRuntime.jsx(
2807
+ HeaderActionDialog,
2808
+ {
2809
+ ...action.dialog,
2810
+ isOpen: dialogId === action.id,
2811
+ onClose: handleClose
2812
+ }
2813
+ ) : null
2814
+ ] }, action.id);
2800
2815
  }
2801
- panels[currentPanelIndex].push(row);
2802
2816
  }
2803
- return panels;
2804
- }, []);
2805
- const componentEditAttributes = Object.entries(data.components).reduce(
2806
- (acc, [uid, configuration]) => {
2807
- acc[uid] = {
2808
- layout: convertEditLayoutToFieldLayouts(
2809
- configuration.layouts.edit,
2810
- components[uid].attributes,
2811
- configuration.metadatas
2812
- ),
2813
- settings: {
2814
- ...configuration.settings,
2815
- icon: components[uid].info.icon,
2816
- displayName: components[uid].info.displayName
2817
- }
2818
- };
2819
- return acc;
2820
- },
2821
- {}
2822
- );
2823
- const editMetadatas = Object.entries(data.contentType.metadatas).reduce(
2824
- (acc, [attribute, metadata]) => {
2825
- return {
2826
- ...acc,
2827
- [attribute]: metadata.edit
2828
- };
2817
+ }) });
2818
+ };
2819
+ const HeaderActionDialog = ({
2820
+ onClose,
2821
+ onCancel,
2822
+ title,
2823
+ content: Content,
2824
+ isOpen
2825
+ }) => {
2826
+ const handleClose = async () => {
2827
+ if (onCancel) {
2828
+ await onCancel();
2829
+ }
2830
+ onClose();
2831
+ };
2832
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Root, { open: isOpen, onOpenChange: handleClose, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Dialog.Content, { children: [
2833
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Header, { children: title }),
2834
+ typeof Content === "function" ? /* @__PURE__ */ jsxRuntime.jsx(Content, { onClose: handleClose }) : Content
2835
+ ] }) });
2836
+ };
2837
+ const ConfigureTheViewAction = ({ collectionType, model }) => {
2838
+ const navigate = reactRouterDom.useNavigate();
2839
+ const { formatMessage } = reactIntl.useIntl();
2840
+ return {
2841
+ label: formatMessage({
2842
+ id: "app.links.configure-view",
2843
+ defaultMessage: "Configure the view"
2844
+ }),
2845
+ icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.ListPlus, {}),
2846
+ onClick: () => {
2847
+ navigate(`../${collectionType}/${model}/configurations/edit`);
2829
2848
  },
2830
- {}
2831
- );
2849
+ position: "header"
2850
+ };
2851
+ };
2852
+ ConfigureTheViewAction.type = "configure-the-view";
2853
+ const EditTheModelAction = ({ model }) => {
2854
+ const navigate = reactRouterDom.useNavigate();
2855
+ const { formatMessage } = reactIntl.useIntl();
2832
2856
  return {
2833
- layout: panelledEditAttributes,
2834
- components: componentEditAttributes,
2835
- metadatas: editMetadatas,
2836
- settings: {
2837
- ...data.contentType.settings,
2838
- displayName: schema?.info.displayName
2857
+ label: formatMessage({
2858
+ id: "content-manager.link-to-ctb",
2859
+ defaultMessage: "Edit the model"
2860
+ }),
2861
+ icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Pencil, {}),
2862
+ onClick: () => {
2863
+ navigate(`/plugins/content-type-builder/content-types/${model}`);
2839
2864
  },
2840
- options: {
2841
- ...schema?.options,
2842
- ...schema?.pluginOptions,
2843
- ...data.contentType.options
2844
- }
2865
+ position: "header"
2845
2866
  };
2846
2867
  };
2847
- const convertEditLayoutToFieldLayouts = (rows, attributes = {}, metadatas, components, schemas = []) => {
2848
- return rows.map(
2849
- (row) => row.map((field) => {
2850
- const attribute = attributes[field.name];
2851
- if (!attribute) {
2852
- return null;
2868
+ EditTheModelAction.type = "edit-the-model";
2869
+ const DeleteAction$1 = ({ documentId, model, collectionType, document }) => {
2870
+ const navigate = reactRouterDom.useNavigate();
2871
+ const { formatMessage } = reactIntl.useIntl();
2872
+ const listViewPathMatch = reactRouterDom.useMatch(LIST_PATH);
2873
+ const canDelete = useDocumentRBAC("DeleteAction", (state) => state.canDelete);
2874
+ const { delete: deleteAction } = useDocumentActions();
2875
+ const { toggleNotification } = strapiAdmin.useNotification();
2876
+ const setSubmitting = strapiAdmin.useForm("DeleteAction", (state) => state.setSubmitting);
2877
+ const isLocalized = document?.locale != null;
2878
+ return {
2879
+ disabled: !canDelete || !document,
2880
+ label: formatMessage(
2881
+ {
2882
+ id: "content-manager.actions.delete.label",
2883
+ defaultMessage: "Delete entry{isLocalized, select, true { (all locales)} other {}}"
2884
+ },
2885
+ { isLocalized }
2886
+ ),
2887
+ icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Trash, {}),
2888
+ dialog: {
2889
+ type: "dialog",
2890
+ title: formatMessage({
2891
+ id: "app.components.ConfirmDialog.title",
2892
+ defaultMessage: "Confirmation"
2893
+ }),
2894
+ content: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, children: [
2895
+ /* @__PURE__ */ jsxRuntime.jsx(Icons.WarningCircle, { width: "24px", height: "24px", fill: "danger600" }),
2896
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "p", variant: "omega", textAlign: "center", children: formatMessage({
2897
+ id: "content-manager.actions.delete.dialog.body",
2898
+ defaultMessage: "Are you sure?"
2899
+ }) })
2900
+ ] }),
2901
+ onConfirm: async () => {
2902
+ if (!listViewPathMatch) {
2903
+ setSubmitting(true);
2904
+ }
2905
+ try {
2906
+ if (!documentId && collectionType !== SINGLE_TYPES) {
2907
+ console.error(
2908
+ "You're trying to delete a document without an id, this is likely a bug with Strapi. Please open an issue."
2909
+ );
2910
+ toggleNotification({
2911
+ message: formatMessage({
2912
+ id: "content-manager.actions.delete.error",
2913
+ defaultMessage: "An error occurred while trying to delete the document."
2914
+ }),
2915
+ type: "danger"
2916
+ });
2917
+ return;
2918
+ }
2919
+ const res = await deleteAction({
2920
+ documentId,
2921
+ model,
2922
+ collectionType,
2923
+ params: {
2924
+ locale: "*"
2925
+ }
2926
+ });
2927
+ if (!("error" in res)) {
2928
+ navigate({ pathname: `../${collectionType}/${model}` }, { replace: true });
2929
+ }
2930
+ } finally {
2931
+ if (!listViewPathMatch) {
2932
+ setSubmitting(false);
2933
+ }
2934
+ }
2853
2935
  }
2854
- const { edit: metadata } = metadatas[field.name];
2855
- const settings = attribute.type === "component" && components ? components.configurations[attribute.component].settings : {};
2856
- return {
2857
- attribute,
2858
- disabled: !metadata.editable,
2859
- hint: metadata.description,
2860
- label: metadata.label ?? "",
2861
- name: field.name,
2862
- // @ts-expect-error – mainField does exist on the metadata for a relation.
2863
- mainField: getMainField(attribute, metadata.mainField || settings.mainField, {
2864
- schemas,
2865
- components: components?.schemas ?? {}
2866
- }),
2867
- placeholder: metadata.placeholder ?? "",
2868
- required: attribute.required ?? false,
2869
- size: field.size,
2870
- unique: "unique" in attribute ? attribute.unique : false,
2871
- visible: metadata.visible ?? true,
2872
- type: attribute.type
2873
- };
2874
- }).filter((field) => field !== null)
2875
- );
2876
- };
2877
- const formatListLayout = (data, {
2878
- schemas,
2879
- schema,
2880
- components
2881
- }) => {
2882
- const listMetadatas = Object.entries(data.contentType.metadatas).reduce(
2883
- (acc, [attribute, metadata]) => {
2884
- return {
2885
- ...acc,
2886
- [attribute]: metadata.list
2887
- };
2888
2936
  },
2889
- {}
2890
- );
2891
- const listAttributes = convertListLayoutToFieldLayouts(
2892
- data.contentType.layouts.list,
2893
- schema?.attributes,
2894
- listMetadatas,
2895
- { configurations: data.components, schemas: components },
2896
- schemas
2897
- );
2898
- return {
2899
- layout: listAttributes,
2900
- settings: { ...data.contentType.settings, displayName: schema?.info.displayName },
2901
- metadatas: listMetadatas,
2902
- options: {
2903
- ...schema?.options,
2904
- ...schema?.pluginOptions,
2905
- ...data.contentType.options
2937
+ variant: "danger",
2938
+ position: ["header", "table-row"]
2939
+ };
2940
+ };
2941
+ DeleteAction$1.type = "delete";
2942
+ const DEFAULT_HEADER_ACTIONS = [EditTheModelAction, ConfigureTheViewAction, DeleteAction$1];
2943
+ const Panels = () => {
2944
+ const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
2945
+ const [
2946
+ {
2947
+ query: { status }
2948
+ }
2949
+ ] = strapiAdmin.useQueryParams({
2950
+ status: "draft"
2951
+ });
2952
+ const { model, id, document, meta, collectionType } = useDoc();
2953
+ const plugins = strapiAdmin.useStrapiApp("Panels", (state) => state.plugins);
2954
+ const props = {
2955
+ activeTab: status,
2956
+ model,
2957
+ documentId: id,
2958
+ document: isCloning ? void 0 : document,
2959
+ meta: isCloning ? void 0 : meta,
2960
+ collectionType
2961
+ };
2962
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, children: /* @__PURE__ */ jsxRuntime.jsx(
2963
+ strapiAdmin.DescriptionComponentRenderer,
2964
+ {
2965
+ props,
2966
+ descriptions: plugins["content-manager"].apis.getEditViewSidePanels(),
2967
+ children: (panels) => panels.map(({ content, id: id2, ...description }) => /* @__PURE__ */ jsxRuntime.jsx(Panel, { ...description, children: content }, id2))
2906
2968
  }
2969
+ ) });
2970
+ };
2971
+ const ActionsPanel = () => {
2972
+ const { formatMessage } = reactIntl.useIntl();
2973
+ return {
2974
+ title: formatMessage({
2975
+ id: "content-manager.containers.edit.panels.default.title",
2976
+ defaultMessage: "Entry"
2977
+ }),
2978
+ content: /* @__PURE__ */ jsxRuntime.jsx(ActionsPanelContent, {})
2907
2979
  };
2908
2980
  };
2909
- const convertListLayoutToFieldLayouts = (columns, attributes = {}, metadatas, components, schemas = []) => {
2910
- return columns.map((name) => {
2911
- const attribute = attributes[name];
2912
- if (!attribute) {
2913
- return null;
2981
+ ActionsPanel.type = "actions";
2982
+ const ActionsPanelContent = () => {
2983
+ const isCloning = reactRouterDom.useMatch(CLONE_PATH) !== null;
2984
+ const [
2985
+ {
2986
+ query: { status = "draft" }
2914
2987
  }
2915
- const metadata = metadatas[name];
2916
- const settings = attribute.type === "component" && components ? components.configurations[attribute.component].settings : {};
2917
- return {
2918
- attribute,
2919
- label: metadata.label ?? "",
2920
- mainField: getMainField(attribute, metadata.mainField || settings.mainField, {
2921
- schemas,
2922
- components: components?.schemas ?? {}
2923
- }),
2924
- name,
2925
- searchable: metadata.searchable ?? true,
2926
- sortable: metadata.sortable ?? true
2927
- };
2928
- }).filter((field) => field !== null);
2988
+ ] = strapiAdmin.useQueryParams();
2989
+ const { model, id, document, meta, collectionType } = useDoc();
2990
+ const plugins = strapiAdmin.useStrapiApp("ActionsPanel", (state) => state.plugins);
2991
+ const props = {
2992
+ activeTab: status,
2993
+ model,
2994
+ documentId: id,
2995
+ document: isCloning ? void 0 : document,
2996
+ meta: isCloning ? void 0 : meta,
2997
+ collectionType
2998
+ };
2999
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, width: "100%", children: [
3000
+ /* @__PURE__ */ jsxRuntime.jsx(
3001
+ strapiAdmin.DescriptionComponentRenderer,
3002
+ {
3003
+ props,
3004
+ descriptions: plugins["content-manager"].apis.getDocumentActions(),
3005
+ children: (actions2) => /* @__PURE__ */ jsxRuntime.jsx(DocumentActions, { actions: actions2 })
3006
+ }
3007
+ ),
3008
+ /* @__PURE__ */ jsxRuntime.jsx(InjectionZone, { area: "editView.right-links", slug: model })
3009
+ ] });
2929
3010
  };
3011
+ const Panel = React__namespace.forwardRef(({ children, title }, ref) => {
3012
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3013
+ designSystem.Flex,
3014
+ {
3015
+ ref,
3016
+ tag: "aside",
3017
+ "aria-labelledby": "additional-information",
3018
+ background: "neutral0",
3019
+ borderColor: "neutral150",
3020
+ hasRadius: true,
3021
+ paddingBottom: 4,
3022
+ paddingLeft: 4,
3023
+ paddingRight: 4,
3024
+ paddingTop: 4,
3025
+ shadow: "tableShadow",
3026
+ gap: 3,
3027
+ direction: "column",
3028
+ justifyContent: "stretch",
3029
+ alignItems: "flex-start",
3030
+ children: [
3031
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { tag: "h2", variant: "sigma", textTransform: "uppercase", children: title }),
3032
+ children
3033
+ ]
3034
+ }
3035
+ );
3036
+ });
2930
3037
  const ConfirmBulkActionDialog = ({
2931
3038
  onToggleDialog,
2932
3039
  isOpen = false,
@@ -2965,6 +3072,7 @@ const ConfirmDialogPublishAll = ({
2965
3072
  const { _unstableFormatAPIError: formatAPIError } = strapiAdmin.useAPIErrorHandler(getTranslation);
2966
3073
  const { model, schema } = useDoc();
2967
3074
  const [{ query }] = strapiAdmin.useQueryParams();
3075
+ const enableDraftRelationsCount = false;
2968
3076
  const {
2969
3077
  data: countDraftRelations = 0,
2970
3078
  isLoading,
@@ -2976,7 +3084,7 @@ const ConfirmDialogPublishAll = ({
2976
3084
  locale: query?.plugins?.i18n?.locale
2977
3085
  },
2978
3086
  {
2979
- skip: selectedEntries.length === 0
3087
+ skip: !enableDraftRelationsCount
2980
3088
  }
2981
3089
  );
2982
3090
  React__namespace.useEffect(() => {
@@ -3161,7 +3269,7 @@ const SelectedEntriesTableContent = ({
3161
3269
  status: row.status
3162
3270
  }
3163
3271
  ) }),
3164
- /* @__PURE__ */ jsxRuntime.jsx(strapiAdmin.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
3272
+ /* @__PURE__ */ jsxRuntime.jsx(strapiAdmin.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { children: /* @__PURE__ */ jsxRuntime.jsx(
3165
3273
  designSystem.IconButton,
3166
3274
  {
3167
3275
  tag: reactRouterDom.Link,
@@ -3184,9 +3292,10 @@ const SelectedEntriesTableContent = ({
3184
3292
  ),
3185
3293
  target: "_blank",
3186
3294
  marginLeft: "auto",
3187
- children: /* @__PURE__ */ jsxRuntime.jsx(Icons.Pencil, {})
3295
+ variant: "ghost",
3296
+ children: /* @__PURE__ */ jsxRuntime.jsx(Icons.Pencil, { width: "1.6rem", height: "1.6rem" })
3188
3297
  }
3189
- ) })
3298
+ ) }) })
3190
3299
  ] }, row.id)) })
3191
3300
  ] });
3192
3301
  };
@@ -3921,7 +4030,7 @@ const index = {
3921
4030
  app.router.addRoute({
3922
4031
  path: "content-manager/*",
3923
4032
  lazy: async () => {
3924
- const { Layout } = await Promise.resolve().then(() => require("./layout-C788OmNr.js"));
4033
+ const { Layout } = await Promise.resolve().then(() => require("./layout-B2MyZU-_.js"));
3925
4034
  return {
3926
4035
  Component: Layout
3927
4036
  };
@@ -3938,7 +4047,7 @@ const index = {
3938
4047
  async registerTrads({ locales }) {
3939
4048
  const importedTrads = await Promise.all(
3940
4049
  locales.map((locale) => {
3941
- return __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "./translations/ar.json": () => Promise.resolve().then(() => require("./ar-BUUWXIYu.js")), "./translations/ca.json": () => Promise.resolve().then(() => require("./ca-Cmk45QO6.js")), "./translations/cs.json": () => Promise.resolve().then(() => require("./cs-CkJy6B2v.js")), "./translations/de.json": () => Promise.resolve().then(() => require("./de-CCEmbAah.js")), "./translations/en.json": () => Promise.resolve().then(() => require("./en-uOUIxfcQ.js")), "./translations/es.json": () => Promise.resolve().then(() => require("./es-EUonQTon.js")), "./translations/eu.json": () => Promise.resolve().then(() => require("./eu-VDH-3ovk.js")), "./translations/fr.json": () => Promise.resolve().then(() => require("./fr-B7kGGg3E.js")), "./translations/gu.json": () => Promise.resolve().then(() => require("./gu-BRmF601H.js")), "./translations/hi.json": () => Promise.resolve().then(() => require("./hi-CCJBptSq.js")), "./translations/hu.json": () => Promise.resolve().then(() => require("./hu-sNV_yLYy.js")), "./translations/id.json": () => Promise.resolve().then(() => require("./id-B5Ser98A.js")), "./translations/it.json": () => Promise.resolve().then(() => require("./it-DkBIs7vD.js")), "./translations/ja.json": () => Promise.resolve().then(() => require("./ja-CcFe8diO.js")), "./translations/ko.json": () => Promise.resolve().then(() => require("./ko-woFZPmLk.js")), "./translations/ml.json": () => Promise.resolve().then(() => require("./ml-C2W8N8k1.js")), "./translations/ms.json": () => Promise.resolve().then(() => require("./ms-BuFotyP_.js")), "./translations/nl.json": () => Promise.resolve().then(() => require("./nl-bbEOHChV.js")), "./translations/pl.json": () => Promise.resolve().then(() => require("./pl-uzwG-hk7.js")), "./translations/pt-BR.json": () => Promise.resolve().then(() => require("./pt-BR-BiOz37D9.js")), "./translations/pt.json": () => Promise.resolve().then(() => require("./pt-CeXQuq50.js")), "./translations/ru.json": () => Promise.resolve().then(() => require("./ru-BT3ybNny.js")), "./translations/sa.json": () => Promise.resolve().then(() => require("./sa-CcvkYInH.js")), "./translations/sk.json": () => Promise.resolve().then(() => require("./sk-CvY09Xjv.js")), "./translations/sv.json": () => Promise.resolve().then(() => require("./sv-MYDuzgvT.js")), "./translations/th.json": () => Promise.resolve().then(() => require("./th-D9_GfAjc.js")), "./translations/tr.json": () => Promise.resolve().then(() => require("./tr-D9UH-O_R.js")), "./translations/uk.json": () => Promise.resolve().then(() => require("./uk-C8EiqJY7.js")), "./translations/vi.json": () => Promise.resolve().then(() => require("./vi-CJlYDheJ.js")), "./translations/zh-Hans.json": () => Promise.resolve().then(() => require("./zh-Hans-9kOncHGw.js")), "./translations/zh.json": () => Promise.resolve().then(() => require("./zh-CQQfszqR.js")) }), `./translations/${locale}.json`).then(({ default: data }) => {
4050
+ return __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "./translations/ar.json": () => Promise.resolve().then(() => require("./ar-BUUWXIYu.js")), "./translations/ca.json": () => Promise.resolve().then(() => require("./ca-Cmk45QO6.js")), "./translations/cs.json": () => Promise.resolve().then(() => require("./cs-CkJy6B2v.js")), "./translations/de.json": () => Promise.resolve().then(() => require("./de-CCEmbAah.js")), "./translations/en.json": () => Promise.resolve().then(() => require("./en-Bm0D0IWz.js")), "./translations/es.json": () => Promise.resolve().then(() => require("./es-EUonQTon.js")), "./translations/eu.json": () => Promise.resolve().then(() => require("./eu-VDH-3ovk.js")), "./translations/fr.json": () => Promise.resolve().then(() => require("./fr-B7kGGg3E.js")), "./translations/gu.json": () => Promise.resolve().then(() => require("./gu-BRmF601H.js")), "./translations/hi.json": () => Promise.resolve().then(() => require("./hi-CCJBptSq.js")), "./translations/hu.json": () => Promise.resolve().then(() => require("./hu-sNV_yLYy.js")), "./translations/id.json": () => Promise.resolve().then(() => require("./id-B5Ser98A.js")), "./translations/it.json": () => Promise.resolve().then(() => require("./it-DkBIs7vD.js")), "./translations/ja.json": () => Promise.resolve().then(() => require("./ja-CcFe8diO.js")), "./translations/ko.json": () => Promise.resolve().then(() => require("./ko-woFZPmLk.js")), "./translations/ml.json": () => Promise.resolve().then(() => require("./ml-C2W8N8k1.js")), "./translations/ms.json": () => Promise.resolve().then(() => require("./ms-BuFotyP_.js")), "./translations/nl.json": () => Promise.resolve().then(() => require("./nl-bbEOHChV.js")), "./translations/pl.json": () => Promise.resolve().then(() => require("./pl-uzwG-hk7.js")), "./translations/pt-BR.json": () => Promise.resolve().then(() => require("./pt-BR-BiOz37D9.js")), "./translations/pt.json": () => Promise.resolve().then(() => require("./pt-CeXQuq50.js")), "./translations/ru.json": () => Promise.resolve().then(() => require("./ru-BT3ybNny.js")), "./translations/sa.json": () => Promise.resolve().then(() => require("./sa-CcvkYInH.js")), "./translations/sk.json": () => Promise.resolve().then(() => require("./sk-CvY09Xjv.js")), "./translations/sv.json": () => Promise.resolve().then(() => require("./sv-MYDuzgvT.js")), "./translations/th.json": () => Promise.resolve().then(() => require("./th-D9_GfAjc.js")), "./translations/tr.json": () => Promise.resolve().then(() => require("./tr-D9UH-O_R.js")), "./translations/uk.json": () => Promise.resolve().then(() => require("./uk-C8EiqJY7.js")), "./translations/vi.json": () => Promise.resolve().then(() => require("./vi-CJlYDheJ.js")), "./translations/zh-Hans.json": () => Promise.resolve().then(() => require("./zh-Hans-9kOncHGw.js")), "./translations/zh.json": () => Promise.resolve().then(() => require("./zh-CQQfszqR.js")) }), `./translations/${locale}.json`).then(({ default: data }) => {
3942
4051
  return {
3943
4052
  data: prefixPluginTranslations(data, PLUGIN_ID),
3944
4053
  locale
@@ -3984,6 +4093,7 @@ exports.getMainField = getMainField;
3984
4093
  exports.getTranslation = getTranslation;
3985
4094
  exports.index = index;
3986
4095
  exports.setInitialData = setInitialData;
4096
+ exports.useContentManagerContext = useContentManagerContext;
3987
4097
  exports.useContentTypeSchema = useContentTypeSchema;
3988
4098
  exports.useDoc = useDoc;
3989
4099
  exports.useDocLayout = useDocLayout;
@@ -3996,4 +4106,4 @@ exports.useGetAllDocumentsQuery = useGetAllDocumentsQuery;
3996
4106
  exports.useGetContentTypeConfigurationQuery = useGetContentTypeConfigurationQuery;
3997
4107
  exports.useGetInitialDataQuery = useGetInitialDataQuery;
3998
4108
  exports.useUpdateContentTypeConfigurationMutation = useUpdateContentTypeConfigurationMutation;
3999
- //# sourceMappingURL=index-C3fJE-1-.js.map
4109
+ //# sourceMappingURL=index-BdMf2lfT.js.map