@strapi/i18n 0.0.0-next.fc1775f7731f8999840e56e298a216b9a6c5c4ad → 0.0.0-next.fdac61dd05ca665168f51f655f1d165b55ec4231

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 (126) hide show
  1. package/dist/admin/chunks/SettingsPage-CcMc5fyu.js +820 -0
  2. package/dist/admin/chunks/SettingsPage-CcMc5fyu.js.map +1 -0
  3. package/dist/admin/chunks/SettingsPage-g9SsggAu.mjs +797 -0
  4. package/dist/admin/chunks/SettingsPage-g9SsggAu.mjs.map +1 -0
  5. package/dist/admin/chunks/de-Cm8mYdaO.mjs +64 -0
  6. package/dist/admin/chunks/de-Cm8mYdaO.mjs.map +1 -0
  7. package/dist/admin/chunks/de-nEMWvIiY.js +66 -0
  8. package/dist/admin/chunks/de-nEMWvIiY.js.map +1 -0
  9. package/dist/admin/chunks/dk-BeUFOegB.mjs +64 -0
  10. package/dist/admin/chunks/dk-BeUFOegB.mjs.map +1 -0
  11. package/dist/admin/chunks/dk-CYATLPVe.js +66 -0
  12. package/dist/admin/chunks/dk-CYATLPVe.js.map +1 -0
  13. package/dist/admin/chunks/en-CG5cUCbD.js +81 -0
  14. package/dist/admin/chunks/en-CG5cUCbD.js.map +1 -0
  15. package/dist/admin/chunks/en-eWSaCeOb.mjs +79 -0
  16. package/dist/admin/chunks/en-eWSaCeOb.mjs.map +1 -0
  17. package/dist/admin/chunks/es-CWsogTGm.js +66 -0
  18. package/dist/admin/chunks/es-CWsogTGm.js.map +1 -0
  19. package/dist/admin/chunks/es-DqF_IdAc.mjs +64 -0
  20. package/dist/admin/chunks/es-DqF_IdAc.mjs.map +1 -0
  21. package/dist/admin/chunks/fr-CC7UFcYd.js +66 -0
  22. package/dist/admin/chunks/fr-CC7UFcYd.js.map +1 -0
  23. package/dist/admin/chunks/fr-CyARbZ3c.mjs +64 -0
  24. package/dist/admin/chunks/fr-CyARbZ3c.mjs.map +1 -0
  25. package/dist/admin/chunks/index-BWv_l535.mjs +2007 -0
  26. package/dist/admin/chunks/index-BWv_l535.mjs.map +1 -0
  27. package/dist/admin/chunks/index-Cek49tl0.js +2036 -0
  28. package/dist/admin/chunks/index-Cek49tl0.js.map +1 -0
  29. package/dist/admin/chunks/ko-Ax4NSedM.mjs +63 -0
  30. package/dist/admin/chunks/ko-Ax4NSedM.mjs.map +1 -0
  31. package/dist/admin/chunks/ko-XwGmfhoq.js +65 -0
  32. package/dist/admin/chunks/ko-XwGmfhoq.js.map +1 -0
  33. package/dist/admin/chunks/pl-B-aqvMqL.mjs +64 -0
  34. package/dist/admin/chunks/pl-B-aqvMqL.mjs.map +1 -0
  35. package/dist/admin/chunks/pl-B_vzY_ZB.js +66 -0
  36. package/dist/admin/chunks/pl-B_vzY_ZB.js.map +1 -0
  37. package/dist/admin/chunks/ru-VkPjQ-Sk.mjs +66 -0
  38. package/dist/admin/chunks/ru-VkPjQ-Sk.mjs.map +1 -0
  39. package/dist/admin/chunks/ru-WzHcJV1f.js +68 -0
  40. package/dist/admin/chunks/ru-WzHcJV1f.js.map +1 -0
  41. package/dist/admin/chunks/tr-CcWp6u3w.js +66 -0
  42. package/dist/admin/chunks/tr-CcWp6u3w.js.map +1 -0
  43. package/dist/admin/chunks/tr-DcTR88c9.mjs +64 -0
  44. package/dist/admin/chunks/tr-DcTR88c9.mjs.map +1 -0
  45. package/dist/admin/chunks/zh-C9So4SGq.js +66 -0
  46. package/dist/admin/chunks/zh-C9So4SGq.js.map +1 -0
  47. package/dist/admin/chunks/zh-Hans-DnU2bhri.js +57 -0
  48. package/dist/admin/chunks/zh-Hans-DnU2bhri.js.map +1 -0
  49. package/dist/admin/chunks/zh-Hans-L3wsRegj.mjs +55 -0
  50. package/dist/admin/chunks/zh-Hans-L3wsRegj.mjs.map +1 -0
  51. package/dist/admin/chunks/zh-RZyMiPIs.mjs +64 -0
  52. package/dist/admin/chunks/zh-RZyMiPIs.mjs.map +1 -0
  53. package/dist/admin/index.js +20 -4
  54. package/dist/admin/index.js.map +1 -1
  55. package/dist/admin/index.mjs +15 -6
  56. package/dist/admin/index.mjs.map +1 -1
  57. package/dist/admin/src/components/CMHeaderActions.d.ts +1 -1
  58. package/dist/admin/src/components/tests/CreateLocale.test.d.ts +1 -0
  59. package/dist/admin/src/components/tests/DeleteLocale.test.d.ts +1 -0
  60. package/dist/admin/src/components/tests/EditLocale.test.d.ts +1 -0
  61. package/dist/admin/src/components/tests/LocaleListCell.test.d.ts +1 -0
  62. package/dist/admin/src/contentReleasesHooks/releaseDetailsView.d.ts +1 -1
  63. package/dist/admin/src/pages/tests/SettingsPage.test.d.ts +1 -0
  64. package/dist/admin/tests/server.d.ts +1 -0
  65. package/dist/admin/tests/utils.d.ts +6 -0
  66. package/dist/server/index.js +3650 -3390
  67. package/dist/server/index.js.map +1 -1
  68. package/dist/server/index.mjs +3632 -3374
  69. package/dist/server/index.mjs.map +1 -1
  70. package/dist/server/src/services/localizations.d.ts +1 -1
  71. package/dist/server/src/services/localizations.d.ts.map +1 -1
  72. package/dist/shared/contracts/content-manager.d.ts +1 -1
  73. package/dist/shared/contracts/shared.d.ts +1 -1
  74. package/package.json +14 -11
  75. package/dist/_chunks/SettingsPage-B6QDUmu9.mjs +0 -554
  76. package/dist/_chunks/SettingsPage-B6QDUmu9.mjs.map +0 -1
  77. package/dist/_chunks/SettingsPage-BsHtr3lV.js +0 -573
  78. package/dist/_chunks/SettingsPage-BsHtr3lV.js.map +0 -1
  79. package/dist/_chunks/de-9eCAqqrB.mjs +0 -66
  80. package/dist/_chunks/de-9eCAqqrB.mjs.map +0 -1
  81. package/dist/_chunks/de-DtWiGdHl.js +0 -66
  82. package/dist/_chunks/de-DtWiGdHl.js.map +0 -1
  83. package/dist/_chunks/dk-2qBjxt-P.mjs +0 -66
  84. package/dist/_chunks/dk-2qBjxt-P.mjs.map +0 -1
  85. package/dist/_chunks/dk-D8C-casx.js +0 -66
  86. package/dist/_chunks/dk-D8C-casx.js.map +0 -1
  87. package/dist/_chunks/en-BKBz3tro.js +0 -81
  88. package/dist/_chunks/en-BKBz3tro.js.map +0 -1
  89. package/dist/_chunks/en-DlXfy6Gy.mjs +0 -81
  90. package/dist/_chunks/en-DlXfy6Gy.mjs.map +0 -1
  91. package/dist/_chunks/es-DS-XFGSw.js +0 -66
  92. package/dist/_chunks/es-DS-XFGSw.js.map +0 -1
  93. package/dist/_chunks/es-DlmMVaBG.mjs +0 -66
  94. package/dist/_chunks/es-DlmMVaBG.mjs.map +0 -1
  95. package/dist/_chunks/fr-3S6ke71d.mjs +0 -66
  96. package/dist/_chunks/fr-3S6ke71d.mjs.map +0 -1
  97. package/dist/_chunks/fr-BTjekDpq.js +0 -66
  98. package/dist/_chunks/fr-BTjekDpq.js.map +0 -1
  99. package/dist/_chunks/index-3XgwXL6T.js +0 -1628
  100. package/dist/_chunks/index-3XgwXL6T.js.map +0 -1
  101. package/dist/_chunks/index-iEQ79W05.mjs +0 -1607
  102. package/dist/_chunks/index-iEQ79W05.mjs.map +0 -1
  103. package/dist/_chunks/ko-DmcGUBQ3.js +0 -65
  104. package/dist/_chunks/ko-DmcGUBQ3.js.map +0 -1
  105. package/dist/_chunks/ko-qTjQ8IMw.mjs +0 -65
  106. package/dist/_chunks/ko-qTjQ8IMw.mjs.map +0 -1
  107. package/dist/_chunks/pl-B67TSHqT.mjs +0 -66
  108. package/dist/_chunks/pl-B67TSHqT.mjs.map +0 -1
  109. package/dist/_chunks/pl-Cn5RYonZ.js +0 -66
  110. package/dist/_chunks/pl-Cn5RYonZ.js.map +0 -1
  111. package/dist/_chunks/ru-BMBgVL3s.js +0 -68
  112. package/dist/_chunks/ru-BMBgVL3s.js.map +0 -1
  113. package/dist/_chunks/ru-hagMa57T.mjs +0 -68
  114. package/dist/_chunks/ru-hagMa57T.mjs.map +0 -1
  115. package/dist/_chunks/tr-CarUU76c.js +0 -66
  116. package/dist/_chunks/tr-CarUU76c.js.map +0 -1
  117. package/dist/_chunks/tr-Dw_jmkG-.mjs +0 -66
  118. package/dist/_chunks/tr-Dw_jmkG-.mjs.map +0 -1
  119. package/dist/_chunks/zh-57YM4amO.mjs +0 -66
  120. package/dist/_chunks/zh-57YM4amO.mjs.map +0 -1
  121. package/dist/_chunks/zh-CukOviB0.js +0 -66
  122. package/dist/_chunks/zh-CukOviB0.js.map +0 -1
  123. package/dist/_chunks/zh-Hans-DSHIXAa3.js +0 -57
  124. package/dist/_chunks/zh-Hans-DSHIXAa3.js.map +0 -1
  125. package/dist/_chunks/zh-Hans-Dyc-aR-h.mjs +0 -57
  126. package/dist/_chunks/zh-Hans-Dyc-aR-h.mjs.map +0 -1
