@strapi/content-manager 5.11.1 → 5.12.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/admin/chunks/{ComponentConfigurationPage-BGBNQxFJ.js → ComponentConfigurationPage-CBvwLnAK.js} +5 -6
  2. package/dist/admin/chunks/{ComponentConfigurationPage-BGBNQxFJ.js.map → ComponentConfigurationPage-CBvwLnAK.js.map} +1 -1
  3. package/dist/admin/chunks/{ComponentConfigurationPage-DKtL-tec.mjs → ComponentConfigurationPage-w_ss7xEy.mjs} +5 -6
  4. package/dist/admin/chunks/{ComponentConfigurationPage-DKtL-tec.mjs.map → ComponentConfigurationPage-w_ss7xEy.mjs.map} +1 -1
  5. package/dist/admin/chunks/{EditConfigurationPage-yliOxLUv.js → EditConfigurationPage-CbAhYSyH.js} +5 -6
  6. package/dist/admin/chunks/{EditConfigurationPage-yliOxLUv.js.map → EditConfigurationPage-CbAhYSyH.js.map} +1 -1
  7. package/dist/admin/chunks/{EditConfigurationPage-KDwSFRyn.mjs → EditConfigurationPage-D1iHIzSR.mjs} +5 -6
  8. package/dist/admin/chunks/{EditConfigurationPage-KDwSFRyn.mjs.map → EditConfigurationPage-D1iHIzSR.mjs.map} +1 -1
  9. package/dist/admin/chunks/{EditViewPage-BAI2r49P.mjs → EditViewPage-BtunY0ZP.mjs} +102 -95
  10. package/dist/admin/chunks/EditViewPage-BtunY0ZP.mjs.map +1 -0
  11. package/dist/admin/chunks/{EditViewPage-DpvonssD.js → EditViewPage-Cf_TPJZd.js} +102 -95
  12. package/dist/admin/chunks/EditViewPage-Cf_TPJZd.js.map +1 -0
  13. package/dist/admin/chunks/{Form-BrzQyDxU.mjs → Form-DsvK3WTh.mjs} +3 -3
  14. package/dist/admin/chunks/{Form-BrzQyDxU.mjs.map → Form-DsvK3WTh.mjs.map} +1 -1
  15. package/dist/admin/chunks/{Form-XD_sf25E.js → Form-UMrizqJP.js} +5 -5
  16. package/dist/admin/chunks/{Form-XD_sf25E.js.map → Form-UMrizqJP.js.map} +1 -1
  17. package/dist/admin/chunks/{History-C-_o7tz8.js → History-Crvb_hzd.js} +17 -13
  18. package/dist/admin/chunks/History-Crvb_hzd.js.map +1 -0
  19. package/dist/admin/chunks/{History-DClLuGIg.mjs → History-DsRVSUF7.mjs} +16 -12
  20. package/dist/admin/chunks/History-DsRVSUF7.mjs.map +1 -0
  21. package/dist/admin/chunks/{Input-Bv-rqfYH.js → Input-C2r54bIL.js} +1327 -64
  22. package/dist/admin/chunks/Input-C2r54bIL.js.map +1 -0
  23. package/dist/admin/chunks/{Input-BMLRZBE3.mjs → Input-D6obstp0.mjs} +1315 -55
  24. package/dist/admin/chunks/Input-D6obstp0.mjs.map +1 -0
  25. package/dist/admin/chunks/{ListConfigurationPage-Do3UDres.mjs → ListConfigurationPage-DW-wAwmW.mjs} +4 -5
  26. package/dist/admin/chunks/{ListConfigurationPage-Do3UDres.mjs.map → ListConfigurationPage-DW-wAwmW.mjs.map} +1 -1
  27. package/dist/admin/chunks/{ListConfigurationPage-D66hgG4-.js → ListConfigurationPage-DlQ2pLyr.js} +6 -7
  28. package/dist/admin/chunks/{ListConfigurationPage-D66hgG4-.js.map → ListConfigurationPage-DlQ2pLyr.js.map} +1 -1
  29. package/dist/admin/chunks/{ListViewPage-Q0auz5lE.mjs → ListViewPage-DcUhPA9a.mjs} +3 -4
  30. package/dist/admin/chunks/{ListViewPage-Q0auz5lE.mjs.map → ListViewPage-DcUhPA9a.mjs.map} +1 -1
  31. package/dist/admin/chunks/{ListViewPage-DNvysJaJ.js → ListViewPage-nJJ227Fo.js} +7 -8
  32. package/dist/admin/chunks/{ListViewPage-DNvysJaJ.js.map → ListViewPage-nJJ227Fo.js.map} +1 -1
  33. package/dist/admin/chunks/{NoContentTypePage-C5qFFfgn.js → NoContentTypePage-Cxt-uFq7.js} +2 -2
  34. package/dist/admin/chunks/{NoContentTypePage-C5qFFfgn.js.map → NoContentTypePage-Cxt-uFq7.js.map} +1 -1
  35. package/dist/admin/chunks/{NoContentTypePage-B_oOeOQb.mjs → NoContentTypePage-DbRXR2cr.mjs} +2 -2
  36. package/dist/admin/chunks/{NoContentTypePage-B_oOeOQb.mjs.map → NoContentTypePage-DbRXR2cr.mjs.map} +1 -1
  37. package/dist/admin/chunks/{NoPermissionsPage-C9sDJXRu.js → NoPermissionsPage-BeMTv_SG.js} +2 -2
  38. package/dist/admin/chunks/{NoPermissionsPage-C9sDJXRu.js.map → NoPermissionsPage-BeMTv_SG.js.map} +1 -1
  39. package/dist/admin/chunks/{NoPermissionsPage-BAW7WY-M.mjs → NoPermissionsPage-RWPwNESA.mjs} +2 -2
  40. package/dist/admin/chunks/{NoPermissionsPage-BAW7WY-M.mjs.map → NoPermissionsPage-RWPwNESA.mjs.map} +1 -1
  41. package/dist/admin/chunks/{Preview-B6ThL2SA.js → Preview-CCjSV5Iu.js} +118 -200
  42. package/dist/admin/chunks/Preview-CCjSV5Iu.js.map +1 -0
  43. package/dist/admin/chunks/{Preview-05BZGpV2.mjs → Preview-aVLT3LM_.mjs} +121 -203
  44. package/dist/admin/chunks/Preview-aVLT3LM_.mjs.map +1 -0
  45. package/dist/admin/chunks/{en-CImiNxXE.mjs → en-C2zEwS3-.mjs} +4 -1
  46. package/dist/admin/chunks/{en-CImiNxXE.mjs.map → en-C2zEwS3-.mjs.map} +1 -1
  47. package/dist/admin/chunks/{en-CLf4SuMQ.js → en-G976DLsg.js} +4 -1
  48. package/dist/admin/chunks/{en-CLf4SuMQ.js.map → en-G976DLsg.js.map} +1 -1
  49. package/dist/admin/chunks/{index-SQ88CePz.js → index-BA_JLxKS.js} +171 -117
  50. package/dist/admin/chunks/index-BA_JLxKS.js.map +1 -0
  51. package/dist/admin/chunks/{index-CcJLBLNf.mjs → index-CIOT3ggy.mjs} +170 -119
  52. package/dist/admin/chunks/index-CIOT3ggy.mjs.map +1 -0
  53. package/dist/admin/chunks/{layout-xxDnIsHG.js → layout-C510xcd6.js} +86 -13
  54. package/dist/admin/chunks/layout-C510xcd6.js.map +1 -0
  55. package/dist/admin/chunks/{layout-4nCaNnTs.mjs → layout-DjT9cccU.mjs} +78 -5
  56. package/dist/admin/chunks/layout-DjT9cccU.mjs.map +1 -0
  57. package/dist/admin/chunks/{useDragAndDrop-gcqEJMnO.js → objects-BJTP843m.js} +73 -1
  58. package/dist/admin/chunks/objects-BJTP843m.js.map +1 -0
  59. package/dist/admin/chunks/{useDragAndDrop-HYwNDExe.mjs → objects-D2z-IJgu.mjs} +72 -2
  60. package/dist/admin/chunks/objects-D2z-IJgu.mjs.map +1 -0
  61. package/dist/admin/chunks/{relations-VlsO9KQZ.js → usePrev-BglKW7a4.js} +18 -2
  62. package/dist/admin/chunks/usePrev-BglKW7a4.js.map +1 -0
  63. package/dist/admin/chunks/{relations-D1R7vM_e.mjs → usePrev-DAWUYIPh.mjs} +18 -4
  64. package/dist/admin/chunks/usePrev-DAWUYIPh.mjs.map +1 -0
  65. package/dist/admin/index.js +1 -1
  66. package/dist/admin/index.mjs +1 -1
  67. package/dist/admin/src/features/DocumentContext.d.ts +53 -0
  68. package/dist/admin/src/features/DocumentRBAC.d.ts +3 -2
  69. package/dist/admin/src/pages/EditView/components/DocumentActions.d.ts +1 -1
  70. package/dist/admin/src/pages/EditView/components/FormInputs/Relations/RelationModal.d.ts +8 -0
  71. package/dist/admin/src/pages/EditView/components/FormInputs/{Relations.d.ts → Relations/Relations.d.ts} +9 -4
  72. package/dist/admin/src/pages/EditView/components/FormLayout.d.ts +8 -3
  73. package/dist/admin/src/pages/EditView/components/InputRenderer.d.ts +7 -4
  74. package/dist/admin/src/preview/components/PreviewHeader.d.ts +1 -2
  75. package/dist/admin/src/preview/pages/Preview.d.ts +0 -2
  76. package/package.json +5 -5
  77. package/dist/admin/chunks/EditViewPage-BAI2r49P.mjs.map +0 -1
  78. package/dist/admin/chunks/EditViewPage-DpvonssD.js.map +0 -1
  79. package/dist/admin/chunks/History-C-_o7tz8.js.map +0 -1
  80. package/dist/admin/chunks/History-DClLuGIg.mjs.map +0 -1
  81. package/dist/admin/chunks/Input-BMLRZBE3.mjs.map +0 -1
  82. package/dist/admin/chunks/Input-Bv-rqfYH.js.map +0 -1
  83. package/dist/admin/chunks/Preview-05BZGpV2.mjs.map +0 -1
  84. package/dist/admin/chunks/Preview-B6ThL2SA.js.map +0 -1
  85. package/dist/admin/chunks/Relations-CJ0GWuqq.js +0 -1318
  86. package/dist/admin/chunks/Relations-CJ0GWuqq.js.map +0 -1
  87. package/dist/admin/chunks/Relations-CiOfFNxW.mjs +0 -1291
  88. package/dist/admin/chunks/Relations-CiOfFNxW.mjs.map +0 -1
  89. package/dist/admin/chunks/index-CcJLBLNf.mjs.map +0 -1
  90. package/dist/admin/chunks/index-SQ88CePz.js.map +0 -1
  91. package/dist/admin/chunks/layout-4nCaNnTs.mjs.map +0 -1
  92. package/dist/admin/chunks/layout-xxDnIsHG.js.map +0 -1
  93. package/dist/admin/chunks/objects-C3EebVVe.js +0 -76
  94. package/dist/admin/chunks/objects-C3EebVVe.js.map +0 -1
  95. package/dist/admin/chunks/objects-wl73iEma.mjs +0 -73
  96. package/dist/admin/chunks/objects-wl73iEma.mjs.map +0 -1
  97. package/dist/admin/chunks/relations-D1R7vM_e.mjs.map +0 -1
  98. package/dist/admin/chunks/relations-VlsO9KQZ.js.map +0 -1
  99. package/dist/admin/chunks/useDragAndDrop-HYwNDExe.mjs.map +0 -1
  100. package/dist/admin/chunks/useDragAndDrop-gcqEJMnO.js.map +0 -1
  101. package/dist/admin/chunks/usePrev-Bjw2dhmq.mjs +0 -18
  102. package/dist/admin/chunks/usePrev-Bjw2dhmq.mjs.map +0 -1
  103. package/dist/admin/chunks/usePrev-DIYl-IAL.js +0 -21
  104. package/dist/admin/chunks/usePrev-DIYl-IAL.js.map +0 -1
  105. package/dist/admin/src/preview/components/PreviewContent.d.ts +0 -2
