-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathindex.tsx
More file actions
301 lines (293 loc) · 8.09 KB
/
index.tsx
File metadata and controls
301 lines (293 loc) · 8.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/**
* WordPress dependencies
*/
import {
Button,
Icon,
__experimentalText as Text,
__experimentalTruncate as Truncate,
__experimentalVStack as VStack,
VisuallyHidden,
} from '@wordpress/components';
import { store as coreStore, type Attachment } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';
import { useCallback, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { archive, audio, video, file } from '@wordpress/icons';
import {
MediaUpload,
privateApis as mediaUtilsPrivateApis,
} from '@wordpress/media-utils';
/**
* Internal dependencies
*/
import { unlock } from '../../lock-unlock';
import type { MediaEditProps } from '../../types';
const { MediaUploadModal } = unlock( mediaUtilsPrivateApis );
/**
* Conditional Media component that uses MediaUploadModal when experiment is enabled,
* otherwise falls back to media-utils MediaUpload.
*
* @param root0 Component props.
* @param root0.render Render prop function that receives { open } object.
* @param root0.multiple Whether to allow multiple media selections.
* @return The component.
*/
function ConditionalMediaUpload( { render, multiple, ...props }: any ) {
const [ isModalOpen, setIsModalOpen ] = useState( false );
if ( ( window as any ).__experimentalDataViewsMediaModal ) {
return (
<>
{ render && render( { open: () => setIsModalOpen( true ) } ) }
{ isModalOpen && (
<MediaUploadModal
{ ...props }
multiple={ multiple }
isOpen={ isModalOpen }
onClose={ () => {
setIsModalOpen( false );
props.onClose?.();
} }
onSelect={ ( media: any ) => {
setIsModalOpen( false );
props.onSelect?.( media );
} }
/>
) }
</>
);
}
// Fallback to media-utils MediaUpload when experiment is disabled.
return (
<MediaUpload
{ ...props }
render={ render }
multiple={ multiple ? 'add' : undefined }
/>
);
}
function MediaPickerButton( {
open,
children,
label,
}: {
open: () => void;
children: React.ReactNode;
label: string;
} ) {
return (
<div
className="fields__media-edit-picker-button"
role="button"
tabIndex={ 0 }
onClick={ open }
onKeyDown={ ( event ) => {
if ( event.key === 'Enter' || event.key === ' ' ) {
event.preventDefault();
open();
}
} }
aria-label={ label }
>
{ children }
</div>
);
}
const archiveMimeTypes = [
'application/zip',
'application/x-zip-compressed',
'application/x-rar-compressed',
'application/x-7z-compressed',
'application/x-tar',
'application/x-gzip',
];
function MediaPreview( {
url,
attachment,
}: {
url: string;
attachment: Attachment< 'view' > | null;
} ) {
if ( ! attachment ) {
return null;
}
const attachmentTitle = attachment.title.rendered;
const mimeType = attachment.mime_type;
let preview: JSX.Element = <Icon icon={ file } />;
if ( mimeType.startsWith( 'image/' ) ) {
preview = (
<img
className="fields__media-edit-thumbnail"
alt={ attachment.alt_text || '' }
src={ url }
/>
);
} else if ( mimeType.startsWith( 'audio/' ) ) {
preview = <Icon icon={ audio } />;
} else if ( mimeType.startsWith( 'video/' ) ) {
preview = <Icon icon={ video } />;
} else if ( archiveMimeTypes.includes( mimeType ) ) {
preview = <Icon icon={ archive } />;
}
return (
<>
{ preview }
<Truncate
className="fields__media-edit-filename"
title={ attachmentTitle }
>
{ attachmentTitle }
</Truncate>
</>
);
}
/**
* A media edit control component that provides a media picker UI with upload functionality
* for selecting WordPress media attachments. Supports both the traditional WordPress media
* library and the experimental DataViews media modal.
*
* This component is intended to be used as the `Edit` property of a field definition when
* registering fields with `registerEntityField` from `@wordpress/editor`.
*
* @template Item - The type of the item being edited.
*
* @param {MediaEditProps<Item>} props - The component props.
* @param {Item} props.data - The item being edited.
* @param {Object} props.field - The field configuration with getValue and setValue methods.
* @param {Function} props.onChange - Callback function when the media selection changes.
* @param {string[]} [props.allowedTypes] - Array of allowed media types. Default `['image']`.
* @param {boolean} [props.multiple] - Whether to allow multiple media selections. Default `false`.
*
* @return {JSX.Element} The media edit control component.
*
* @example
* ```tsx
* import { MediaEdit } from '@wordpress/fields';
* import type { DataFormControlProps } from '@wordpress/dataviews';
*
* const featuredImageField = {
* id: 'featured_media',
* type: 'media',
* label: 'Featured Image',
* Edit: (props: DataFormControlProps<MyPostType>) => (
* <MediaEdit
* {...props}
* allowedTypes={['image']}
* />
* ),
* };
* ```
*/
export default function MediaEdit< Item >( {
data,
field,
onChange,
allowedTypes = [ 'image' ],
multiple,
}: MediaEditProps< Item > ) {
const value = field.getValue( { item: data } );
const attachments = useSelect(
( select ) => {
if ( ! value ) {
return null;
}
const normalizedValue = Array.isArray( value ) ? value : [ value ];
const { getEntityRecords } = select( coreStore );
return getEntityRecords( 'postType', 'attachment', {
include: normalizedValue,
} ) as Attachment< 'view' >[] | null;
},
[ value ]
);
const onChangeControl = useCallback(
( newValue: number | number[] | undefined ) =>
onChange( field.setValue( { item: data, value: newValue } ) ),
[ data, field, onChange ]
);
const removeItem = ( itemId: number ) => {
const currentIds = Array.isArray( value ) ? value : [ value ];
const newIds = currentIds.filter( ( id ) => id !== itemId );
onChangeControl( newIds.length ? newIds : undefined );
};
return (
<fieldset className="fields__media-edit" data-field-id={ field.id }>
<ConditionalMediaUpload
onSelect={ ( selectedMedia: any ) => {
if ( multiple ) {
const newIds = Array.isArray( selectedMedia )
? selectedMedia.map( ( m: any ) => m.id )
: [ selectedMedia.id ];
onChangeControl( newIds );
} else {
onChangeControl( selectedMedia.id );
}
} }
allowedTypes={ allowedTypes }
value={ value }
multiple={ multiple }
title={ field.label }
render={ ( { open }: any ) => {
const addButtonLabel = attachments?.length
? __( 'Add files' )
: field.placeholder || __( 'Choose file' );
return (
<VStack spacing={ 2 }>
<VisuallyHidden as="label">
{ field.label }
</VisuallyHidden>
{ !! attachments?.length && (
<VStack spacing={ 2 }>
{ attachments.map( ( attachment ) => (
<div
key={ attachment.id }
className="fields__media-edit-row"
>
<MediaPickerButton
open={ open }
label={ __( 'Replace' ) }
>
<MediaPreview
url={
attachment.source_url
}
attachment={ attachment }
/>
</MediaPickerButton>
<Button
__next40pxDefaultSize
className="fields__media-edit-remove"
text={ __( 'Remove' ) }
variant="secondary"
onClick={ (
event: React.MouseEvent< HTMLButtonElement >
) => {
event.stopPropagation();
removeItem( attachment.id );
} }
/>
</div>
) ) }
</VStack>
) }
{ ( multiple || ! attachments?.length ) && (
<MediaPickerButton
open={ open }
label={ addButtonLabel }
>
<span className="fields__media-edit-placeholder">
{ addButtonLabel }
</span>
</MediaPickerButton>
) }
{ field.description && (
<Text variant="muted">
{ field.description }
</Text>
) }
</VStack>
);
} }
/>
</fieldset>
);
}