@@ -0,0 +1,2007 @@
1
+ import get from 'lodash/get';
2
+ import * as yup from 'yup';
3
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
4
+ import * as React from 'react';
5
+ import { Typography, Dialog, Field, Checkbox, Flex, Button, Modal, Box, Status, IconButton, Tooltip, SingleSelect, SingleSelectOption, VisuallyHidden, useCollator, Popover } from '@strapi/design-system';
6
+ import { WarningCircle, Pencil, CrossCircle, CheckCircle, ArrowsCounterClockwise, Trash, Plus, Earth, ListPlus, Cross, CaretDown } from '@strapi/icons';
7
+ import { useIntl } from 'react-intl';
8
+ import { styled } from 'styled-components';
9
+ import { skipToken } from '@reduxjs/toolkit/query';
10
+ import { useAuth, adminApi, useTable, Table, useQueryParams, useForm, useNotification, useAPIErrorHandler } from '@strapi/admin/strapi-admin';
11
+ import { unstable_useDocument, unstable_useDocumentActions, buildValidParams } from '@strapi/content-manager/strapi-admin';
12
+ import { useParams, Link, useNavigate, matchPath } from 'react-router-dom';
13
+ import * as qs from 'qs';
14
+ import { stringify } from 'qs';
15
+ import omit from 'lodash/omit';
16
+
17
+ const pluginId = 'i18n';
18
+
19
+ const getTranslation = (id)=>`${pluginId}.${id}`;
20
+
21
+ const TextAlignTypography = styled(Typography)`
22
+ text-align: center;
23
+ `;
24
+ const CheckboxConfirmation = ({ description, isCreating = false, intlLabel, name, onChange, value })=>{
25
+ const { formatMessage } = useIntl();
26
+ const [isOpen, setIsOpen] = React.useState(false);
27
+ const handleChange = (value)=>{
28
+ if (isCreating || value) {
29
+ return onChange({
30
+ target: {
31
+ name,
32
+ value,
33
+ type: 'checkbox'
34
+ }
35
+ });
36
+ }
37
+ if (!value) {
38
+ return setIsOpen(true);
39
+ }
40
+ return null;
41
+ };
42
+ const handleConfirm = ()=>{
43
+ onChange({
44
+ target: {
45
+ name,
46
+ value: false,
47
+ type: 'checkbox'
48
+ }
49
+ });
50
+ };
51
+ const label = intlLabel.id ? formatMessage({
52
+ id: intlLabel.id,
53
+ defaultMessage: intlLabel.defaultMessage
54
+ }, {
55
+ ...intlLabel.values
56
+ }) : name;
57
+ const hint = description ? formatMessage({
58
+ id: description.id,
59
+ defaultMessage: description.defaultMessage
60
+ }, {
61
+ ...description.values
62
+ }) : '';
63
+ return /*#__PURE__*/ jsxs(Dialog.Root, {
64
+ open: isOpen,
65
+ onOpenChange: setIsOpen,
66
+ children: [
67
+ /*#__PURE__*/ jsxs(Field.Root, {
68
+ hint: hint,
69
+ name: name,
70
+ children: [
71
+ /*#__PURE__*/ jsx(Checkbox, {
72
+ onCheckedChange: handleChange,
73
+ checked: value,
74
+ children: label
75
+ }),
76
+ /*#__PURE__*/ jsx(Field.Hint, {})
77
+ ]
78
+ }),
79
+ /*#__PURE__*/ jsxs(Dialog.Content, {
80
+ children: [
81
+ /*#__PURE__*/ jsx(Dialog.Header, {
82
+ children: formatMessage({
83
+ id: getTranslation('CheckboxConfirmation.Modal.title'),
84
+ defaultMessage: 'Disable localization'
85
+ })
86
+ }),
87
+ /*#__PURE__*/ jsx(Dialog.Body, {
88
+ icon: /*#__PURE__*/ jsx(WarningCircle, {}),
89
+ children: /*#__PURE__*/ jsxs(Flex, {
90
+ direction: "column",
91
+ alignItems: "stretch",
92
+ gap: 2,
93
+ children: [
94
+ /*#__PURE__*/ jsx(Flex, {
95
+ justifyContent: "center",
96
+ children: /*#__PURE__*/ jsx(TextAlignTypography, {
97
+ children: formatMessage({
98
+ id: getTranslation('CheckboxConfirmation.Modal.content'),
99
+ defaultMessage: 'Disabling localization will engender the deletion of all your content but the one associated to your default locale (if existing).'
100
+ })
101
+ })
102
+ }),
103
+ /*#__PURE__*/ jsx(Flex, {
104
+ justifyContent: "center",
105
+ children: /*#__PURE__*/ jsx(Typography, {
106
+ fontWeight: "semiBold",
107
+ children: formatMessage({
108
+ id: getTranslation('CheckboxConfirmation.Modal.body'),
109
+ defaultMessage: 'Do you want to disable it?'
110
+ })
111
+ })
112
+ })
113
+ ]
114
+ })
115
+ }),
116
+ /*#__PURE__*/ jsxs(Dialog.Footer, {
117
+ children: [
118
+ /*#__PURE__*/ jsx(Dialog.Cancel, {
119
+ children: /*#__PURE__*/ jsx(Button, {
120
+ variant: "tertiary",
121
+ children: formatMessage({
122
+ id: 'components.popUpWarning.button.cancel',
123
+ defaultMessage: 'No, cancel'
124
+ })
125
+ })
126
+ }),
127
+ /*#__PURE__*/ jsx(Dialog.Action, {
128
+ children: /*#__PURE__*/ jsx(Button, {
129
+ variant: "danger-light",
130
+ onClick: handleConfirm,
131
+ children: formatMessage({
132
+ id: getTranslation('CheckboxConfirmation.Modal.button-confirm'),
133
+ defaultMessage: 'Yes, disable'
134
+ })
135
+ })
136
+ })
137
+ ]
138
+ })
139
+ ]
140
+ })
141
+ ]
142
+ });
143
+ };
144
+
145
+ const LOCALIZED_FIELDS = [
146
+ 'biginteger',
147
+ 'boolean',
148
+ 'component',
149
+ 'date',
150
+ 'datetime',
151
+ 'decimal',
152
+ 'dynamiczone',
153
+ 'email',
154
+ 'enumeration',
155
+ 'float',
156
+ 'integer',
157
+ 'json',
158
+ 'media',
159
+ 'number',
160
+ 'password',
161
+ 'richtext',
162
+ 'blocks',
163
+ 'string',
164
+ 'text',
165
+ 'time'
166
+ ];
167
+ const doesPluginOptionsHaveI18nLocalized = (opts)=>typeof opts === 'object' && opts !== null && 'i18n' in opts && typeof opts.i18n === 'object' && opts.i18n !== null && 'localized' in opts.i18n && typeof opts.i18n.localized === 'boolean';
168
+
169
+ const capitalize = (str)=>str.charAt(0).toUpperCase() + str.slice(1);
170
+
171
+ /**
172
+ * @alpha
173
+ * @description This hook is used to get the i18n status of a content type.
174
+ * Also returns the CRUDP permission locale properties for the content type
175
+ * so we know which locales the user can perform actions on.
176
+ */ const useI18n = ()=>{
177
+ // Extract the params from the URL to pass to our useDocument hook
178
+ const params = useParams();
179
+ const userPermissions = useAuth('useI18n', (state)=>state.permissions);
180
+ const actions = React.useMemo(()=>{
181
+ const permissions = userPermissions.filter((permission)=>permission.subject === params.slug);
182
+ return permissions.reduce((acc, permission)=>{
183
+ const [actionShorthand] = permission.action.split('.').slice(-1);
184
+ return {
185
+ ...acc,
186
+ [`can${capitalize(actionShorthand)}`]: permission.properties?.locales ?? []
187
+ };
188
+ }, {
189
+ canCreate: [],
190
+ canRead: [],
191
+ canUpdate: [],
192
+ canDelete: [],
193
+ canPublish: []
194
+ });
195
+ }, [
196
+ params.slug,
197
+ userPermissions
198
+ ]);
199
+ // TODO: use specific hook to get schema only
200
+ const { schema } = unstable_useDocument({
201
+ // We can non-null assert these because below we skip the query if they are not present
202
+ collectionType: params.collectionType,
203
+ model: params.slug
204
+ }, {
205
+ skip: true
206
+ });
207
+ if (doesPluginOptionsHaveI18nLocalized(schema?.pluginOptions)) {
208
+ return {
209
+ hasI18n: schema.pluginOptions.i18n.localized,
210
+ ...actions
211
+ };
212
+ }
213
+ return {
214
+ hasI18n: false,
215
+ ...actions
216
+ };
217
+ };
218
+
219
+ const i18nApi = adminApi.enhanceEndpoints({
220
+ addTagTypes: [
221
+ 'Locale'
222
+ ]
223
+ });
224
+
225
+ const localesApi = i18nApi.injectEndpoints({
226
+ endpoints: (builder)=>({
227
+ createLocale: builder.mutation({
228
+ query: (data)=>({
229
+ url: '/i18n/locales',
230
+ method: 'POST',
231
+ data
232
+ }),
233
+ invalidatesTags: [
234
+ {
235
+ type: 'Locale',
236
+ id: 'LIST'
237
+ }
238
+ ]
239
+ }),
240
+ deleteLocale: builder.mutation({
241
+ query: (id)=>({
242
+ url: `/i18n/locales/${id}`,
243
+ method: 'DELETE'
244
+ }),
245
+ invalidatesTags: (result, error, id)=>[
246
+ {
247
+ type: 'Locale',
248
+ id
249
+ }
250
+ ]
251
+ }),
252
+ getLocales: builder.query({
253
+ query: ()=>'/i18n/locales',
254
+ providesTags: (res)=>[
255
+ {
256
+ type: 'Locale',
257
+ id: 'LIST'
258
+ },
259
+ ...Array.isArray(res) ? res.map((locale)=>({
260
+ type: 'Locale',
261
+ id: locale.id
262
+ })) : []
263
+ ]
264
+ }),
265
+ getDefaultLocales: builder.query({
266
+ query: ()=>'/i18n/iso-locales'
267
+ }),
268
+ updateLocale: builder.mutation({
269
+ query: ({ id, ...data })=>({
270
+ url: `/i18n/locales/${id}`,
271
+ method: 'PUT',
272
+ data
273
+ }),
274
+ invalidatesTags: (result, error, { id })=>[
275
+ {
276
+ type: 'Locale',
277
+ id
278
+ }
279
+ ]
280
+ })
281
+ })
282
+ });
283
+ const { useCreateLocaleMutation, useDeleteLocaleMutation, useGetLocalesQuery, useGetDefaultLocalesQuery, useUpdateLocaleMutation } = localesApi;
284
+
285
+ const relationsApi = i18nApi.injectEndpoints({
286
+ overrideExisting: true,
287
+ endpoints: (builder)=>({
288
+ getManyDraftRelationCount: builder.query({
289
+ query: ({ model, ...params })=>({
290
+ url: `/content-manager/collection-types/${model}/actions/countManyEntriesDraftRelations`,
291
+ method: 'GET',
292
+ config: {
293
+ params
294
+ }
295
+ }),
296
+ transformResponse: (response)=>response.data
297
+ })
298
+ })
299
+ });
300
+ const { useGetManyDraftRelationCountQuery } = relationsApi;
301
+
302
+ const cleanData = (data, schema, components)=>{
303
+ const cleanedData = removeFields(data, [
304
+ 'createdAt',
305
+ 'createdBy',
306
+ 'updatedAt',
307
+ 'updatedBy',
308
+ 'id',
309
+ 'documentId',
310
+ 'publishedAt',
311
+ 'strapi_stage',
312
+ 'strapi_assignee',
313
+ 'locale',
314
+ 'status'
315
+ ]);
316
+ const cleanedDataWithoutPasswordAndRelation = recursiveRemoveFieldTypes(cleanedData, schema, components, [
317
+ 'relation',
318
+ 'password'
319
+ ]);
320
+ return cleanedDataWithoutPasswordAndRelation;
321
+ };
322
+ const removeFields = (data, fields)=>{
323
+ return Object.keys(data).reduce((acc, current)=>{
324
+ if (fields.includes(current)) {
325
+ return acc;
326
+ }
327
+ acc[current] = data[current];
328
+ return acc;
329
+ }, {});
330
+ };
331
+ const recursiveRemoveFieldTypes = (data, schema, components, fields)=>{
332
+ return Object.keys(data).reduce((acc, current)=>{
333
+ const attribute = schema.attributes[current] ?? {
334
+ type: undefined
335
+ };
336
+ if (fields.includes(attribute.type)) {
337
+ return acc;
338
+ }
339
+ if (attribute.type === 'dynamiczone') {
340
+ acc[current] = data[current].map((componentValue, index)=>{
341
+ const { id: _, ...rest } = recursiveRemoveFieldTypes(componentValue, components[componentValue.__component], components, fields);
342
+ return {
343
+ ...rest,
344
+ __temp_key__: index + 1
345
+ };
346
+ });
347
+ } else if (attribute.type === 'component') {
348
+ const { repeatable, component } = attribute;
349
+ if (repeatable) {
350
+ acc[current] = (data[current] ?? []).map((compoData, index)=>{
351
+ const { id: _, ...rest } = recursiveRemoveFieldTypes(compoData, components[component], components, fields);
352
+ return {
353
+ ...rest,
354
+ __temp_key__: index + 1
355
+ };
356
+ });
357
+ } else {
358
+ const { id: _, ...rest } = recursiveRemoveFieldTypes(data[current] ?? {}, components[component], components, fields);
359
+ acc[current] = rest;
360
+ }
361
+ } else {
362
+ acc[current] = data[current];
363
+ }
364
+ return acc;
365
+ }, {});
366
+ };
367
+
368
+ const isErrorMessageDescriptor = (object)=>{
369
+ return typeof object === 'object' && object !== null && 'id' in object && 'defaultMessage' in object;
370
+ };
371
+ const EntryValidationText = ({ status = 'draft', validationErrors, action })=>{
372
+ const { formatMessage } = useIntl();
373
+ /**
374
+ * TODO: Should this be extracted an made into a factory to recursively get
375
+ * error messages??
376
+ */ const getErrorStr = (key, value)=>{
377
+ if (typeof value === 'string') {
378
+ return `${key}: ${value}`;
379
+ } else if (isErrorMessageDescriptor(value)) {
380
+ return `${key}: ${formatMessage(value)}`;
381
+ } else if (Array.isArray(value)) {
382
+ return value.map((v)=>getErrorStr(key, v)).join(' ');
383
+ } else if (typeof value === 'object' && !Array.isArray(value)) {
384
+ return Object.entries(value).map(([k, v])=>getErrorStr(k, v)).join(' ');
385
+ } else {
386
+ /**
387
+ * unlikely to happen, but we need to return something
388
+ */ return '';
389
+ }
390
+ };
391
+ if (validationErrors) {
392
+ const validationErrorsMessages = Object.entries(validationErrors).map(([key, value])=>{
393
+ return getErrorStr(key, value);
394
+ }).join(' ');
395
+ return /*#__PURE__*/ jsxs(Flex, {
396
+ gap: 2,
397
+ children: [
398
+ /*#__PURE__*/ jsx(CrossCircle, {
399
+ fill: "danger600"
400
+ }),
401
+ /*#__PURE__*/ jsx(Tooltip, {
402
+ label: validationErrorsMessages,
403
+ children: /*#__PURE__*/ jsx(Typography, {
404
+ maxWidth: '30rem',
405
+ textColor: "danger600",
406
+ variant: "omega",
407
+ fontWeight: "semiBold",
408
+ ellipsis: true,
409
+ children: validationErrorsMessages
410
+ })
411
+ })
412
+ ]
413
+ });
414
+ }
415
+ const getStatusMessage = ()=>{
416
+ if (action === 'bulk-publish') {
417
+ if (status === 'published') {
418
+ return {
419
+ icon: /*#__PURE__*/ jsx(CheckCircle, {
420
+ fill: "success600"
421
+ }),
422
+ text: formatMessage({
423
+ id: 'content-manager.bulk-publish.already-published',
424
+ defaultMessage: 'Already Published'
425
+ }),
426
+ textColor: 'success600',
427
+ fontWeight: 'bold'
428
+ };
429
+ } else if (status === 'modified') {
430
+ return {
431
+ icon: /*#__PURE__*/ jsx(ArrowsCounterClockwise, {
432
+ fill: "alternative600"
433
+ }),
434
+ text: formatMessage({
435
+ id: 'app.utils.ready-to-publish-changes',
436
+ defaultMessage: 'Ready to publish changes'
437
+ })
438
+ };
439
+ } else {
440
+ return {
441
+ icon: /*#__PURE__*/ jsx(CheckCircle, {
442
+ fill: "success600"
443
+ }),
444
+ text: formatMessage({
445
+ id: 'app.utils.ready-to-publish',
446
+ defaultMessage: 'Ready to publish'
447
+ })
448
+ };
449
+ }
450
+ } else {
451
+ if (status === 'draft') {
452
+ return {
453
+ icon: /*#__PURE__*/ jsx(CheckCircle, {
454
+ fill: "success600"
455
+ }),
456
+ text: formatMessage({
457
+ id: 'content-manager.bulk-unpublish.already-unpublished',
458
+ defaultMessage: 'Already Unpublished'
459
+ }),
460
+ textColor: 'success600',
461
+ fontWeight: 'bold'
462
+ };
463
+ } else {
464
+ return {
465
+ icon: /*#__PURE__*/ jsx(CheckCircle, {
466
+ fill: "success600"
467
+ }),
468
+ text: formatMessage({
469
+ id: 'app.utils.ready-to-unpublish-changes',
470
+ defaultMessage: 'Ready to unpublish'
471
+ }),
472
+ textColor: 'success600',
473
+ fontWeight: 'bold'
474
+ };
475
+ }
476
+ }
477
+ };
478
+ const { icon, text, textColor = 'success600', fontWeight = 'normal' } = getStatusMessage();
479
+ return /*#__PURE__*/ jsxs(Flex, {
480
+ gap: 2,
481
+ children: [
482
+ icon,
483
+ /*#__PURE__*/ jsx(Typography, {
484
+ textColor: textColor,
485
+ fontWeight: fontWeight,
486
+ children: text
487
+ })
488
+ ]
489
+ });
490
+ };
491
+ /* -------------------------------------------------------------------------------------------------
492
+ * BoldChunk
493
+ * -----------------------------------------------------------------------------------------------*/ const BoldChunk = (chunks)=>/*#__PURE__*/ jsx(Typography, {
494
+ fontWeight: "bold",
495
+ children: chunks
496
+ });
497
+ const BulkLocaleActionModal = ({ headers, rows, localesMetadata, validationErrors = {}, action })=>{
498
+ const { formatMessage } = useIntl();
499
+ const selectedRows = useTable('BulkLocaleActionModal', (state)=>state.selectedRows);
500
+ const getFormattedCountMessage = ()=>{
501
+ const currentStatusByLocale = rows.reduce((acc, { locale, status })=>{
502
+ acc[locale] = status;
503
+ return acc;
504
+ }, {});
505
+ const localesWithErrors = Object.keys(validationErrors);
506
+ const publishedCount = selectedRows.filter(({ locale })=>currentStatusByLocale[locale] === 'published').length;
507
+ const draftCount = selectedRows.filter(({ locale })=>(currentStatusByLocale[locale] === 'draft' || currentStatusByLocale[locale] === 'modified') && !localesWithErrors.includes(locale)).length;
508
+ const withErrorsCount = localesWithErrors.length;
509
+ const messageId = action === 'bulk-publish' ? 'content-manager.containers.list.selectedEntriesModal.selectedCount.publish' : 'content-manager.containers.list.selectedEntriesModal.selectedCount.unpublish';
510
+ const defaultMessage = action === 'bulk-publish' ? '<b>{publishedCount}</b> {publishedCount, plural, =0 {entries} one {entry} other {entries}} already published. <b>{draftCount}</b> {draftCount, plural, =0 {entries} one {entry} other {entries}} ready to publish. <b>{withErrorsCount}</b> {withErrorsCount, plural, =0 {entries} one {entry} other {entries}} waiting for action.' : '<b>{draftCount}</b> {draftCount, plural, =0 {entries} one {entry} other {entries}} already unpublished. <b>{publishedCount}</b> {publishedCount, plural, =0 {entries} one {entry} other {entries}} ready to unpublish.';
511
+ return formatMessage({
512
+ id: messageId,
513
+ defaultMessage
514
+ }, {
515
+ withErrorsCount,
516
+ draftCount,
517
+ publishedCount,
518
+ b: BoldChunk
519
+ });
520
+ };
521
+ return /*#__PURE__*/ jsxs(Modal.Body, {
522
+ children: [
523
+ /*#__PURE__*/ jsx(Typography, {
524
+ children: getFormattedCountMessage()
525
+ }),
526
+ /*#__PURE__*/ jsx(Box, {
527
+ marginTop: 5,
528
+ children: /*#__PURE__*/ jsxs(Table.Content, {
529
+ children: [
530
+ /*#__PURE__*/ jsxs(Table.Head, {
531
+ children: [
532
+ /*#__PURE__*/ jsx(Table.HeaderCheckboxCell, {}),
533
+ headers.map((head)=>/*#__PURE__*/ jsx(Table.HeaderCell, {
534
+ ...head
535
+ }, head.name))
536
+ ]
537
+ }),
538
+ /*#__PURE__*/ jsx(Table.Body, {
539
+ children: rows.map(({ locale, status }, index)=>{
540
+ const error = validationErrors?.[locale] ?? null;
541
+ const statusVariant = status === 'draft' ? 'primary' : status === 'published' ? 'success' : 'alternative';
542
+ return /*#__PURE__*/ jsxs(Table.Row, {
543
+ children: [
544
+ /*#__PURE__*/ jsx(Table.CheckboxCell, {
545
+ id: locale,
546
+ "aria-label": `Select ${locale}`
547
+ }),
548
+ /*#__PURE__*/ jsx(Table.Cell, {
549
+ children: /*#__PURE__*/ jsx(Typography, {
550
+ variant: "sigma",
551
+ textColor: "neutral600",
552
+ children: Array.isArray(localesMetadata) ? localesMetadata.find((localeEntry)=>localeEntry.code === locale)?.name : locale
553
+ })
554
+ }),
555
+ /*#__PURE__*/ jsx(Table.Cell, {
556
+ children: /*#__PURE__*/ jsx(Box, {
557
+ display: "flex",
558
+ children: /*#__PURE__*/ jsx(Status, {
559
+ display: "flex",
560
+ paddingLeft: "6px",
561
+ paddingRight: "6px",
562
+ paddingTop: "2px",
563
+ paddingBottom: "2px",
564
+ size: 'S',
565
+ variant: statusVariant,
566
+ children: /*#__PURE__*/ jsx(Typography, {
567
+ tag: "span",
568
+ variant: "pi",
569
+ fontWeight: "bold",
570
+ children: capitalize(status)
571
+ })
572
+ })
573
+ })
574
+ }),
575
+ /*#__PURE__*/ jsx(Table.Cell, {
576
+ children: /*#__PURE__*/ jsx(EntryValidationText, {
577
+ validationErrors: error,
578
+ status: status,
579
+ action: action
580
+ })
581
+ }),
582
+ /*#__PURE__*/ jsx(Table.Cell, {
583
+ children: /*#__PURE__*/ jsx(IconButton, {
584
+ tag: Link,
585
+ to: {
586
+ search: stringify({
587
+ plugins: {
588
+ i18n: {
589
+ locale
590
+ }
591
+ }
592
+ })
593
+ },
594
+ label: formatMessage({
595
+ id: getTranslation('Settings.list.actions.edit'),
596
+ defaultMessage: 'Edit {name} locale'
597
+ }, {
598
+ name: locale
599
+ }),
600
+ variant: "ghost",
601
+ children: /*#__PURE__*/ jsx(Pencil, {})
602
+ })
603
+ })
604
+ ]
605
+ }, index);
606
+ })
607
+ })
608
+ ]
609
+ })
610
+ })
611
+ ]
612
+ });
613
+ };
614
+
615
+ const statusVariants = {
616
+ draft: 'secondary',
617
+ published: 'success',
618
+ modified: 'alternative'
619
+ };
620
+ const LocaleOption = ({ isDraftAndPublishEnabled, locale, status, entryExists })=>{
621
+ const { formatMessage } = useIntl();
622
+ if (!entryExists) {
623
+ return formatMessage({
624
+ id: getTranslation('CMEditViewLocalePicker.locale.create'),
625
+ defaultMessage: 'Create <bold>{locale}</bold> locale'
626
+ }, {
627
+ bold: (locale)=>/*#__PURE__*/ jsx("b", {
628
+ children: locale
629
+ }),
630
+ locale: locale.name
631
+ });
632
+ }
633
+ return /*#__PURE__*/ jsxs(Flex, {
634
+ width: "100%",
635
+ gap: 1,
636
+ justifyContent: "space-between",
637
+ children: [
638
+ /*#__PURE__*/ jsx(Typography, {
639
+ children: locale.name
640
+ }),
641
+ isDraftAndPublishEnabled ? /*#__PURE__*/ jsx(Status, {
642
+ display: "flex",
643
+ paddingLeft: "6px",
644
+ paddingRight: "6px",
645
+ paddingTop: "2px",
646
+ paddingBottom: "2px",
647
+ size: "S",
648
+ variant: statusVariants[status],
649
+ children: /*#__PURE__*/ jsx(Typography, {
650
+ tag: "span",
651
+ variant: "pi",
652
+ fontWeight: "bold",
653
+ children: capitalize(status)
654
+ })
655
+ }) : null
656
+ ]
657
+ });
658
+ };
659
+ const LocalePickerAction = ({ document, meta, model, collectionType, documentId })=>{
660
+ const { formatMessage } = useIntl();
661
+ const [{ query }, setQuery] = useQueryParams();
662
+ const { hasI18n, canCreate, canRead } = useI18n();
663
+ const { data: locales = [] } = useGetLocalesQuery();
664
+ const currentDesiredLocale = query.plugins?.i18n?.locale;
665
+ const { schema } = unstable_useDocument({
666
+ model,
667
+ collectionType,
668
+ documentId,
669
+ params: {
670
+ locale: currentDesiredLocale
671
+ }
672
+ });
673
+ const handleSelect = React.useCallback((value)=>{
674
+ setQuery({
675
+ plugins: {
676
+ ...query.plugins,
677
+ i18n: {
678
+ locale: value
679
+ }
680
+ }
681
+ });
682
+ }, [
683
+ query.plugins,
684
+ setQuery
685
+ ]);
686
+ React.useEffect(()=>{
687
+ if (!Array.isArray(locales) || !hasI18n) {
688
+ return;
689
+ }
690
+ /**
691
+ * Handle the case where the current locale query param doesn't exist
692
+ * in the list of available locales, so we redirect to the default locale.
693
+ */ const doesLocaleExist = locales.find((loc)=>loc.code === currentDesiredLocale);
694
+ const defaultLocale = locales.find((locale)=>locale.isDefault);
695
+ if (!doesLocaleExist && defaultLocale?.code) {
696
+ handleSelect(defaultLocale.code);
697
+ }
698
+ }, [
699
+ handleSelect,
700
+ hasI18n,
701
+ locales,
702
+ currentDesiredLocale
703
+ ]);
704
+ const currentLocale = Array.isArray(locales) ? locales.find((locale)=>locale.code === currentDesiredLocale) : undefined;
705
+ const allCurrentLocales = [
706
+ {
707
+ status: getDocumentStatus(document, meta),
708
+ locale: currentLocale?.code
709
+ },
710
+ ...document?.localizations ?? []
711
+ ];
712
+ if (!hasI18n || !Array.isArray(locales) || locales.length === 0) {
713
+ return null;
714
+ }
715
+ const displayedLocales = locales.filter((locale)=>{
716
+ /**
717
+ * If you can read we allow you to see the locale exists
718
+ * otherwise the locale is hidden.
719
+ */ return canRead.includes(locale.code);
720
+ });
721
+ return {
722
+ label: formatMessage({
723
+ id: getTranslation('Settings.locales.modal.locales.label'),
724
+ defaultMessage: 'Locales'
725
+ }),
726
+ options: displayedLocales.map((locale)=>{
727
+ const entryWithLocaleExists = allCurrentLocales.some((doc)=>doc.locale === locale.code);
728
+ const currentLocaleDoc = allCurrentLocales.find((doc)=>'locale' in doc ? doc.locale === locale.code : false);
729
+ const permissionsToCheck = currentLocaleDoc ? canRead : canCreate;
730
+ return {
731
+ disabled: !permissionsToCheck.includes(locale.code),
732
+ value: locale.code,
733
+ label: /*#__PURE__*/ jsx(LocaleOption, {
734
+ isDraftAndPublishEnabled: !!schema?.options?.draftAndPublish,
735
+ locale: locale,
736
+ status: currentLocaleDoc?.status,
737
+ entryExists: entryWithLocaleExists
738
+ }),
739
+ startIcon: !entryWithLocaleExists ? /*#__PURE__*/ jsx(Plus, {}) : null
740
+ };
741
+ }),
742
+ customizeContent: ()=>currentLocale?.name,
743
+ onSelect: handleSelect,
744
+ value: currentLocale
745
+ };
746
+ };
747
+ const getDocumentStatus = (document, meta)=>{
748
+ const docStatus = document?.status;
749
+ const statuses = meta?.availableStatus ?? [];
750
+ /**
751
+ * Creating an entry
752
+ */ if (!docStatus) {
753
+ return 'draft';
754
+ }
755
+ /**
756
+ * We're viewing a draft, but the document could have a published version
757
+ */ if (docStatus === 'draft' && statuses.find((doc)=>doc.publishedAt !== null)) {
758
+ return 'published';
759
+ }
760
+ return docStatus;
761
+ };
762
+ /* -------------------------------------------------------------------------------------------------
763
+ * FillFromAnotherLocaleAction
764
+ * -----------------------------------------------------------------------------------------------*/ const FillFromAnotherLocaleAction = ({ documentId, meta, model, collectionType })=>{
765
+ const { formatMessage } = useIntl();
766
+ const [{ query }] = useQueryParams();
767
+ const { hasI18n } = useI18n();
768
+ const currentDesiredLocale = query.plugins?.i18n?.locale;
769
+ const [localeSelected, setLocaleSelected] = React.useState(null);
770
+ const setValues = useForm('FillFromAnotherLocale', (state)=>state.setValues);
771
+ const { getDocument } = unstable_useDocumentActions();
772
+ const { schema, components } = unstable_useDocument({
773
+ model,
774
+ documentId,
775
+ collectionType,
776
+ params: {
777
+ locale: currentDesiredLocale
778
+ }
779
+ });
780
+ const { data: locales = [] } = useGetLocalesQuery();
781
+ const availableLocales = Array.isArray(locales) ? locales.filter((locale)=>meta?.availableLocales.some((l)=>l.locale === locale.code)) : [];
782
+ const fillFromLocale = (onClose)=>async ()=>{
783
+ const response = await getDocument({
784
+ collectionType,
785
+ model,
786
+ documentId,
787
+ params: {
788
+ locale: localeSelected
789
+ }
790
+ });
791
+ if (!response || !schema) {
792
+ return;
793
+ }
794
+ const { data } = response;
795
+ const cleanedData = cleanData(data, schema, components);
796
+ setValues(cleanedData);
797
+ onClose();
798
+ };
799
+ if (!hasI18n) {
800
+ return null;
801
+ }
802
+ return {
803
+ type: 'icon',
804
+ icon: /*#__PURE__*/ jsx(Earth, {}),
805
+ disabled: availableLocales.length === 0,
806
+ label: formatMessage({
807
+ id: getTranslation('CMEditViewCopyLocale.copy-text'),
808
+ defaultMessage: 'Fill in from another locale'
809
+ }),
810
+ dialog: {
811
+ type: 'dialog',
812
+ title: formatMessage({
813
+ id: getTranslation('CMEditViewCopyLocale.dialog.title'),
814
+ defaultMessage: 'Confirmation'
815
+ }),
816
+ content: ({ onClose })=>/*#__PURE__*/ jsxs(Fragment, {
817
+ children: [
818
+ /*#__PURE__*/ jsx(Dialog.Body, {
819
+ children: /*#__PURE__*/ jsxs(Flex, {
820
+ direction: "column",
821
+ gap: 3,
822
+ children: [
823
+ /*#__PURE__*/ jsx(WarningCircle, {
824
+ width: "24px",
825
+ height: "24px",
826
+ fill: "danger600"
827
+ }),
828
+ /*#__PURE__*/ jsx(Typography, {
829
+ textAlign: "center",
830
+ children: formatMessage({
831
+ id: getTranslation('CMEditViewCopyLocale.dialog.body'),
832
+ defaultMessage: 'Your current content will be erased and filled by the content of the selected locale:'
833
+ })
834
+ }),
835
+ /*#__PURE__*/ jsxs(Field.Root, {
836
+ width: "100%",
837
+ children: [
838
+ /*#__PURE__*/ jsx(Field.Label, {
839
+ children: formatMessage({
840
+ id: getTranslation('CMEditViewCopyLocale.dialog.field.label'),
841
+ defaultMessage: 'Locale'
842
+ })
843
+ }),
844
+ /*#__PURE__*/ jsx(SingleSelect, {
845
+ value: localeSelected,
846
+ placeholder: formatMessage({
847
+ id: getTranslation('CMEditViewCopyLocale.dialog.field.placeholder'),
848
+ defaultMessage: 'Select one locale...'
849
+ }),
850
+ // @ts-expect-error – the DS will handle numbers, but we're not allowing the API.
851
+ onChange: (value)=>setLocaleSelected(value),
852
+ children: availableLocales.map((locale)=>/*#__PURE__*/ jsx(SingleSelectOption, {
853
+ value: locale.code,
854
+ children: locale.name
855
+ }, locale.code))
856
+ })
857
+ ]
858
+ })
859
+ ]
860
+ })
861
+ }),
862
+ /*#__PURE__*/ jsx(Dialog.Footer, {
863
+ children: /*#__PURE__*/ jsxs(Flex, {
864
+ gap: 2,
865
+ width: "100%",
866
+ children: [
867
+ /*#__PURE__*/ jsx(Button, {
868
+ flex: "auto",
869
+ variant: "tertiary",
870
+ onClick: onClose,
871
+ children: formatMessage({
872
+ id: getTranslation('CMEditViewCopyLocale.cancel-text'),
873
+ defaultMessage: 'No, cancel'
874
+ })
875
+ }),
876
+ /*#__PURE__*/ jsx(Button, {
877
+ flex: "auto",
878
+ variant: "success",
879
+ onClick: fillFromLocale(onClose),
880
+ children: formatMessage({
881
+ id: getTranslation('CMEditViewCopyLocale.submit-text'),
882
+ defaultMessage: 'Yes, fill in'
883
+ })
884
+ })
885
+ ]
886
+ })
887
+ })
888
+ ]
889
+ })
890
+ }
891
+ };
892
+ };
893
+ /* -------------------------------------------------------------------------------------------------
894
+ * DeleteLocaleAction
895
+ * -----------------------------------------------------------------------------------------------*/ const DeleteLocaleAction = ({ document, documentId, model, collectionType })=>{
896
+ const { formatMessage } = useIntl();
897
+ const navigate = useNavigate();
898
+ const { toggleNotification } = useNotification();
899
+ const { delete: deleteAction, isLoading } = unstable_useDocumentActions();
900
+ const { hasI18n, canDelete } = useI18n();
901
+ // Get the current locale object, using the URL instead of document so it works while creating
902
+ const [{ query }] = useQueryParams();
903
+ const { data: locales = [] } = useGetLocalesQuery();
904
+ const currentDesiredLocale = query.plugins?.i18n?.locale;
905
+ const locale = !('error' in locales) && locales.find((loc)=>loc.code === currentDesiredLocale);
906
+ if (!hasI18n) {
907
+ return null;
908
+ }
909
+ return {
910
+ disabled: document?.locale && !canDelete.includes(document.locale) || !document || !document.id,
911
+ position: [
912
+ 'header',
913
+ 'table-row'
914
+ ],
915
+ label: formatMessage({
916
+ id: getTranslation('actions.delete.label'),
917
+ defaultMessage: 'Delete entry ({locale})'
918
+ }, {
919
+ locale: locale && locale.name
920
+ }),
921
+ icon: /*#__PURE__*/ jsx(StyledTrash, {}),
922
+ variant: 'danger',
923
+ dialog: {
924
+ type: 'dialog',
925
+ title: formatMessage({
926
+ id: getTranslation('actions.delete.dialog.title'),
927
+ defaultMessage: 'Confirmation'
928
+ }),
929
+ content: /*#__PURE__*/ jsxs(Flex, {
930
+ direction: "column",
931
+ gap: 2,
932
+ children: [
933
+ /*#__PURE__*/ jsx(WarningCircle, {
934
+ width: "24px",
935
+ height: "24px",
936
+ fill: "danger600"
937
+ }),
938
+ /*#__PURE__*/ jsx(Typography, {
939
+ tag: "p",
940
+ variant: "omega",
941
+ textAlign: "center",
942
+ children: formatMessage({
943
+ id: getTranslation('actions.delete.dialog.body'),
944
+ defaultMessage: 'Are you sure?'
945
+ })
946
+ })
947
+ ]
948
+ }),
949
+ loading: isLoading,
950
+ onConfirm: async ()=>{
951
+ const unableToDelete = // We are unable to delete a collection type without a document ID
952
+ // & unable to delete generally if there is no document locale
953
+ collectionType !== 'single-types' && !documentId || !document?.locale;
954
+ if (unableToDelete) {
955
+ console.error("You're trying to delete a document without an id or locale, this is likely a bug with Strapi. Please open an issue.");
956
+ toggleNotification({
957
+ message: formatMessage({
958
+ id: getTranslation('actions.delete.error'),
959
+ defaultMessage: 'An error occurred while trying to delete the document locale.'
960
+ }),
961
+ type: 'danger'
962
+ });
963
+ return;
964
+ }
965
+ const res = await deleteAction({
966
+ documentId,
967
+ model,
968
+ collectionType,
969
+ params: {
970
+ locale: document.locale
971
+ }
972
+ });
973
+ if (!('error' in res)) {
974
+ navigate({
975
+ pathname: `../${collectionType}/${model}`
976
+ }, {
977
+ replace: true
978
+ });
979
+ }
980
+ }
981
+ }
982
+ };
983
+ };
984
+ /* -------------------------------------------------------------------------------------------------
985
+ * BulkLocaleAction
986
+ *
987
+ * This component is used to handle bulk publish and unpublish actions on locales.
988
+ * -----------------------------------------------------------------------------------------------*/ const BulkLocaleAction = ({ document, documentId, model, collectionType, action })=>{
989
+ const locale = document?.locale ?? null;
990
+ const [{ query }] = useQueryParams();
991
+ const params = React.useMemo(()=>buildValidParams(query), [
992
+ query
993
+ ]);
994
+ const isOnPublishedTab = query.status === 'published';
995
+ const { formatMessage } = useIntl();
996
+ const { hasI18n, canPublish } = useI18n();
997
+ const { toggleNotification } = useNotification();
998
+ const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();
999
+ const [selectedRows, setSelectedRows] = React.useState([]);
1000
+ const [isDraftRelationConfirmationOpen, setIsDraftRelationConfirmationOpen] = React.useState(false);
1001
+ const { publishMany: publishManyAction, unpublishMany: unpublishManyAction } = unstable_useDocumentActions();
1002
+ const { schema, validate } = unstable_useDocument({
1003
+ model,
1004
+ collectionType,
1005
+ documentId,
1006
+ params: {
1007
+ locale
1008
+ }
1009
+ }, {
1010
+ // No need to fetch the document, the data is already available in the `document` prop
1011
+ skip: true
1012
+ });
1013
+ const { data: localesMetadata = [] } = useGetLocalesQuery(hasI18n ? undefined : skipToken);
1014
+ const headers = [
1015
+ {
1016
+ label: formatMessage({
1017
+ id: 'global.name',
1018
+ defaultMessage: 'Name'
1019
+ }),
1020
+ name: 'name'
1021
+ },
1022
+ {
1023
+ label: formatMessage({
1024
+ id: getTranslation('CMEditViewBulkLocale.status'),
1025
+ defaultMessage: 'Status'
1026
+ }),
1027
+ name: 'status'
1028
+ },
1029
+ {
1030
+ label: formatMessage({
1031
+ id: getTranslation('CMEditViewBulkLocale.publication-status'),
1032
+ defaultMessage: 'Publication Status'
1033
+ }),
1034
+ name: 'publication-status'
1035
+ }
1036
+ ];
1037
+ // Extract the rows for the bulk locale publish modal and any validation
1038
+ // errors per locale
1039
+ const [rows, validationErrors] = React.useMemo(()=>{
1040
+ if (!document) {
1041
+ return [
1042
+ [],
1043
+ {}
1044
+ ];
1045
+ }
1046
+ const localizations = document.localizations ?? [];
1047
+ // Build the rows for the bulk locale publish modal by combining the current
1048
+ // document with all the available locales from the document meta
1049
+ const locales = localizations.map((doc)=>{
1050
+ const { locale, status } = doc;
1051
+ return {
1052
+ locale,
1053
+ status
1054
+ };
1055
+ });
1056
+ // Add the current document locale
1057
+ locales.unshift({
1058
+ locale: document.locale,
1059
+ status: document.status
1060
+ });
1061
+ // Build the validation errors for each locale.
1062
+ const allDocuments = [
1063
+ document,
1064
+ ...localizations
1065
+ ];
1066
+ const errors = allDocuments.reduce((errs, document)=>{
1067
+ if (!document) {
1068
+ return errs;
1069
+ }
1070
+ // Validate each locale entry via the useDocument validate function and store any errors in a dictionary
1071
+ const validation = validate(document);
1072
+ if (validation !== null) {
1073
+ errs[document.locale] = validation;
1074
+ }
1075
+ return errs;
1076
+ }, {});
1077
+ return [
1078
+ locales,
1079
+ errors
1080
+ ];
1081
+ }, [
1082
+ document,
1083
+ validate
1084
+ ]);
1085
+ const isBulkPublish = action === 'bulk-publish';
1086
+ const localesForAction = selectedRows.reduce((acc, selectedRow)=>{
1087
+ const isValidLocale = // Validation errors are irrelevant if we are trying to unpublish
1088
+ !isBulkPublish || !Object.keys(validationErrors).includes(selectedRow.locale);
1089
+ const shouldAddLocale = isBulkPublish ? selectedRow.status !== 'published' && isValidLocale : selectedRow.status !== 'draft' && isValidLocale;
1090
+ if (shouldAddLocale) {
1091
+ acc.push(selectedRow.locale);
1092
+ }
1093
+ return acc;
1094
+ }, []);
1095
+ // TODO skipping this for now as there is a bug with the draft relation count that will be worked on separately
1096
+ // see https://www.notion.so/strapi/Count-draft-relations-56901b492efb45ab90d42fe975b32bd8?pvs=4
1097
+ const enableDraftRelationsCount = false;
1098
+ const { data: draftRelationsCount = 0, isLoading: isDraftRelationsLoading, error: isDraftRelationsError } = useGetManyDraftRelationCountQuery({
1099
+ model,
1100
+ documentIds: [
1101
+ documentId
1102
+ ],
1103
+ locale: localesForAction
1104
+ }, {
1105
+ skip: !enableDraftRelationsCount
1106
+ });
1107
+ React.useEffect(()=>{
1108
+ if (isDraftRelationsError) {
1109
+ toggleNotification({
1110
+ type: 'danger',
1111
+ message: formatAPIError(isDraftRelationsError)
1112
+ });
1113
+ }
1114
+ }, [
1115
+ isDraftRelationsError,
1116
+ toggleNotification,
1117
+ formatAPIError
1118
+ ]);
1119
+ if (!schema?.options?.draftAndPublish) {
1120
+ return null;
1121
+ }
1122
+ if (!hasI18n) {
1123
+ return null;
1124
+ }
1125
+ if (!documentId) {
1126
+ return null;
1127
+ }
1128
+ // This document action can be enabled given that draft and publish and i18n are
1129
+ // enabled and we can publish the current locale.
1130
+ const publish = async ()=>{
1131
+ await publishManyAction({
1132
+ model,
1133
+ documentIds: [
1134
+ documentId
1135
+ ],
1136
+ params: {
1137
+ ...params,
1138
+ locale: localesForAction
1139
+ }
1140
+ });
1141
+ setSelectedRows([]);
1142
+ };
1143
+ const unpublish = async ()=>{
1144
+ await unpublishManyAction({
1145
+ model,
1146
+ documentIds: [
1147
+ documentId
1148
+ ],
1149
+ params: {
1150
+ ...params,
1151
+ locale: localesForAction
1152
+ }
1153
+ });
1154
+ setSelectedRows([]);
1155
+ };
1156
+ const handleAction = async ()=>{
1157
+ if (draftRelationsCount > 0) {
1158
+ setIsDraftRelationConfirmationOpen(true);
1159
+ } else if (isBulkPublish) {
1160
+ await publish();
1161
+ } else {
1162
+ await unpublish();
1163
+ }
1164
+ };
1165
+ if (isDraftRelationConfirmationOpen) {
1166
+ return {
1167
+ label: formatMessage({
1168
+ id: 'app.components.ConfirmDialog.title',
1169
+ defaultMessage: 'Confirmation'
1170
+ }),
1171
+ variant: 'danger',
1172
+ dialog: {
1173
+ onCancel: ()=>{
1174
+ setIsDraftRelationConfirmationOpen(false);
1175
+ },
1176
+ onConfirm: async ()=>{
1177
+ await publish();
1178
+ setIsDraftRelationConfirmationOpen(false);
1179
+ },
1180
+ type: 'dialog',
1181
+ title: formatMessage({
1182
+ id: getTranslation('actions.publish.dialog.title'),
1183
+ defaultMessage: 'Confirmation'
1184
+ }),
1185
+ content: /*#__PURE__*/ jsxs(Flex, {
1186
+ direction: "column",
1187
+ alignItems: "center",
1188
+ gap: 2,
1189
+ children: [
1190
+ /*#__PURE__*/ jsx(WarningCircle, {
1191
+ width: "2.4rem",
1192
+ height: "2.4rem",
1193
+ fill: "danger600"
1194
+ }),
1195
+ /*#__PURE__*/ jsx(Typography, {
1196
+ textAlign: "center",
1197
+ children: formatMessage({
1198
+ id: getTranslation('CMEditViewBulkLocale.draft-relation-warning'),
1199
+ defaultMessage: 'Some locales are related to draft entries. Publishing them could leave broken links in your app.'
1200
+ })
1201
+ }),
1202
+ /*#__PURE__*/ jsx(Typography, {
1203
+ textAlign: "center",
1204
+ children: formatMessage({
1205
+ id: getTranslation('CMEditViewBulkLocale.continue-confirmation'),
1206
+ defaultMessage: 'Are you sure you want to continue?'
1207
+ })
1208
+ })
1209
+ ]
1210
+ })
1211
+ }
1212
+ };
1213
+ }
1214
+ const hasPermission = selectedRows.map(({ locale })=>locale).every((locale)=>canPublish.includes(locale));
1215
+ return {
1216
+ label: formatMessage({
1217
+ id: getTranslation(`CMEditViewBulkLocale.${isBulkPublish ? 'publish' : 'unpublish'}-title`),
1218
+ defaultMessage: `${isBulkPublish ? 'Publish' : 'Unpublish'} Multiple Locales`
1219
+ }),
1220
+ variant: isBulkPublish ? 'secondary' : 'danger',
1221
+ icon: isBulkPublish ? /*#__PURE__*/ jsx(ListPlus, {}) : /*#__PURE__*/ jsx(Cross, {}),
1222
+ disabled: isOnPublishedTab || canPublish.length === 0,
1223
+ position: [
1224
+ 'panel'
1225
+ ],
1226
+ dialog: {
1227
+ type: 'modal',
1228
+ title: formatMessage({
1229
+ id: getTranslation(`CMEditViewBulkLocale.${isBulkPublish ? 'publish' : 'unpublish'}-title`),
1230
+ defaultMessage: `${isBulkPublish ? 'Publish' : 'Unpublish'} Multiple Locales`
1231
+ }),
1232
+ content: ()=>{
1233
+ return /*#__PURE__*/ jsx(Table.Root, {
1234
+ headers: headers,
1235
+ rows: rows.map((row)=>({
1236
+ ...row,
1237
+ id: row.locale
1238
+ })),
1239
+ selectedRows: selectedRows,
1240
+ onSelectedRowsChange: (tableSelectedRows)=>setSelectedRows(tableSelectedRows),
1241
+ children: /*#__PURE__*/ jsx(BulkLocaleActionModal, {
1242
+ validationErrors: validationErrors,
1243
+ headers: headers,
1244
+ rows: rows,
1245
+ localesMetadata: localesMetadata,
1246
+ action: action ?? 'bulk-publish'
1247
+ })
1248
+ });
1249
+ },
1250
+ footer: ()=>/*#__PURE__*/ jsx(Modal.Footer, {
1251
+ justifyContent: "flex-end",
1252
+ children: /*#__PURE__*/ jsx(Button, {
1253
+ loading: isDraftRelationsLoading,
1254
+ disabled: !hasPermission || localesForAction.length === 0,
1255
+ variant: "default",
1256
+ onClick: handleAction,
1257
+ children: formatMessage({
1258
+ id: isBulkPublish ? 'app.utils.publish' : 'app.utils.unpublish',
1259
+ defaultMessage: isBulkPublish ? 'Publish' : 'Unpublish'
1260
+ })
1261
+ })
1262
+ })
1263
+ }
1264
+ };
1265
+ };
1266
+ /* -------------------------------------------------------------------------------------------------
1267
+ * BulkLocalePublishAction
1268
+ * -----------------------------------------------------------------------------------------------*/ const BulkLocalePublishAction = (props)=>{
1269
+ return BulkLocaleAction({
1270
+ action: 'bulk-publish',
1271
+ ...props
1272
+ });
1273
+ };
1274
+ /* -------------------------------------------------------------------------------------------------
1275
+ * BulkLocaleUnpublishAction
1276
+ * -----------------------------------------------------------------------------------------------*/ const BulkLocaleUnpublishAction = (props)=>{
1277
+ return BulkLocaleAction({
1278
+ action: 'bulk-unpublish',
1279
+ ...props
1280
+ });
1281
+ };
1282
+ /**
1283
+ * Because the icon system is completely broken, we have to do
1284
+ * this to remove the fill from the cog.
1285
+ */ const StyledTrash = styled(Trash)`
1286
+ path {
1287
+ fill: currentColor;
1288
+ }
1289
+ `;
1290
+
1291
+ const Emphasis = (chunks)=>{
1292
+ return /*#__PURE__*/ jsx(Typography, {
1293
+ fontWeight: "semiBold",
1294
+ textColor: "danger500",
1295
+ children: chunks
1296
+ });
1297
+ };
1298
+ const DeleteModalAdditionalInfo = ()=>{
1299
+ const { hasI18n } = useI18n();
1300
+ const { formatMessage } = useIntl();
1301
+ if (!hasI18n) {
1302
+ return null;
1303
+ }
1304
+ return /*#__PURE__*/ jsx(Typography, {
1305
+ textColor: "danger500",
1306
+ children: formatMessage({
1307
+ id: getTranslation('Settings.list.actions.deleteAdditionalInfos'),
1308
+ defaultMessage: 'This will delete the active locale versions <em>(from Internationalization)</em>'
1309
+ }, {
1310
+ em: Emphasis
1311
+ })
1312
+ });
1313
+ };
1314
+ const PublishModalAdditionalInfo = ()=>{
1315
+ const { hasI18n } = useI18n();
1316
+ const { formatMessage } = useIntl();
1317
+ if (!hasI18n) {
1318
+ return null;
1319
+ }
1320
+ return /*#__PURE__*/ jsx(Typography, {
1321
+ textColor: "danger500",
1322
+ children: formatMessage({
1323
+ id: getTranslation('Settings.list.actions.publishAdditionalInfos'),
1324
+ defaultMessage: 'This will publish the active locale versions <em>(from Internationalization)</em>'
1325
+ }, {
1326
+ em: Emphasis
1327
+ })
1328
+ });
1329
+ };
1330
+ const UnpublishModalAdditionalInfo = ()=>{
1331
+ const { hasI18n } = useI18n();
1332
+ const { formatMessage } = useIntl();
1333
+ if (!hasI18n) {
1334
+ return null;
1335
+ }
1336
+ return /*#__PURE__*/ jsx(Typography, {
1337
+ textColor: "danger500",
1338
+ children: formatMessage({
1339
+ id: getTranslation('Settings.list.actions.unpublishAdditionalInfos'),
1340
+ defaultMessage: 'This will unpublish the active locale versions <em>(from Internationalization)</em>'
1341
+ }, {
1342
+ em: Emphasis
1343
+ })
1344
+ });
1345
+ };
1346
+
1347
+ const LocalePicker = ()=>{
1348
+ const { formatMessage } = useIntl();
1349
+ const [{ query }, setQuery] = useQueryParams();
1350
+ const { hasI18n, canRead, canCreate } = useI18n();
1351
+ const { data: locales = [] } = useGetLocalesQuery(undefined, {
1352
+ skip: !hasI18n
1353
+ });
1354
+ const handleChange = React.useCallback((code, replace = false)=>{
1355
+ setQuery({
1356
+ page: 1,
1357
+ plugins: {
1358
+ ...query.plugins,
1359
+ i18n: {
1360
+ locale: code
1361
+ }
1362
+ }
1363
+ }, 'push', replace);
1364
+ }, [
1365
+ query.plugins,
1366
+ setQuery
1367
+ ]);
1368
+ React.useEffect(()=>{
1369
+ if (!Array.isArray(locales) || !hasI18n) {
1370
+ return;
1371
+ }
1372
+ /**
1373
+ * Handle the case where the current locale query param doesn't exist
1374
+ * in the list of available locales, so we redirect to the default locale.
1375
+ */ const currentDesiredLocale = query.plugins?.i18n?.locale;
1376
+ const doesLocaleExist = locales.find((loc)=>loc.code === currentDesiredLocale);
1377
+ const defaultLocale = locales.find((locale)=>locale.isDefault);
1378
+ if (!doesLocaleExist && defaultLocale?.code) {
1379
+ handleChange(defaultLocale.code, true);
1380
+ }
1381
+ }, [
1382
+ hasI18n,
1383
+ handleChange,
1384
+ locales,
1385
+ query.plugins?.i18n?.locale
1386
+ ]);
1387
+ if (!hasI18n || !Array.isArray(locales) || locales.length === 0) {
1388
+ return null;
1389
+ }
1390
+ const displayedLocales = locales.filter((locale)=>{
1391
+ /**
1392
+ * If you can create or read we allow you to see the locale exists
1393
+ * this is because in the ListView, you may be able to create a new entry
1394
+ * in a locale you can't read.
1395
+ */ return canCreate.includes(locale.code) || canRead.includes(locale.code);
1396
+ });
1397
+ return /*#__PURE__*/ jsx(SingleSelect, {
1398
+ size: "S",
1399
+ "aria-label": formatMessage({
1400
+ id: getTranslation('actions.select-locale'),
1401
+ defaultMessage: 'Select locale'
1402
+ }),
1403
+ value: query.plugins?.i18n?.locale || locales.find((locale)=>locale.isDefault)?.code,
1404
+ // @ts-expect-error – This can be removed in V2 of the DS.
1405
+ onChange: handleChange,
1406
+ children: displayedLocales.map((locale)=>/*#__PURE__*/ jsx(SingleSelectOption, {
1407
+ value: locale.code,
1408
+ children: locale.name
1409
+ }, locale.id))
1410
+ });
1411
+ };
1412
+
1413
+ const PERMISSIONS = {
1414
+ accessMain: [
1415
+ {
1416
+ action: 'plugin::i18n.locale.read',
1417
+ subject: null
1418
+ }
1419
+ ],
1420
+ create: [
1421
+ {
1422
+ action: 'plugin::i18n.locale.create',
1423
+ subject: null
1424
+ }
1425
+ ],
1426
+ delete: [
1427
+ {
1428
+ action: 'plugin::i18n.locale.delete',
1429
+ subject: null
1430
+ }
1431
+ ],
1432
+ update: [
1433
+ {
1434
+ action: 'plugin::i18n.locale.update',
1435
+ subject: null
1436
+ }
1437
+ ],
1438
+ read: [
1439
+ {
1440
+ action: 'plugin::i18n.locale.read',
1441
+ subject: null
1442
+ }
1443
+ ]
1444
+ };
1445
+
1446
+ const mutateEditViewHook = ({ layout })=>{
1447
+ // If i18n isn't explicitly enabled on the content type, then no field can be localized
1448
+ if (!('i18n' in layout.options) || typeof layout.options.i18n === 'object' && layout.options.i18n !== null && 'localized' in layout.options.i18n && !layout.options.i18n.localized) {
1449
+ return {
1450
+ layout
1451
+ };
1452
+ }
1453
+ const components = Object.entries(layout.components).reduce((acc, [key, componentLayout])=>{
1454
+ return {
1455
+ ...acc,
1456
+ [key]: {
1457
+ ...componentLayout,
1458
+ layout: componentLayout.layout.map((row)=>row.map(addLabelActionToField))
1459
+ }
1460
+ };
1461
+ }, {});
1462
+ return {
1463
+ layout: {
1464
+ ...layout,
1465
+ components,
1466
+ layout: layout.layout.map((panel)=>panel.map((row)=>row.map(addLabelActionToField)))
1467
+ }
1468
+ };
1469
+ };
1470
+ const addLabelActionToField = (field)=>{
1471
+ const isFieldLocalized = doesFieldHaveI18nPluginOpt(field.attribute.pluginOptions) ? field.attribute.pluginOptions.i18n.localized : true;
1472
+ const labelActionProps = {
1473
+ title: {
1474
+ id: isFieldLocalized ? getTranslation('Field.localized') : getTranslation('Field.not-localized'),
1475
+ defaultMessage: isFieldLocalized ? 'This value is unique for the selected locale' : 'This value is the same across all locales'
1476
+ },
1477
+ icon: isFieldLocalized ? /*#__PURE__*/ jsx(Earth, {}) : null
1478
+ };
1479
+ return {
1480
+ ...field,
1481
+ labelAction: isFieldLocalized ? /*#__PURE__*/ jsx(LabelAction, {
1482
+ ...labelActionProps
1483
+ }) : null
1484
+ };
1485
+ };
1486
+ const doesFieldHaveI18nPluginOpt = (pluginOpts)=>{
1487
+ if (!pluginOpts) {
1488
+ return false;
1489
+ }
1490
+ return 'i18n' in pluginOpts && typeof pluginOpts.i18n === 'object' && pluginOpts.i18n !== null && 'localized' in pluginOpts.i18n;
1491
+ };
1492
+ const LabelAction = ({ title, icon })=>{
1493
+ const { formatMessage } = useIntl();
1494
+ return /*#__PURE__*/ jsxs(Span, {
1495
+ tag: "span",
1496
+ children: [
1497
+ /*#__PURE__*/ jsx(VisuallyHidden, {
1498
+ tag: "span",
1499
+ children: formatMessage(title)
1500
+ }),
1501
+ /*#__PURE__*/ React.cloneElement(icon, {
1502
+ 'aria-hidden': true,
1503
+ focusable: false
1504
+ })
1505
+ ]
1506
+ });
1507
+ };
1508
+ const Span = styled(Flex)`
1509
+ svg {
1510
+ width: 12px;
1511
+ height: 12px;
1512
+
1513
+ fill: ${({ theme })=>theme.colors.neutral500};
1514
+
1515
+ path {
1516
+ fill: ${({ theme })=>theme.colors.neutral500};
1517
+ }
1518
+ }
1519
+ `;
1520
+
1521
+ const LocaleListCell = ({ locale: currentLocale, localizations })=>{
1522
+ const { locale: language } = useIntl();
1523
+ const { data: locales = [] } = useGetLocalesQuery();
1524
+ const formatter = useCollator(language, {
1525
+ sensitivity: 'base'
1526
+ });
1527
+ if (!Array.isArray(locales) || !localizations) {
1528
+ return null;
1529
+ }
1530
+ const availableLocales = localizations.map((loc)=>loc.locale);
1531
+ const localesForDocument = locales.reduce((acc, locale)=>{
1532
+ const createdLocale = [
1533
+ currentLocale,
1534
+ ...availableLocales
1535
+ ].find((loc)=>{
1536
+ return loc === locale.code;
1537
+ });
1538
+ if (createdLocale) {
1539
+ acc.push(locale);
1540
+ }
1541
+ return acc;
1542
+ }, []).map((locale)=>{
1543
+ if (locale.isDefault) {
1544
+ return `${locale.name} (default)`;
1545
+ }
1546
+ return locale.name;
1547
+ }).toSorted((a, b)=>formatter.compare(a, b));
1548
+ return /*#__PURE__*/ jsxs(Popover.Root, {
1549
+ children: [
1550
+ /*#__PURE__*/ jsx(Popover.Trigger, {
1551
+ children: /*#__PURE__*/ jsx(Button, {
1552
+ variant: "ghost",
1553
+ type: "button",
1554
+ onClick: (e)=>e.stopPropagation(),
1555
+ children: /*#__PURE__*/ jsxs(Flex, {
1556
+ minWidth: "100%",
1557
+ alignItems: "center",
1558
+ justifyContent: "center",
1559
+ fontWeight: "regular",
1560
+ children: [
1561
+ /*#__PURE__*/ jsx(Typography, {
1562
+ textColor: "neutral800",
1563
+ ellipsis: true,
1564
+ marginRight: 2,
1565
+ children: localesForDocument.join(', ')
1566
+ }),
1567
+ /*#__PURE__*/ jsx(Flex, {
1568
+ children: /*#__PURE__*/ jsx(CaretDown, {
1569
+ width: "1.2rem",
1570
+ height: "1.2rem"
1571
+ })
1572
+ })
1573
+ ]
1574
+ })
1575
+ })
1576
+ }),
1577
+ /*#__PURE__*/ jsx(Popover.Content, {
1578
+ sideOffset: 16,
1579
+ children: /*#__PURE__*/ jsx("ul", {
1580
+ children: localesForDocument.map((name)=>/*#__PURE__*/ jsx(Box, {
1581
+ padding: 3,
1582
+ tag: "li",
1583
+ children: /*#__PURE__*/ jsx(Typography, {
1584
+ children: name
1585
+ })
1586
+ }, name))
1587
+ })
1588
+ })
1589
+ ]
1590
+ });
1591
+ };
1592
+
1593
+ const addColumnToTableHook = ({ displayedHeaders, layout })=>{
1594
+ const { options } = layout;
1595
+ const isFieldLocalized = doesPluginOptionsHaveI18nLocalized(options) ? options.i18n.localized : false;
1596
+ if (!isFieldLocalized) {
1597
+ return {
1598
+ displayedHeaders,
1599
+ layout
1600
+ };
1601
+ }
1602
+ return {
1603
+ displayedHeaders: [
1604
+ ...displayedHeaders,
1605
+ {
1606
+ attribute: {
1607
+ type: 'string'
1608
+ },
1609
+ label: {
1610
+ id: getTranslation('list-view.table.header.label'),
1611
+ defaultMessage: 'Available in'
1612
+ },
1613
+ searchable: false,
1614
+ sortable: false,
1615
+ name: 'locales',
1616
+ // @ts-expect-error – ID is seen as number | string; this will change when we move the type over.
1617
+ cellFormatter: (props, _header, meta)=>/*#__PURE__*/ jsx(LocaleListCell, {
1618
+ ...props,
1619
+ ...meta
1620
+ })
1621
+ }
1622
+ ],
1623
+ layout
1624
+ };
1625
+ };
1626
+
1627
+ const addLocaleToReleasesHook = ({ displayedHeaders = [] })=>{
1628
+ return {
1629
+ displayedHeaders: [
1630
+ ...displayedHeaders,
1631
+ {
1632
+ label: {
1633
+ id: 'content-releases.page.ReleaseDetails.table.header.label.locale',
1634
+ defaultMessage: 'locale'
1635
+ },
1636
+ name: 'locale'
1637
+ }
1638
+ ],
1639
+ hasI18nEnabled: true
1640
+ };
1641
+ };
1642
+
1643
+ const extendCTBAttributeInitialDataMiddleware = ()=>{
1644
+ return ({ getState })=>(next)=>(action)=>{
1645
+ const enhanceAction = ()=>{
1646
+ // the block here is to catch the error when trying to access the state
1647
+ // of the ctb when the plugin is not mounted
1648
+ try {
1649
+ const store = getState();
1650
+ const hasi18nEnabled = get(store, [
1651
+ 'content-type-builder_dataManagerProvider',
1652
+ 'modifiedData',
1653
+ 'contentType',
1654
+ 'schema',
1655
+ 'pluginOptions',
1656
+ 'i18n',
1657
+ 'localized'
1658
+ ], false);
1659
+ if (hasi18nEnabled) {
1660
+ const pluginOptions = action.options ? {
1661
+ ...action.options.pluginOptions,
1662
+ i18n: {
1663
+ localized: true
1664
+ }
1665
+ } : {
1666
+ i18n: {
1667
+ localized: true
1668
+ }
1669
+ };
1670
+ return next({
1671
+ ...action,
1672
+ options: {
1673
+ pluginOptions
1674
+ }
1675
+ });
1676
+ }
1677
+ return next(action);
1678
+ } catch (err) {
1679
+ return next(action);
1680
+ }
1681
+ };
1682
+ if (action.type === 'ContentTypeBuilder/FormModal/SET_ATTRIBUTE_DATA_SCHEMA' && action.forTarget === 'contentType' && ![
1683
+ 'relation',
1684
+ 'component'
1685
+ ].includes(action.attributeType) && !action.isEditing) {
1686
+ return enhanceAction();
1687
+ }
1688
+ if (action.type === 'ContentTypeBuilder/FormModal/SET_CUSTOM_FIELD_DATA_SCHEMA' && action.forTarget === 'contentType' && !action.isEditing) {
1689
+ return enhanceAction();
1690
+ }
1691
+ if ((action.type === 'ContentTypeBuilder/FormModal/RESET_PROPS_AND_SET_FORM_FOR_ADDING_AN_EXISTING_COMPO' || action.type === 'ContentTypeBuilder/FormModal/RESET_PROPS_AND_SAVE_CURRENT_DATA') && action.forTarget === 'contentType') {
1692
+ return enhanceAction();
1693
+ }
1694
+ return next(action);
1695
+ };
1696
+ };
1697
+
1698
+ const extendCTBInitialDataMiddleware = ()=>{
1699
+ return ()=>(next)=>(action)=>{
1700
+ if (action.type === 'ContentTypeBuilder/FormModal/SET_DATA_TO_EDIT' && action.modalType === 'contentType') {
1701
+ const i18n = {
1702
+ localized: false
1703
+ };
1704
+ const pluginOptions = action.data.pluginOptions ? {
1705
+ ...action.data.pluginOptions,
1706
+ i18n
1707
+ } : {
1708
+ i18n
1709
+ };
1710
+ const data = {
1711
+ ...action.data,
1712
+ pluginOptions
1713
+ };
1714
+ if (action.actionType === 'create') {
1715
+ return next({
1716
+ ...action,
1717
+ data
1718
+ });
1719
+ }
1720
+ // Override the action if the pluginOption config does not contain i18n
1721
+ // In this case we need to set the proper initialData shape
1722
+ if (!action.data.pluginOptions?.i18n?.localized) {
1723
+ return next({
1724
+ ...action,
1725
+ data
1726
+ });
1727
+ }
1728
+ }
1729
+ // action is not the one we want to override
1730
+ return next(action);
1731
+ };
1732
+ };
1733
+
1734
+ const localeMiddleware = (ctx)=>(next)=>(permissions)=>{
1735
+ const match = matchPath('/content-manager/:collectionType/:model?/:id', ctx.pathname);
1736
+ if (!match) {
1737
+ return next(permissions);
1738
+ }
1739
+ const search = qs.parse(ctx.search);
1740
+ if (typeof search !== 'object') {
1741
+ return next(permissions);
1742
+ }
1743
+ if (!('plugins' in search && typeof search.plugins === 'object')) {
1744
+ return next(permissions);
1745
+ }
1746
+ if (!('i18n' in search.plugins && typeof search.plugins.i18n === 'object' && !Array.isArray(search.plugins.i18n))) {
1747
+ return next(permissions);
1748
+ }
1749
+ const { locale } = search.plugins.i18n;
1750
+ if (typeof locale !== 'string') {
1751
+ return next(permissions);
1752
+ }
1753
+ const revisedPermissions = permissions.filter((permission)=>!permission.properties?.locales || permission.properties.locales.includes(locale));
1754
+ return next(revisedPermissions);
1755
+ };
1756
+
1757
+ const prefixPluginTranslations = (trad, pluginId)=>{
1758
+ return Object.keys(trad).reduce((acc, current)=>{
1759
+ acc[`${pluginId}.${current}`] = trad[current];
1760
+ return acc;
1761
+ }, {});
1762
+ };
1763
+
1764
+ /* -------------------------------------------------------------------------------------------------
1765
+ * mutateCTBContentTypeSchema
1766
+ * -----------------------------------------------------------------------------------------------*/ const mutateCTBContentTypeSchema = (nextSchema, prevSchema)=>{
1767
+ // Don't perform mutations components
1768
+ if (!doesPluginOptionsHaveI18nLocalized(nextSchema.pluginOptions)) {
1769
+ return nextSchema;
1770
+ }
1771
+ const isNextSchemaLocalized = nextSchema.pluginOptions.i18n.localized;
1772
+ const isPrevSchemaLocalized = doesPluginOptionsHaveI18nLocalized(prevSchema?.schema?.pluginOptions) ? prevSchema?.schema?.pluginOptions.i18n.localized : false;
1773
+ // No need to perform modification on the schema, if the i18n feature was not changed
1774
+ // at the ct level
1775
+ if (isNextSchemaLocalized && isPrevSchemaLocalized) {
1776
+ return nextSchema;
1777
+ }
1778
+ if (isNextSchemaLocalized) {
1779
+ const attributes = addLocalisationToFields(nextSchema.attributes);
1780
+ return {
1781
+ ...nextSchema,
1782
+ attributes
1783
+ };
1784
+ }
1785
+ // Remove the i18n object from the pluginOptions
1786
+ if (!isNextSchemaLocalized) {
1787
+ const pluginOptions = omit(nextSchema.pluginOptions, 'i18n');
1788
+ const attributes = disableAttributesLocalisation(nextSchema.attributes);
1789
+ return {
1790
+ ...nextSchema,
1791
+ pluginOptions,
1792
+ attributes
1793
+ };
1794
+ }
1795
+ return nextSchema;
1796
+ };
1797
+ /* -------------------------------------------------------------------------------------------------
1798
+ * addLocalisationToFields
1799
+ * -----------------------------------------------------------------------------------------------*/ const addLocalisationToFields = (attributes)=>Object.keys(attributes).reduce((acc, current)=>{
1800
+ const currentAttribute = attributes[current];
1801
+ if (LOCALIZED_FIELDS.includes(currentAttribute.type)) {
1802
+ const i18n = {
1803
+ localized: true
1804
+ };
1805
+ const pluginOptions = currentAttribute.pluginOptions ? {
1806
+ ...currentAttribute.pluginOptions,
1807
+ i18n
1808
+ } : {
1809
+ i18n
1810
+ };
1811
+ acc[current] = {
1812
+ ...currentAttribute,
1813
+ pluginOptions
1814
+ };
1815
+ return acc;
1816
+ }
1817
+ acc[current] = currentAttribute;
1818
+ return acc;
1819
+ }, {});
1820
+ const disableAttributesLocalisation = (attributes)=>Object.keys(attributes).reduce((acc, current)=>{
1821
+ acc[current] = omit(attributes[current], 'pluginOptions.i18n');
1822
+ return acc;
1823
+ }, {});
1824
+
1825
+ function __variableDynamicImportRuntime1__(path) {
1826
+ switch (path) {
1827
+ case './translations/de.json': return import('./de-Cm8mYdaO.mjs');
1828
+ case './translations/dk.json': return import('./dk-BeUFOegB.mjs');
1829
+ case './translations/en.json': return import('./en-eWSaCeOb.mjs');
1830
+ case './translations/es.json': return import('./es-DqF_IdAc.mjs');
1831
+ case './translations/fr.json': return import('./fr-CyARbZ3c.mjs');
1832
+ case './translations/ko.json': return import('./ko-Ax4NSedM.mjs');
1833
+ case './translations/pl.json': return import('./pl-B-aqvMqL.mjs');
1834
+ case './translations/ru.json': return import('./ru-VkPjQ-Sk.mjs');
1835
+ case './translations/tr.json': return import('./tr-DcTR88c9.mjs');
1836
+ case './translations/zh-Hans.json': return import('./zh-Hans-L3wsRegj.mjs');
1837
+ case './translations/zh.json': return import('./zh-RZyMiPIs.mjs');
1838
+ default: return new Promise(function(resolve, reject) {
1839
+ (typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(
1840
+ reject.bind(null, new Error("Unknown variable dynamic import: " + path))
1841
+ );
1842
+ })
1843
+ }
1844
+ }
1845
+ // eslint-disable-next-line import/no-default-export
1846
+ var index = {
1847
+ register (app) {
1848
+ app.addMiddlewares([
1849
+ extendCTBAttributeInitialDataMiddleware,
1850
+ extendCTBInitialDataMiddleware
1851
+ ]);
1852
+ app.addMiddlewares([
1853
+ ()=>i18nApi.middleware
1854
+ ]);
1855
+ app.addReducers({
1856
+ [i18nApi.reducerPath]: i18nApi.reducer
1857
+ });
1858
+ app.addRBACMiddleware([
1859
+ localeMiddleware
1860
+ ]);
1861
+ app.registerPlugin({
1862
+ id: pluginId,
1863
+ name: pluginId
1864
+ });
1865
+ },
1866
+ bootstrap (app) {
1867
+ // // Hook that adds a column into the CM's LV table
1868
+ app.registerHook('Admin/CM/pages/ListView/inject-column-in-table', addColumnToTableHook);
1869
+ app.registerHook('Admin/CM/pages/EditView/mutate-edit-view-layout', mutateEditViewHook);
1870
+ // Hooks that checks if the locale is present in the release
1871
+ app.registerHook('ContentReleases/pages/ReleaseDetails/add-locale-in-releases', addLocaleToReleasesHook);
1872
+ // Add the settings link
1873
+ app.addSettingsLink('global', {
1874
+ intlLabel: {
1875
+ id: getTranslation('plugin.name'),
1876
+ defaultMessage: 'Internationalization'
1877
+ },
1878
+ id: 'internationalization',
1879
+ to: 'internationalization',
1880
+ Component: ()=>import('./SettingsPage-g9SsggAu.mjs').then((mod)=>({
1881
+ default: mod.ProtectedSettingsPage
1882
+ })),
1883
+ permissions: PERMISSIONS.accessMain
1884
+ });
1885
+ const contentManager = app.getPlugin('content-manager');
1886
+ contentManager.apis.addDocumentHeaderAction([
1887
+ LocalePickerAction,
1888
+ FillFromAnotherLocaleAction
1889
+ ]);
1890
+ contentManager.apis.addDocumentAction((actions)=>{
1891
+ const indexOfDeleteAction = actions.findIndex((action)=>action.type === 'delete');
1892
+ actions.splice(indexOfDeleteAction, 0, DeleteLocaleAction);
1893
+ return actions;
1894
+ });
1895
+ contentManager.apis.addDocumentAction((actions)=>{
1896
+ // When enabled the bulk locale publish action should be the first action
1897
+ // in 'More Document Actions' and therefore the third action in the array
1898
+ actions.splice(2, 0, BulkLocalePublishAction);
1899
+ actions.splice(5, 0, BulkLocaleUnpublishAction);
1900
+ return actions;
1901
+ });
1902
+ contentManager.injectComponent('listView', 'actions', {
1903
+ name: 'i18n-locale-filter',
1904
+ Component: LocalePicker
1905
+ });
1906
+ contentManager.injectComponent('listView', 'publishModalAdditionalInfos', {
1907
+ name: 'i18n-publish-bullets-in-modal',
1908
+ Component: PublishModalAdditionalInfo
1909
+ });
1910
+ contentManager.injectComponent('listView', 'unpublishModalAdditionalInfos', {
1911
+ name: 'i18n-unpublish-bullets-in-modal',
1912
+ Component: UnpublishModalAdditionalInfo
1913
+ });
1914
+ contentManager.injectComponent('listView', 'deleteModalAdditionalInfos', {
1915
+ name: 'i18n-delete-bullets-in-modal',
1916
+ Component: DeleteModalAdditionalInfo
1917
+ });
1918
+ const ctbPlugin = app.getPlugin('content-type-builder');
1919
+ if (ctbPlugin) {
1920
+ const ctbFormsAPI = ctbPlugin.apis.forms;
1921
+ ctbFormsAPI.addContentTypeSchemaMutation(mutateCTBContentTypeSchema);
1922
+ ctbFormsAPI.components.add({
1923
+ id: 'checkboxConfirmation',
1924
+ component: CheckboxConfirmation
1925
+ });
1926
+ ctbFormsAPI.extendContentType({
1927
+ validator: ()=>({
1928
+ i18n: yup.object().shape({
1929
+ localized: yup.bool()
1930
+ })
1931
+ }),
1932
+ form: {
1933
+ advanced () {
1934
+ return [
1935
+ {
1936
+ name: 'pluginOptions.i18n.localized',
1937
+ description: {
1938
+ id: getTranslation('plugin.schema.i18n.localized.description-content-type'),
1939
+ defaultMessage: 'Allows translating an entry into different languages'
1940
+ },
1941
+ type: 'checkboxConfirmation',
1942
+ intlLabel: {
1943
+ id: getTranslation('plugin.schema.i18n.localized.label-content-type'),
1944
+ defaultMessage: 'Localization'
1945
+ }
1946
+ }
1947
+ ];
1948
+ }
1949
+ }
1950
+ });
1951
+ ctbFormsAPI.extendFields(LOCALIZED_FIELDS, {
1952
+ form: {
1953
+ advanced ({ contentTypeSchema, forTarget, type, step }) {
1954
+ if (forTarget !== 'contentType') {
1955
+ return [];
1956
+ }
1957
+ const hasI18nEnabled = get(contentTypeSchema, [
1958
+ 'schema',
1959
+ 'pluginOptions',
1960
+ 'i18n',
1961
+ 'localized'
1962
+ ], false);
1963
+ if (!hasI18nEnabled) {
1964
+ return [];
1965
+ }
1966
+ if (type === 'component' && step === '1') {
1967
+ return [];
1968
+ }
1969
+ return [
1970
+ {
1971
+ name: 'pluginOptions.i18n.localized',
1972
+ description: {
1973
+ id: getTranslation('plugin.schema.i18n.localized.description-field'),
1974
+ defaultMessage: 'The field can have different values in each locale'
1975
+ },
1976
+ type: 'checkbox',
1977
+ intlLabel: {
1978
+ id: getTranslation('plugin.schema.i18n.localized.label-field'),
1979
+ defaultMessage: 'Enable localization for this field'
1980
+ }
1981
+ }
1982
+ ];
1983
+ }
1984
+ }
1985
+ });
1986
+ }
1987
+ },
1988
+ async registerTrads ({ locales }) {
1989
+ const importedTrads = await Promise.all(locales.map((locale)=>{
1990
+ return __variableDynamicImportRuntime1__(`./translations/${locale}.json`).then(({ default: data })=>{
1991
+ return {
1992
+ data: prefixPluginTranslations(data, pluginId),
1993
+ locale
1994
+ };
1995
+ }).catch(()=>{
1996
+ return {
1997
+ data: {},
1998
+ locale
1999
+ };
2000
+ });
2001
+ }));
2002
+ return Promise.resolve(importedTrads);
2003
+ }
2004
+ };
2005
+
2006
+ export { PERMISSIONS as P, useGetDefaultLocalesQuery as a, useDeleteLocaleMutation as b, useUpdateLocaleMutation as c, useGetLocalesQuery as d, getTranslation as g, index as i, useCreateLocaleMutation as u };
2007
+ //# sourceMappingURL=index-BWv_l535.mjs.map