@@ -1,1291 +0,0 @@
1
- import { jsxs, jsx } from 'react/jsx-runtime';
2
- import * as React from 'react';
3
- import { createContext, useQueryParams, useForm, useField, useNotification, useFocusInputField } from '@strapi/admin/strapi-admin';
4
- import { Flex, Box, TextButton, Link, Field, Combobox, ComboboxOption, Typography, VisuallyHidden, useComposedRefs, IconButton, Tooltip } from '@strapi/design-system';
5
- import { ArrowClockwise, Drag, Cross } from '@strapi/icons';
6
- import { generateNKeysBetween } from 'fractional-indexing';
7
- import pipe from 'lodash/fp/pipe';
8
- import { getEmptyImage } from 'react-dnd-html5-backend';
9
- import { useIntl } from 'react-intl';
10
- import { NavLink } from 'react-router-dom';
11
- import { FixedSizeList } from 'react-window';
12
- import { styled } from 'styled-components';
13
- import { c as useDoc, d as buildValidParams, C as COLLECTION_TYPES, g as getTranslation, D as DocumentStatus } from './index-CcJLBLNf.mjs';
14
- import { u as useDragAndDrop, I as ItemTypes, D as DROP_SENSITIVITY } from './useDragAndDrop-HYwNDExe.mjs';
15
- import { u as useGetRelationsQuery, g as getRelationLabel, a as useDebounce, b as useLazySearchRelationsQuery } from './relations-D1R7vM_e.mjs';
16
-
17
- /**
18
- * We use this component to wrap any individual component field in the Edit View,
19
- * this could be a component field in a dynamic zone, a component within a repeatable space,
20
- * or even nested components.
21
- *
22
- * We primarily need this to provide the component id to the components so that they can
23
- * correctly fetch their relations.
24
- */ const [ComponentProvider, useComponent] = createContext('ComponentContext', {
25
- id: undefined,
26
- level: -1,
27
- uid: undefined,
28
- type: undefined
29
- });
30
-
31
- /**
32
- * Remove a relation, whether it's been already saved or not.
33
- * It's used both in RelationsList, where the "remove relation" button is, and in the input,
34
- * because we sometimes need to remove a previous relation when selecting a new one.
35
- */ function useHandleDisconnect(fieldName, consumerName) {
36
- const field = useField(fieldName);
37
- const removeFieldRow = useForm(consumerName, (state)=>state.removeFieldRow);
38
- const addFieldRow = useForm(consumerName, (state)=>state.addFieldRow);
39
- const handleDisconnect = (relation)=>{
40
- if (field.value && field.value.connect) {
41
- /**
42
- * A relation will exist in the `connect` array _if_ it has
43
- * been added without saving. In this case, we just remove it
44
- * from the connect array
45
- */ const indexOfRelationInConnectArray = field.value.connect.findIndex((rel)=>rel.id === relation.id);
46
- if (indexOfRelationInConnectArray >= 0) {
47
- removeFieldRow(`${fieldName}.connect`, indexOfRelationInConnectArray);
48
- return;
49
- }
50
- }
51
- addFieldRow(`${fieldName}.disconnect`, {
52
- id: relation.id,
53
- apiData: {
54
- id: relation.id,
55
- documentId: relation.documentId,
56
- locale: relation.locale
57
- }
58
- });
59
- };
60
- return handleDisconnect;
61
- }
62
- /* -------------------------------------------------------------------------------------------------
63
- * RelationsField
64
- * -----------------------------------------------------------------------------------------------*/ const RELATIONS_TO_DISPLAY = 5;
65
- const ONE_WAY_RELATIONS = [
66
- 'oneWay',
67
- 'oneToOne',
68
- 'manyToOne',
69
- 'oneToManyMorph',
70
- 'oneToOneMorph'
71
- ];
72
- /**
73
- * TODO: we get a rather ugly flash when we remove a single relation from the list leaving
74
- * no other relations when we press save. The initial relation re-renders, probably because
75
- * of the lag in the Form cleaning it's "disconnect" array, whilst our data has not been invalidated.
76
- *
77
- * Could we invalidate relation data on the document actions? Should we?
78
- */ /**
79
- * @internal
80
- * @description The relations field holds a lot of domain logic for handling relations which is rather complicated
81
- * At present we do not expose this to plugin developers, however, they are able to overwrite it themselves should
82
- * they wish to do so.
83
- */ const UnstableRelationsField = /*#__PURE__*/ React.forwardRef(({ disabled, label, ...props }, ref)=>{
84
- const [currentPage, setCurrentPage] = React.useState(1);
85
- const { document, model: documentModel } = useDoc();
86
- const documentId = document?.documentId;
87
- const { formatMessage } = useIntl();
88
- const [{ query }] = useQueryParams();
89
- const params = buildValidParams(query);
90
- const isMorph = props.attribute.relation.toLowerCase().includes('morph');
91
- const isDisabled = isMorph || disabled;
92
- const { componentId, componentUID } = useComponent('RelationsField', ({ uid, id })=>({
93
- componentId: id,
94
- componentUID: uid
95
- }));
96
- const isSubmitting = useForm('RelationsList', (state)=>state.isSubmitting);
97
- React.useEffect(()=>{
98
- setCurrentPage(1);
99
- }, [
100
- isSubmitting
101
- ]);
102
- /**
103
- * We'll always have a documentId in a created entry, so we look for a componentId first.
104
- * Same with `uid` and `documentModel`.
105
- */ const id = componentId ? componentId.toString() : documentId;
106
- const model = componentUID ?? documentModel;
107
- /**
108
- * The `name` prop is a complete path to the field, e.g. `field1.field2.field3`.
109
- * Where the above example would a nested field within two components, however
110
- * we only require the field on the component not the complete path since we query
111
- * individual components. Therefore we split the string and take the last item.
112
- */ const [targetField] = props.name.split('.').slice(-1);
113
- const { data, isLoading, isFetching } = useGetRelationsQuery({
114
- model,
115
- targetField,
116
- // below we don't run the query if there is no id.
117
- id: id,
118
- params: {
119
- ...params,
120
- pageSize: RELATIONS_TO_DISPLAY,
121
- page: currentPage
122
- }
123
- }, {
124
- refetchOnMountOrArgChange: true,
125
- skip: !id,
126
- selectFromResult: (result)=>{
127
- return {
128
- ...result,
129
- data: {
130
- ...result.data,
131
- results: result.data?.results ? result.data.results : []
132
- }
133
- };
134
- }
135
- });
136
- const handleLoadMore = ()=>{
137
- setCurrentPage((prev)=>prev + 1);
138
- };
139
- const field = useField(props.name);
140
- const isFetchingMoreRelations = isLoading || isFetching;
141
- const realServerRelationsCount = 'pagination' in data && data.pagination ? data.pagination.total : 0;
142
- /**
143
- * Items that are already connected, but reordered would be in
144
- * this list, so to get an accurate figure, we remove them.
145
- */ const relationsConnected = (field.value?.connect ?? []).filter((rel)=>data.results.findIndex((relation)=>relation.id === rel.id) === -1).length ?? 0;
146
- const relationsDisconnected = field.value?.disconnect?.length ?? 0;
147
- const relationsCount = realServerRelationsCount + relationsConnected - relationsDisconnected;
148
- /**
149
- * This is it, the source of truth for reordering in conjunction with partial loading & updating
150
- * of relations. Relations on load are given __temp_key__ when fetched, because we don't want to
151
- * create brand new keys everytime the data updates, just keep adding them onto the newly loaded ones.
152
- */ const relations = React.useMemo(()=>{
153
- const ctx = {
154
- field: field.value,
155
- // @ts-expect-error – targetModel does exist on the attribute. But it's not typed.
156
- href: `../${COLLECTION_TYPES}/${props.attribute.targetModel}`,
157
- mainField: props.mainField
158
- };
159
- /**
160
- * Tidy up our data.
161
- */ const transformations = pipe(removeConnected(ctx), removeDisconnected(ctx), addLabelAndHref(ctx));
162
- const transformedRels = transformations([
163
- ...data.results
164
- ]);
165
- /**
166
- * THIS IS CRUCIAL. If you don't sort by the __temp_key__ which comes from fractional indexing
167
- * then the list will be in the wrong order.
168
- */ return [
169
- ...transformedRels,
170
- ...field.value?.connect ?? []
171
- ].sort((a, b)=>{
172
- if (a.__temp_key__ < b.__temp_key__) return -1;
173
- if (a.__temp_key__ > b.__temp_key__) return 1;
174
- return 0;
175
- });
176
- }, [
177
- data.results,
178
- field.value,
179
- // @ts-expect-error – targetModel does exist on the attribute. But it's not typed.
180
- props.attribute.targetModel,
181
- props.mainField
182
- ]);
183
- const handleDisconnect = useHandleDisconnect(props.name, 'RelationsField');
184
- const handleConnect = (relation)=>{
185
- const [lastItemInList] = relations.slice(-1);
186
- const item = {
187
- id: relation.id,
188
- apiData: {
189
- id: relation.id,
190
- documentId: relation.documentId,
191
- locale: relation.locale
192
- },
193
- status: relation.status,
194
- /**
195
- * If there's a last item, that's the first key we use to generate out next one.
196
- */ __temp_key__: generateNKeysBetween(lastItemInList?.__temp_key__ ?? null, null, 1)[0],
197
- // Fallback to `id` if there is no `mainField` value, which will overwrite the above `id` property with the exact same data.
198
- [props.mainField?.name ?? 'documentId']: relation[props.mainField?.name ?? 'documentId'],
199
- label: getRelationLabel(relation, props.mainField),
200
- // @ts-expect-error – targetModel does exist on the attribute, but it's not typed.
201
- href: `../${COLLECTION_TYPES}/${props.attribute.targetModel}/${relation.documentId}?${relation.locale ? `plugins[i18n][locale]=${relation.locale}` : ''}`
202
- };
203
- if (ONE_WAY_RELATIONS.includes(props.attribute.relation)) {
204
- // Remove any existing relation so they can be replaced with the new one
205
- field.value?.connect?.forEach(handleDisconnect);
206
- relations.forEach(handleDisconnect);
207
- field.onChange(`${props.name}.connect`, [
208
- item
209
- ]);
210
- } else {
211
- field.onChange(`${props.name}.connect`, [
212
- ...field.value?.connect ?? [],
213
- item
214
- ]);
215
- }
216
- };
217
- return /*#__PURE__*/ jsxs(Flex, {
218
- ref: ref,
219
- direction: "column",
220
- gap: 3,
221
- justifyContent: "space-between",
222
- alignItems: "stretch",
223
- wrap: "wrap",
224
- children: [
225
- /*#__PURE__*/ jsxs(StyledFlex, {
226
- direction: "column",
227
- alignItems: "start",
228
- gap: 2,
229
- width: "100%",
230
- children: [
231
- /*#__PURE__*/ jsx(RelationsInput, {
232
- disabled: isDisabled,
233
- // NOTE: we should not default to using the documentId if the component is being created (componentUID is undefined)
234
- id: componentUID ? componentId ? `${componentId}` : '' : documentId,
235
- label: `${label} ${relationsCount > 0 ? `(${relationsCount})` : ''}`,
236
- model: model,
237
- onChange: handleConnect,
238
- ...props
239
- }),
240
- 'pagination' in data && data.pagination && data.pagination.pageCount > data.pagination.page ? /*#__PURE__*/ jsx(TextButton, {
241
- disabled: isFetchingMoreRelations,
242
- onClick: handleLoadMore,
243
- loading: isFetchingMoreRelations,
244
- startIcon: /*#__PURE__*/ jsx(ArrowClockwise, {}),
245
- // prevent the label from line-wrapping
246
- shrink: 0,
247
- children: formatMessage({
248
- id: getTranslation('relation.loadMore'),
249
- defaultMessage: 'Load More'
250
- })
251
- }) : null
252
- ]
253
- }),
254
- /*#__PURE__*/ jsx(UnstableRelationsList, {
255
- data: relations,
256
- serverData: data.results,
257
- disabled: isDisabled,
258
- name: props.name,
259
- isLoading: isFetchingMoreRelations,
260
- relationType: props.attribute.relation
261
- })
262
- ]
263
- });
264
- });
265
- const RelationsField = /*#__PURE__*/ React.forwardRef(({ disabled, label, ...props }, ref)=>{
266
- const [currentPage, setCurrentPage] = React.useState(1);
267
- const { document, model: documentModel } = useDoc();
268
- const documentId = document?.documentId;
269
- const { formatMessage } = useIntl();
270
- const [{ query }] = useQueryParams();
271
- const params = buildValidParams(query);
272
- const isMorph = props.attribute.relation.toLowerCase().includes('morph');
273
- const isDisabled = isMorph || disabled;
274
- const { componentId, componentUID } = useComponent('RelationsField', ({ uid, id })=>({
275
- componentId: id,
276
- componentUID: uid
277
- }));
278
- const isSubmitting = useForm('RelationsList', (state)=>state.isSubmitting);
279
- React.useEffect(()=>{
280
- setCurrentPage(1);
281
- }, [
282
- isSubmitting
283
- ]);
284
- /**
285
- * We'll always have a documentId in a created entry, so we look for a componentId first.
286
- * Same with `uid` and `documentModel`.
287
- */ const id = componentId ? componentId.toString() : documentId;
288
- const model = componentUID ?? documentModel;
289
- /**
290
- * The `name` prop is a complete path to the field, e.g. `field1.field2.field3`.
291
- * Where the above example would a nested field within two components, however
292
- * we only require the field on the component not the complete path since we query
293
- * individual components. Therefore we split the string and take the last item.
294
- */ const [targetField] = props.name.split('.').slice(-1);
295
- const { data, isLoading, isFetching } = useGetRelationsQuery({
296
- model,
297
- targetField,
298
- // below we don't run the query if there is no id.
299
- id: id,
300
- params: {
301
- ...params,
302
- pageSize: RELATIONS_TO_DISPLAY,
303
- page: currentPage
304
- }
305
- }, {
306
- refetchOnMountOrArgChange: true,
307
- skip: !id,
308
- selectFromResult: (result)=>{
309
- return {
310
- ...result,
311
- data: {
312
- ...result.data,
313
- results: result.data?.results ? result.data.results : []
314
- }
315
- };
316
- }
317
- });
318
- const handleLoadMore = ()=>{
319
- setCurrentPage((prev)=>prev + 1);
320
- };
321
- const field = useField(props.name);
322
- const isFetchingMoreRelations = isLoading || isFetching;
323
- const realServerRelationsCount = 'pagination' in data && data.pagination ? data.pagination.total : 0;
324
- /**
325
- * Items that are already connected, but reordered would be in
326
- * this list, so to get an accurate figure, we remove them.
327
- */ const relationsConnected = (field.value?.connect ?? []).filter((rel)=>data.results.findIndex((relation)=>relation.id === rel.id) === -1).length ?? 0;
328
- const relationsDisconnected = field.value?.disconnect?.length ?? 0;
329
- const relationsCount = realServerRelationsCount + relationsConnected - relationsDisconnected;
330
- /**
331
- * This is it, the source of truth for reordering in conjunction with partial loading & updating
332
- * of relations. Relations on load are given __temp_key__ when fetched, because we don't want to
333
- * create brand new keys everytime the data updates, just keep adding them onto the newly loaded ones.
334
- */ const relations = React.useMemo(()=>{
335
- const ctx = {
336
- field: field.value,
337
- // @ts-expect-error – targetModel does exist on the attribute. But it's not typed.
338
- href: `../${COLLECTION_TYPES}/${props.attribute.targetModel}`,
339
- mainField: props.mainField
340
- };
341
- /**
342
- * Tidy up our data.
343
- */ const transformations = pipe(removeConnected(ctx), removeDisconnected(ctx), addLabelAndHref(ctx));
344
- const transformedRels = transformations([
345
- ...data.results
346
- ]);
347
- /**
348
- * THIS IS CRUCIAL. If you don't sort by the __temp_key__ which comes from fractional indexing
349
- * then the list will be in the wrong order.
350
- */ return [
351
- ...transformedRels,
352
- ...field.value?.connect ?? []
353
- ].sort((a, b)=>{
354
- if (a.__temp_key__ < b.__temp_key__) return -1;
355
- if (a.__temp_key__ > b.__temp_key__) return 1;
356
- return 0;
357
- });
358
- }, [
359
- data.results,
360
- field.value,
361
- // @ts-expect-error – targetModel does exist on the attribute. But it's not typed.
362
- props.attribute.targetModel,
363
- props.mainField
364
- ]);
365
- const handleDisconnect = useHandleDisconnect(props.name, 'RelationsField');
366
- const handleConnect = (relation)=>{
367
- const [lastItemInList] = relations.slice(-1);
368
- const item = {
369
- id: relation.id,
370
- apiData: {
371
- id: relation.id,
372
- documentId: relation.documentId,
373
- locale: relation.locale
374
- },
375
- status: relation.status,
376
- /**
377
- * If there's a last item, that's the first key we use to generate out next one.
378
- */ __temp_key__: generateNKeysBetween(lastItemInList?.__temp_key__ ?? null, null, 1)[0],
379
- // Fallback to `id` if there is no `mainField` value, which will overwrite the above `id` property with the exact same data.
380
- [props.mainField?.name ?? 'documentId']: relation[props.mainField?.name ?? 'documentId'],
381
- label: getRelationLabel(relation, props.mainField),
382
- // @ts-expect-error – targetModel does exist on the attribute, but it's not typed.
383
- href: `../${COLLECTION_TYPES}/${props.attribute.targetModel}/${relation.documentId}?${relation.locale ? `plugins[i18n][locale]=${relation.locale}` : ''}`
384
- };
385
- if (ONE_WAY_RELATIONS.includes(props.attribute.relation)) {
386
- // Remove any existing relation so they can be replaced with the new one
387
- field.value?.connect?.forEach(handleDisconnect);
388
- relations.forEach(handleDisconnect);
389
- field.onChange(`${props.name}.connect`, [
390
- item
391
- ]);
392
- } else {
393
- field.onChange(`${props.name}.connect`, [
394
- ...field.value?.connect ?? [],
395
- item
396
- ]);
397
- }
398
- };
399
- return /*#__PURE__*/ jsxs(Flex, {
400
- ref: ref,
401
- direction: "column",
402
- gap: 3,
403
- justifyContent: "space-between",
404
- alignItems: "stretch",
405
- wrap: "wrap",
406
- children: [
407
- /*#__PURE__*/ jsxs(StyledFlex, {
408
- direction: "column",
409
- alignItems: "start",
410
- gap: 2,
411
- width: "100%",
412
- children: [
413
- /*#__PURE__*/ jsx(RelationsInput, {
414
- disabled: isDisabled,
415
- // NOTE: we should not default to using the documentId if the component is being created (componentUID is undefined)
416
- id: componentUID ? componentId ? `${componentId}` : '' : documentId,
417
- label: `${label} ${relationsCount > 0 ? `(${relationsCount})` : ''}`,
418
- model: model,
419
- onChange: handleConnect,
420
- ...props
421
- }),
422
- 'pagination' in data && data.pagination && data.pagination.pageCount > data.pagination.page ? /*#__PURE__*/ jsx(TextButton, {
423
- disabled: isFetchingMoreRelations,
424
- onClick: handleLoadMore,
425
- loading: isFetchingMoreRelations,
426
- startIcon: /*#__PURE__*/ jsx(ArrowClockwise, {}),
427
- // prevent the label from line-wrapping
428
- shrink: 0,
429
- children: formatMessage({
430
- id: getTranslation('relation.loadMore'),
431
- defaultMessage: 'Load More'
432
- })
433
- }) : null
434
- ]
435
- }),
436
- /*#__PURE__*/ jsx(RelationsList, {
437
- data: relations,
438
- serverData: data.results,
439
- disabled: isDisabled,
440
- name: props.name,
441
- isLoading: isFetchingMoreRelations,
442
- relationType: props.attribute.relation
443
- })
444
- ]
445
- });
446
- });
447
- /**
448
- * TODO: this can be removed once we stop shipping Inputs with
449
- * labels wrapped round in DS@2.
450
- */ const StyledFlex = styled(Flex)`
451
- & > div {
452
- width: 100%;
453
- }
454
- `;
455
- /**
456
- * If it's in the connected array, it can get out of our data array,
457
- * we'll be putting it back in later and sorting it anyway.
458
- */ const removeConnected = ({ field })=>(relations)=>{
459
- return relations.filter((relation)=>{
460
- const connectedRelations = field?.connect ?? [];
461
- return connectedRelations.findIndex((rel)=>rel.id === relation.id) === -1;
462
- });
463
- };
464
- /**
465
- * @description Removes relations that are in the `disconnect` array of the field
466
- */ const removeDisconnected = ({ field })=>(relations)=>relations.filter((relation)=>{
467
- const disconnectedRelations = field?.disconnect ?? [];
468
- return disconnectedRelations.findIndex((rel)=>rel.id === relation.id) === -1;
469
- });
470
- /**
471
- * @description Adds a label and href to the relation object we use this to render
472
- * a better UI where we can link to the relation and display a human-readable label.
473
- */ const addLabelAndHref = ({ mainField, href })=>(relations)=>relations.map((relation)=>{
474
- return {
475
- ...relation,
476
- // Fallback to `id` if there is no `mainField` value, which will overwrite the above `documentId` property with the exact same data.
477
- [mainField?.name ?? 'documentId']: relation[mainField?.name ?? 'documentId'],
478
- label: getRelationLabel(relation, mainField),
479
- href: `${href}/${relation.documentId}?${relation.locale ? `plugins[i18n][locale]=${relation.locale}` : ''}`
480
- };
481
- });
482
- /**
483
- * @description Contains all the logic for the combobox that can search
484
- * for relations and then add them to the field's connect array.
485
- */ const RelationsInput = ({ hint, id, model, label, labelAction, name, mainField, placeholder, required, unique: _unique, 'aria-label': _ariaLabel, onChange, ...props })=>{
486
- const [textValue, setTextValue] = React.useState('');
487
- const [searchParams, setSearchParams] = React.useState({
488
- _q: '',
489
- page: 1
490
- });
491
- const { toggleNotification } = useNotification();
492
- const [{ query }] = useQueryParams();
493
- const { formatMessage } = useIntl();
494
- const fieldRef = useFocusInputField(name);
495
- const field = useField(name);
496
- const searchParamsDebounced = useDebounce(searchParams, 300);
497
- const [searchForTrigger, { data, isLoading }] = useLazySearchRelationsQuery();
498
- /**
499
- * Because we're using a lazy query, we need to trigger the search
500
- * when the component mounts and when the search params change.
501
- * We also need to trigger the search when the field value changes
502
- * so that we can filter out the relations that are already connected.
503
- */ React.useEffect(()=>{
504
- /**
505
- * The `name` prop is a complete path to the field, e.g. `field1.field2.field3`.
506
- * Where the above example would a nested field within two components, however
507
- * we only require the field on the component not the complete path since we query
508
- * individual components. Therefore we split the string and take the last item.
509
- */ const [targetField] = name.split('.').slice(-1);
510
- searchForTrigger({
511
- model,
512
- targetField,
513
- params: {
514
- ...buildValidParams(query),
515
- id: id ?? '',
516
- pageSize: 10,
517
- idsToInclude: field.value?.disconnect?.map((rel)=>rel.id.toString()) ?? [],
518
- idsToOmit: field.value?.connect?.map((rel)=>rel.id.toString()) ?? [],
519
- ...searchParamsDebounced
520
- }
521
- });
522
- }, [
523
- field.value?.connect,
524
- field.value?.disconnect,
525
- id,
526
- model,
527
- name,
528
- query,
529
- searchForTrigger,
530
- searchParamsDebounced
531
- ]);
532
- const handleSearch = async (search)=>{
533
- setSearchParams((s)=>({
534
- ...s,
535
- _q: search,
536
- page: 1
537
- }));
538
- };
539
- const hasNextPage = data?.pagination ? data.pagination.page < data.pagination.pageCount : false;
540
- const options = data?.results ?? [];
541
- const handleChange = (relationId)=>{
542
- if (!relationId) {
543
- return;
544
- }
545
- const relation = options.find((opt)=>opt.id.toString() === relationId);
546
- if (!relation) {
547
- // This is very unlikely to happen, but it ensures we don't have any data for.
548
- console.error("You've tried to add a relation with an id that does not exist in the options you can see, this is likely a bug with Strapi. Please open an issue.");
549
- toggleNotification({
550
- message: formatMessage({
551
- id: getTranslation('relation.error-adding-relation'),
552
- defaultMessage: 'An error occurred while trying to add the relation.'
553
- }),
554
- type: 'danger'
555
- });
556
- return;
557
- }
558
- /**
559
- * You need to give this relation a correct _temp_key_ but
560
- * this component doesn't know about those ones, you can't rely
561
- * on the connect array because that doesn't hold items that haven't
562
- * moved. So use a callback to fill in the gaps when connecting.
563
- *
564
- */ onChange(relation);
565
- };
566
- const handleLoadMore = ()=>{
567
- if (!data || !data.pagination) {
568
- return;
569
- } else if (data.pagination.page < data.pagination.pageCount) {
570
- setSearchParams((s)=>({
571
- ...s,
572
- page: s.page + 1
573
- }));
574
- }
575
- };
576
- React.useLayoutEffect(()=>{
577
- setTextValue('');
578
- }, [
579
- field.value
580
- ]);
581
- return /*#__PURE__*/ jsxs(Field.Root, {
582
- error: field.error,
583
- hint: hint,
584
- name: name,
585
- required: required,
586
- children: [
587
- /*#__PURE__*/ jsx(Field.Label, {
588
- action: labelAction,
589
- children: label
590
- }),
591
- /*#__PURE__*/ jsx(Combobox, {
592
- ref: fieldRef,
593
- name: name,
594
- autocomplete: "list",
595
- placeholder: placeholder || formatMessage({
596
- id: getTranslation('relation.add'),
597
- defaultMessage: 'Add relation'
598
- }),
599
- hasMoreItems: hasNextPage,
600
- loading: isLoading,
601
- onOpenChange: ()=>{
602
- handleSearch(textValue ?? '');
603
- },
604
- noOptionsMessage: ()=>formatMessage({
605
- id: getTranslation('relation.notAvailable'),
606
- defaultMessage: 'No relations available'
607
- }),
608
- loadingMessage: formatMessage({
609
- id: getTranslation('relation.isLoading'),
610
- defaultMessage: 'Relations are loading'
611
- }),
612
- onLoadMore: handleLoadMore,
613
- textValue: textValue,
614
- onChange: handleChange,
615
- onTextValueChange: (text)=>{
616
- setTextValue(text);
617
- },
618
- onInputChange: (event)=>{
619
- handleSearch(event.currentTarget.value);
620
- },
621
- ...props,
622
- children: options.map((opt)=>{
623
- const textValue = getRelationLabel(opt, mainField);
624
- return /*#__PURE__*/ jsx(ComboboxOption, {
625
- value: opt.id.toString(),
626
- textValue: textValue,
627
- children: /*#__PURE__*/ jsxs(Flex, {
628
- gap: 2,
629
- justifyContent: "space-between",
630
- children: [
631
- /*#__PURE__*/ jsx(Typography, {
632
- ellipsis: true,
633
- children: textValue
634
- }),
635
- opt.status ? /*#__PURE__*/ jsx(DocumentStatus, {
636
- status: opt.status
637
- }) : null
638
- ]
639
- })
640
- }, opt.id);
641
- })
642
- }),
643
- /*#__PURE__*/ jsx(Field.Error, {}),
644
- /*#__PURE__*/ jsx(Field.Hint, {})
645
- ]
646
- });
647
- };
648
- /* -------------------------------------------------------------------------------------------------
649
- * RelationsList
650
- * -----------------------------------------------------------------------------------------------*/ const RELATION_ITEM_HEIGHT = 50;
651
- const RELATION_GUTTER = 4;
652
- const UnstableRelationsList = ({ data, serverData, disabled, name, isLoading, relationType })=>{
653
- const ariaDescriptionId = React.useId();
654
- const { formatMessage } = useIntl();
655
- const listRef = React.useRef(null);
656
- const outerListRef = React.useRef(null);
657
- const [overflow, setOverflow] = React.useState();
658
- const [liveText, setLiveText] = React.useState('');
659
- const field = useField(name);
660
- React.useEffect(()=>{
661
- if (data.length <= RELATIONS_TO_DISPLAY) {
662
- return setOverflow(undefined);
663
- }
664
- const handleNativeScroll = (e)=>{
665
- const el = e.target;
666
- const parentScrollContainerHeight = el.parentNode.scrollHeight;
667
- const maxScrollBottom = el.scrollHeight - el.scrollTop;
668
- if (el.scrollTop === 0) {
669
- return setOverflow('bottom');
670
- }
671
- if (maxScrollBottom === parentScrollContainerHeight) {
672
- return setOverflow('top');
673
- }
674
- return setOverflow('top-bottom');
675
- };
676
- const outerListRefCurrent = outerListRef?.current;
677
- if (!isLoading && data.length > 0 && outerListRefCurrent) {
678
- outerListRef.current.addEventListener('scroll', handleNativeScroll);
679
- }
680
- return ()=>{
681
- if (outerListRefCurrent) {
682
- outerListRefCurrent.removeEventListener('scroll', handleNativeScroll);
683
- }
684
- };
685
- }, [
686
- isLoading,
687
- data.length
688
- ]);
689
- const getItemPos = (index)=>`${index + 1} of ${data.length}`;
690
- const handleMoveItem = (newIndex, oldIndex)=>{
691
- const item = data[oldIndex];
692
- setLiveText(formatMessage({
693
- id: getTranslation('dnd.reorder'),
694
- defaultMessage: '{item}, moved. New position in list: {position}.'
695
- }, {
696
- item: item.label ?? item.documentId,
697
- position: getItemPos(newIndex)
698
- }));
699
- /**
700
- * Splicing mutates the array, so we need to create a new array
701
- */ const newData = [
702
- ...data
703
- ];
704
- const currentRow = data[oldIndex];
705
- const startKey = oldIndex > newIndex ? newData[newIndex - 1]?.__temp_key__ : newData[newIndex]?.__temp_key__;
706
- const endKey = oldIndex > newIndex ? newData[newIndex]?.__temp_key__ : newData[newIndex + 1]?.__temp_key__;
707
- /**
708
- * We're moving the relation between two other relations, so
709
- * we need to generate a new key that keeps the order
710
- */ const [newKey] = generateNKeysBetween(startKey, endKey, 1);
711
- newData.splice(oldIndex, 1);
712
- newData.splice(newIndex, 0, {
713
- ...currentRow,
714
- __temp_key__: newKey
715
- });
716
- /**
717
- * Now we diff against the server to understand what's different so we
718
- * can keep the connect array nice and tidy. It also needs reversing because
719
- * we reverse the relations from the server in the first place.
720
- */ const connectedRelations = newData.reduce((acc, relation, currentIndex, array)=>{
721
- const relationOnServer = serverData.find((oldRelation)=>oldRelation.id === relation.id);
722
- const relationInFront = array[currentIndex + 1];
723
- if (!relationOnServer || relationOnServer.__temp_key__ !== relation.__temp_key__) {
724
- const position = relationInFront ? {
725
- before: relationInFront.documentId,
726
- locale: relationInFront.locale,
727
- status: 'publishedAt' in relationInFront && relationInFront.publishedAt ? 'published' : 'draft'
728
- } : {
729
- end: true
730
- };
731
- const relationWithPosition = {
732
- ...relation,
733
- ...{
734
- apiData: {
735
- id: relation.id,
736
- documentId: relation.documentId,
737
- locale: relation.locale,
738
- position
739
- }
740
- }
741
- };
742
- return [
743
- ...acc,
744
- relationWithPosition
745
- ];
746
- }
747
- return acc;
748
- }, []).toReversed();
749
- field.onChange(`${name}.connect`, connectedRelations);
750
- };
751
- const handleGrabItem = (index)=>{
752
- const item = data[index];
753
- setLiveText(formatMessage({
754
- id: getTranslation('dnd.grab-item'),
755
- defaultMessage: `{item}, grabbed. Current position in list: {position}. Press up and down arrow to change position, Spacebar to drop, Escape to cancel.`
756
- }, {
757
- item: item.label ?? item.documentId,
758
- position: getItemPos(index)
759
- }));
760
- };
761
- const handleDropItem = (index)=>{
762
- const { href: _href, label, ...item } = data[index];
763
- setLiveText(formatMessage({
764
- id: getTranslation('dnd.drop-item'),
765
- defaultMessage: `{item}, dropped. Final position in list: {position}.`
766
- }, {
767
- item: label ?? item.documentId,
768
- position: getItemPos(index)
769
- }));
770
- };
771
- const handleCancel = (index)=>{
772
- const item = data[index];
773
- setLiveText(formatMessage({
774
- id: getTranslation('dnd.cancel-item'),
775
- defaultMessage: '{item}, dropped. Re-order cancelled.'
776
- }, {
777
- item: item.label ?? item.documentId
778
- }));
779
- };
780
- const handleDisconnect = useHandleDisconnect(name, 'RelationsList');
781
- /**
782
- * These relation types will only ever have one item
783
- * in their list, so you can't reorder a single item!
784
- */ const canReorder = !ONE_WAY_RELATIONS.includes(relationType);
785
- const dynamicListHeight = data.length > RELATIONS_TO_DISPLAY ? Math.min(data.length, RELATIONS_TO_DISPLAY) * (RELATION_ITEM_HEIGHT + RELATION_GUTTER) + RELATION_ITEM_HEIGHT / 2 : Math.min(data.length, RELATIONS_TO_DISPLAY) * (RELATION_ITEM_HEIGHT + RELATION_GUTTER);
786
- return /*#__PURE__*/ jsxs(ShadowBox, {
787
- $overflowDirection: overflow,
788
- children: [
789
- /*#__PURE__*/ jsx(VisuallyHidden, {
790
- id: ariaDescriptionId,
791
- children: formatMessage({
792
- id: getTranslation('dnd.instructions'),
793
- defaultMessage: `Press spacebar to grab and re-order`
794
- })
795
- }),
796
- /*#__PURE__*/ jsx(VisuallyHidden, {
797
- "aria-live": "assertive",
798
- children: liveText
799
- }),
800
- /*#__PURE__*/ jsx(FixedSizeList, {
801
- height: dynamicListHeight,
802
- ref: listRef,
803
- outerRef: outerListRef,
804
- itemCount: data.length,
805
- itemSize: RELATION_ITEM_HEIGHT + RELATION_GUTTER,
806
- itemData: {
807
- ariaDescribedBy: ariaDescriptionId,
808
- canDrag: canReorder,
809
- disabled,
810
- handleCancel,
811
- handleDropItem,
812
- handleGrabItem,
813
- handleMoveItem,
814
- name,
815
- handleDisconnect,
816
- relations: data
817
- },
818
- itemKey: (index)=>data[index].id,
819
- innerElementType: "ol",
820
- children: UnstableListItem
821
- })
822
- ]
823
- });
824
- };
825
- const RelationsList = ({ data, serverData, disabled, name, isLoading, relationType })=>{
826
- const ariaDescriptionId = React.useId();
827
- const { formatMessage } = useIntl();
828
- const listRef = React.useRef(null);
829
- const outerListRef = React.useRef(null);
830
- const [overflow, setOverflow] = React.useState();
831
- const [liveText, setLiveText] = React.useState('');
832
- const field = useField(name);
833
- React.useEffect(()=>{
834
- if (data.length <= RELATIONS_TO_DISPLAY) {
835
- return setOverflow(undefined);
836
- }
837
- const handleNativeScroll = (e)=>{
838
- const el = e.target;
839
- const parentScrollContainerHeight = el.parentNode.scrollHeight;
840
- const maxScrollBottom = el.scrollHeight - el.scrollTop;
841
- if (el.scrollTop === 0) {
842
- return setOverflow('bottom');
843
- }
844
- if (maxScrollBottom === parentScrollContainerHeight) {
845
- return setOverflow('top');
846
- }
847
- return setOverflow('top-bottom');
848
- };
849
- const outerListRefCurrent = outerListRef?.current;
850
- if (!isLoading && data.length > 0 && outerListRefCurrent) {
851
- outerListRef.current.addEventListener('scroll', handleNativeScroll);
852
- }
853
- return ()=>{
854
- if (outerListRefCurrent) {
855
- outerListRefCurrent.removeEventListener('scroll', handleNativeScroll);
856
- }
857
- };
858
- }, [
859
- isLoading,
860
- data.length
861
- ]);
862
- const getItemPos = (index)=>`${index + 1} of ${data.length}`;
863
- const handleMoveItem = (newIndex, oldIndex)=>{
864
- const item = data[oldIndex];
865
- setLiveText(formatMessage({
866
- id: getTranslation('dnd.reorder'),
867
- defaultMessage: '{item}, moved. New position in list: {position}.'
868
- }, {
869
- item: item.label ?? item.documentId,
870
- position: getItemPos(newIndex)
871
- }));
872
- /**
873
- * Splicing mutates the array, so we need to create a new array
874
- */ const newData = [
875
- ...data
876
- ];
877
- const currentRow = data[oldIndex];
878
- const startKey = oldIndex > newIndex ? newData[newIndex - 1]?.__temp_key__ : newData[newIndex]?.__temp_key__;
879
- const endKey = oldIndex > newIndex ? newData[newIndex]?.__temp_key__ : newData[newIndex + 1]?.__temp_key__;
880
- /**
881
- * We're moving the relation between two other relations, so
882
- * we need to generate a new key that keeps the order
883
- */ const [newKey] = generateNKeysBetween(startKey, endKey, 1);
884
- newData.splice(oldIndex, 1);
885
- newData.splice(newIndex, 0, {
886
- ...currentRow,
887
- __temp_key__: newKey
888
- });
889
- /**
890
- * Now we diff against the server to understand what's different so we
891
- * can keep the connect array nice and tidy. It also needs reversing because
892
- * we reverse the relations from the server in the first place.
893
- */ const connectedRelations = newData.reduce((acc, relation, currentIndex, array)=>{
894
- const relationOnServer = serverData.find((oldRelation)=>oldRelation.id === relation.id);
895
- const relationInFront = array[currentIndex + 1];
896
- if (!relationOnServer || relationOnServer.__temp_key__ !== relation.__temp_key__) {
897
- const position = relationInFront ? {
898
- before: relationInFront.documentId,
899
- locale: relationInFront.locale,
900
- status: 'publishedAt' in relationInFront && relationInFront.publishedAt ? 'published' : 'draft'
901
- } : {
902
- end: true
903
- };
904
- const relationWithPosition = {
905
- ...relation,
906
- ...{
907
- apiData: {
908
- id: relation.id,
909
- documentId: relation.documentId,
910
- locale: relation.locale,
911
- position
912
- }
913
- }
914
- };
915
- return [
916
- ...acc,
917
- relationWithPosition
918
- ];
919
- }
920
- return acc;
921
- }, []).toReversed();
922
- field.onChange(`${name}.connect`, connectedRelations);
923
- };
924
- const handleGrabItem = (index)=>{
925
- const item = data[index];
926
- setLiveText(formatMessage({
927
- id: getTranslation('dnd.grab-item'),
928
- defaultMessage: `{item}, grabbed. Current position in list: {position}. Press up and down arrow to change position, Spacebar to drop, Escape to cancel.`
929
- }, {
930
- item: item.label ?? item.documentId,
931
- position: getItemPos(index)
932
- }));
933
- };
934
- const handleDropItem = (index)=>{
935
- const { href: _href, label, ...item } = data[index];
936
- setLiveText(formatMessage({
937
- id: getTranslation('dnd.drop-item'),
938
- defaultMessage: `{item}, dropped. Final position in list: {position}.`
939
- }, {
940
- item: label ?? item.documentId,
941
- position: getItemPos(index)
942
- }));
943
- };
944
- const handleCancel = (index)=>{
945
- const item = data[index];
946
- setLiveText(formatMessage({
947
- id: getTranslation('dnd.cancel-item'),
948
- defaultMessage: '{item}, dropped. Re-order cancelled.'
949
- }, {
950
- item: item.label ?? item.documentId
951
- }));
952
- };
953
- const handleDisconnect = useHandleDisconnect(name, 'RelationsList');
954
- /**
955
- * These relation types will only ever have one item
956
- * in their list, so you can't reorder a single item!
957
- */ const canReorder = !ONE_WAY_RELATIONS.includes(relationType);
958
- const dynamicListHeight = data.length > RELATIONS_TO_DISPLAY ? Math.min(data.length, RELATIONS_TO_DISPLAY) * (RELATION_ITEM_HEIGHT + RELATION_GUTTER) + RELATION_ITEM_HEIGHT / 2 : Math.min(data.length, RELATIONS_TO_DISPLAY) * (RELATION_ITEM_HEIGHT + RELATION_GUTTER);
959
- return /*#__PURE__*/ jsxs(ShadowBox, {
960
- $overflowDirection: overflow,
961
- children: [
962
- /*#__PURE__*/ jsx(VisuallyHidden, {
963
- id: ariaDescriptionId,
964
- children: formatMessage({
965
- id: getTranslation('dnd.instructions'),
966
- defaultMessage: `Press spacebar to grab and re-order`
967
- })
968
- }),
969
- /*#__PURE__*/ jsx(VisuallyHidden, {
970
- "aria-live": "assertive",
971
- children: liveText
972
- }),
973
- /*#__PURE__*/ jsx(FixedSizeList, {
974
- height: dynamicListHeight,
975
- ref: listRef,
976
- outerRef: outerListRef,
977
- itemCount: data.length,
978
- itemSize: RELATION_ITEM_HEIGHT + RELATION_GUTTER,
979
- itemData: {
980
- ariaDescribedBy: ariaDescriptionId,
981
- canDrag: canReorder,
982
- disabled,
983
- handleCancel,
984
- handleDropItem,
985
- handleGrabItem,
986
- handleMoveItem,
987
- name,
988
- handleDisconnect,
989
- relations: data
990
- },
991
- itemKey: (index)=>data[index].id,
992
- innerElementType: "ol",
993
- children: ListItem
994
- })
995
- ]
996
- });
997
- };
998
- const ShadowBox = styled(Box)`
999
- position: relative;
1000
- overflow: hidden;
1001
- flex: 1;
1002
-
1003
- &:before,
1004
- &:after {
1005
- position: absolute;
1006
- width: 100%;
1007
- height: 4px;
1008
- z-index: 1;
1009
- }
1010
-
1011
- &:before {
1012
- /* TODO: as for DS Table component we would need this to be handled by the DS theme */
1013
- content: '';
1014
- background: linear-gradient(rgba(3, 3, 5, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
1015
- top: 0;
1016
- opacity: ${({ $overflowDirection })=>$overflowDirection === 'top-bottom' || $overflowDirection === 'top' ? 1 : 0};
1017
- transition: opacity 0.2s ease-in-out;
1018
- }
1019
-
1020
- &:after {
1021
- /* TODO: as for DS Table component we would need this to be handled by the DS theme */
1022
- content: '';
1023
- background: linear-gradient(0deg, rgba(3, 3, 5, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
1024
- bottom: 0;
1025
- opacity: ${({ $overflowDirection })=>$overflowDirection === 'top-bottom' || $overflowDirection === 'bottom' ? 1 : 0};
1026
- transition: opacity 0.2s ease-in-out;
1027
- }
1028
- `;
1029
- const CustomTextButton = styled(TextButton)`
1030
- & > span {
1031
- font-size: ${({ theme })=>theme.fontSizes[2]};
1032
- }
1033
- `;
1034
- const UnstableListItem = ({ data, index, style })=>{
1035
- const { ariaDescribedBy, canDrag = false, disabled = false, handleCancel, handleDisconnect, handleDropItem, handleGrabItem, handleMoveItem, name, relations } = data;
1036
- const { formatMessage } = useIntl();
1037
- const { id, label, status } = relations[index];
1038
- const [{ handlerId, isDragging, handleKeyDown }, relationRef, dropRef, dragRef, dragPreviewRef] = useDragAndDrop(canDrag && !disabled, {
1039
- type: `${ItemTypes.RELATION}_${name}`,
1040
- index,
1041
- item: {
1042
- displayedValue: label,
1043
- status,
1044
- id: id,
1045
- index
1046
- },
1047
- onMoveItem: handleMoveItem,
1048
- onDropItem: handleDropItem,
1049
- onGrabItem: handleGrabItem,
1050
- onCancel: handleCancel,
1051
- dropSensitivity: DROP_SENSITIVITY.REGULAR
1052
- });
1053
- const composedRefs = useComposedRefs(relationRef, dragRef);
1054
- React.useEffect(()=>{
1055
- dragPreviewRef(getEmptyImage());
1056
- }, [
1057
- dragPreviewRef
1058
- ]);
1059
- return /*#__PURE__*/ jsx(Box, {
1060
- style: style,
1061
- tag: "li",
1062
- ref: dropRef,
1063
- "aria-describedby": ariaDescribedBy,
1064
- cursor: canDrag ? 'all-scroll' : 'default',
1065
- children: isDragging ? /*#__PURE__*/ jsx(RelationItemPlaceholder, {}) : /*#__PURE__*/ jsxs(Flex, {
1066
- paddingTop: 2,
1067
- paddingBottom: 2,
1068
- paddingLeft: canDrag ? 2 : 4,
1069
- paddingRight: 4,
1070
- hasRadius: true,
1071
- borderColor: "neutral200",
1072
- background: disabled ? 'neutral150' : 'neutral0',
1073
- justifyContent: "space-between",
1074
- ref: composedRefs,
1075
- "data-handler-id": handlerId,
1076
- children: [
1077
- /*#__PURE__*/ jsxs(FlexWrapper, {
1078
- gap: 1,
1079
- children: [
1080
- canDrag ? /*#__PURE__*/ jsx(IconButton, {
1081
- tag: "div",
1082
- role: "button",
1083
- tabIndex: 0,
1084
- withTooltip: false,
1085
- label: formatMessage({
1086
- id: getTranslation('components.RelationInput.icon-button-aria-label'),
1087
- defaultMessage: 'Drag'
1088
- }),
1089
- variant: "ghost",
1090
- onKeyDown: handleKeyDown,
1091
- disabled: disabled,
1092
- children: /*#__PURE__*/ jsx(Drag, {})
1093
- }) : null,
1094
- /*#__PURE__*/ jsxs(Flex, {
1095
- width: "100%",
1096
- minWidth: 0,
1097
- justifyContent: "space-between",
1098
- children: [
1099
- /*#__PURE__*/ jsx(Box, {
1100
- minWidth: 0,
1101
- paddingTop: 1,
1102
- paddingBottom: 1,
1103
- paddingRight: 4,
1104
- children: /*#__PURE__*/ jsx(Tooltip, {
1105
- description: label,
1106
- children: /*#__PURE__*/ jsx(CustomTextButton, {
1107
- onClick: ()=>console.log('OPEN MODAL'),
1108
- children: label
1109
- })
1110
- })
1111
- }),
1112
- status ? /*#__PURE__*/ jsx(DocumentStatus, {
1113
- status: status
1114
- }) : null
1115
- ]
1116
- })
1117
- ]
1118
- }),
1119
- /*#__PURE__*/ jsx(Box, {
1120
- paddingLeft: 4,
1121
- children: /*#__PURE__*/ jsx(IconButton, {
1122
- onClick: ()=>handleDisconnect(relations[index]),
1123
- disabled: disabled,
1124
- label: formatMessage({
1125
- id: getTranslation('relation.disconnect'),
1126
- defaultMessage: 'Remove'
1127
- }),
1128
- variant: "ghost",
1129
- size: "S",
1130
- children: /*#__PURE__*/ jsx(Cross, {})
1131
- })
1132
- })
1133
- ]
1134
- })
1135
- });
1136
- };
1137
- const ListItem = ({ data, index, style })=>{
1138
- const { ariaDescribedBy, canDrag = false, disabled = false, handleCancel, handleDisconnect, handleDropItem, handleGrabItem, handleMoveItem, name, relations } = data;
1139
- const { formatMessage } = useIntl();
1140
- const { href, id, label, status } = relations[index];
1141
- const [{ handlerId, isDragging, handleKeyDown }, relationRef, dropRef, dragRef, dragPreviewRef] = useDragAndDrop(canDrag && !disabled, {
1142
- type: `${ItemTypes.RELATION}_${name}`,
1143
- index,
1144
- item: {
1145
- displayedValue: label,
1146
- status,
1147
- id: id,
1148
- index
1149
- },
1150
- onMoveItem: handleMoveItem,
1151
- onDropItem: handleDropItem,
1152
- onGrabItem: handleGrabItem,
1153
- onCancel: handleCancel,
1154
- dropSensitivity: DROP_SENSITIVITY.REGULAR
1155
- });
1156
- const composedRefs = useComposedRefs(relationRef, dragRef);
1157
- React.useEffect(()=>{
1158
- dragPreviewRef(getEmptyImage());
1159
- }, [
1160
- dragPreviewRef
1161
- ]);
1162
- return /*#__PURE__*/ jsx(Box, {
1163
- style: style,
1164
- tag: "li",
1165
- ref: dropRef,
1166
- "aria-describedby": ariaDescribedBy,
1167
- cursor: canDrag ? 'all-scroll' : 'default',
1168
- children: isDragging ? /*#__PURE__*/ jsx(RelationItemPlaceholder, {}) : /*#__PURE__*/ jsxs(Flex, {
1169
- paddingTop: 2,
1170
- paddingBottom: 2,
1171
- paddingLeft: canDrag ? 2 : 4,
1172
- paddingRight: 4,
1173
- hasRadius: true,
1174
- borderColor: "neutral200",
1175
- background: disabled ? 'neutral150' : 'neutral0',
1176
- justifyContent: "space-between",
1177
- ref: composedRefs,
1178
- "data-handler-id": handlerId,
1179
- children: [
1180
- /*#__PURE__*/ jsxs(FlexWrapper, {
1181
- gap: 1,
1182
- children: [
1183
- canDrag ? /*#__PURE__*/ jsx(IconButton, {
1184
- tag: "div",
1185
- role: "button",
1186
- tabIndex: 0,
1187
- withTooltip: false,
1188
- label: formatMessage({
1189
- id: getTranslation('components.RelationInput.icon-button-aria-label'),
1190
- defaultMessage: 'Drag'
1191
- }),
1192
- variant: "ghost",
1193
- onKeyDown: handleKeyDown,
1194
- disabled: disabled,
1195
- children: /*#__PURE__*/ jsx(Drag, {})
1196
- }) : null,
1197
- /*#__PURE__*/ jsxs(Flex, {
1198
- width: "100%",
1199
- minWidth: 0,
1200
- justifyContent: "space-between",
1201
- children: [
1202
- /*#__PURE__*/ jsx(Box, {
1203
- minWidth: 0,
1204
- paddingTop: 1,
1205
- paddingBottom: 1,
1206
- paddingRight: 4,
1207
- children: /*#__PURE__*/ jsx(Tooltip, {
1208
- description: label,
1209
- children: href ? /*#__PURE__*/ jsx(LinkEllipsis, {
1210
- tag: NavLink,
1211
- to: href,
1212
- isExternal: false,
1213
- children: label
1214
- }) : /*#__PURE__*/ jsx(Typography, {
1215
- textColor: disabled ? 'neutral600' : 'primary600',
1216
- ellipsis: true,
1217
- children: label
1218
- })
1219
- })
1220
- }),
1221
- status ? /*#__PURE__*/ jsx(DocumentStatus, {
1222
- status: status
1223
- }) : null
1224
- ]
1225
- })
1226
- ]
1227
- }),
1228
- /*#__PURE__*/ jsx(Box, {
1229
- paddingLeft: 4,
1230
- children: /*#__PURE__*/ jsx(IconButton, {
1231
- onClick: ()=>handleDisconnect(relations[index]),
1232
- disabled: disabled,
1233
- label: formatMessage({
1234
- id: getTranslation('relation.disconnect'),
1235
- defaultMessage: 'Remove'
1236
- }),
1237
- variant: "ghost",
1238
- size: "S",
1239
- children: /*#__PURE__*/ jsx(Cross, {})
1240
- })
1241
- })
1242
- ]
1243
- })
1244
- });
1245
- };
1246
- const FlexWrapper = styled(Flex)`
1247
- width: 100%;
1248
- /* Used to prevent endAction to be pushed out of container */
1249
- min-width: 0;
1250
-
1251
- & > div[role='button'] {
1252
- cursor: all-scroll;
1253
- }
1254
- `;
1255
- const DisconnectButton = styled.button`
1256
- svg path {
1257
- fill: ${({ theme, disabled })=>disabled ? theme.colors.neutral600 : theme.colors.neutral500};
1258
- }
1259
-
1260
- &:hover svg path,
1261
- &:focus svg path {
1262
- fill: ${({ theme, disabled })=>!disabled && theme.colors.neutral600};
1263
- }
1264
- `;
1265
- const LinkEllipsis = styled(Link)`
1266
- display: block;
1267
-
1268
- & > span {
1269
- white-space: nowrap;
1270
- overflow: hidden;
1271
- text-overflow: ellipsis;
1272
- display: block;
1273
- }
1274
- `;
1275
- const RelationItemPlaceholder = ()=>/*#__PURE__*/ jsx(Box, {
1276
- paddingTop: 2,
1277
- paddingBottom: 2,
1278
- paddingLeft: 4,
1279
- paddingRight: 4,
1280
- hasRadius: true,
1281
- borderStyle: "dashed",
1282
- borderColor: "primary600",
1283
- borderWidth: "1px",
1284
- background: "primary100",
1285
- height: `calc(100% - ${RELATION_GUTTER}px)`
1286
- });
1287
- const MemoizedRelationsField = /*#__PURE__*/ React.memo(RelationsField);
1288
- const MemoizedUnstableRelationsField = /*#__PURE__*/ React.memo(UnstableRelationsField);
1289
-
1290
- export { ComponentProvider as C, DisconnectButton as D, FlexWrapper as F, LinkEllipsis as L, MemoizedUnstableRelationsField as M, MemoizedRelationsField as a, useComponent as u };
1291
- //# sourceMappingURL=Relations-CiOfFNxW.mjs.map