-
Notifications
You must be signed in to change notification settings - Fork 862
Expand file tree
/
Copy pathedit.tsx
More file actions
567 lines (503 loc) · 15.6 KB
/
edit.tsx
File metadata and controls
567 lines (503 loc) · 15.6 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/**
* WordPress dependencies
*/
import { store as blockEditorStore } from '@wordpress/block-editor';
import {
BlockIcon,
useBlockProps,
InspectorControls,
BlockControls,
} from '@wordpress/block-editor';
import { createBlock } from '@wordpress/blocks';
import { Spinner, Placeholder, Button, withNotices } from '@wordpress/components';
import { store as coreStore } from '@wordpress/core-data';
import { useSelect, useDispatch } from '@wordpress/data';
import { useEffect, useState, useCallback, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import classNames from 'classnames';
import debugFactory from 'debug';
/**
* Internal dependencies
*/
import getMediaToken from '../../../lib/get-media-token';
import { buildVideoPressURL, getVideoPressUrl } from '../../../lib/url';
import { useSyncMedia } from '../../hooks/use-video-data-update';
import ColorPanel from './components/color-panel';
import DetailsPanel from './components/details-panel';
import { VideoPressIcon } from './components/icons';
import PlaybackPanel from './components/playback-panel';
import PosterImageBlockControl from './components/poster-image-block-control';
import PrivacyAndRatingPanel from './components/privacy-and-rating-panel';
import ReplaceControl from './components/replace-control';
import TracksControl from './components/tracks-control';
import VideoPressPlayer from './components/videopress-player';
import VideoPressUploader from './components/videopress-uploader';
import { description, title } from '.';
/**
* Types
*/
import type { VideoBlockAttributes } from './types';
import type React from 'react';
import './editor.scss';
const debug = debugFactory( 'videopress:video:edit' );
const VIDEO_PREVIEW_ATTEMPTS_LIMIT = 10;
export const PlaceholderWrapper = withNotices( function ( {
children,
errorMessage,
noticeUI,
noticeOperations,
instructions = description,
disableInstructions,
} ) {
useEffect( () => {
if ( ! errorMessage ) {
return;
}
noticeOperations.removeAllNotices();
noticeOperations.createErrorNotice( errorMessage );
}, [ errorMessage, noticeOperations ] );
return (
<Placeholder
icon={ <BlockIcon icon={ VideoPressIcon } /> }
label={ title }
instructions={ disableInstructions ? null : instructions }
notices={ noticeUI }
>
{ children }
</Placeholder>
);
} );
/**
* VideoPress block Edit react components
*
* @param {object} props - Component props.
* @param {object} props.attributes - Block attributes.
* @param {Function} props.setAttributes - Function to set block attributes.
* @param {boolean} props.isSelected - Whether the block is selected.
* @param {string} props.clientId - Block client ID.
* @returns {React.ReactNode} - React component.
*/
export default function VideoPressEdit( {
attributes,
setAttributes,
isSelected,
clientId,
} ): React.ReactNode {
const {
autoplay,
loop,
muted,
controls,
playsinline,
preload,
useAverageColor,
seekbarColor,
seekbarLoadingColor,
seekbarPlayedColor,
guid,
id,
cacheHtml,
poster,
align,
videoRatio,
tracks,
isPrivate,
src,
caption,
isExample,
} = attributes;
const videoPressUrl = getVideoPressUrl( guid, {
autoplay,
controls,
loop,
muted,
playsinline,
preload,
seekbarColor,
seekbarLoadingColor,
seekbarPlayedColor,
useAverageColor,
poster,
} );
/*
* Request token when site is private
*/
const [ token, setToken ] = useState( null );
useEffect( () => {
if ( ! isPrivate ) {
return setToken( null );
}
getMediaToken( 'playback', { id, guid } ).then( tokenData => {
setToken( tokenData?.token );
} );
}, [ isPrivate ] );
// Store if the chapters file is auto-generated in a local state.
const [ isAutoGeneratedChapter, setIsAutoGeneratedChapter ] = useState( true );
// Detect if the chapter file is auto-generated.
const chapter = tracks?.filter( track => track.kind === 'chapters' )?.[ 0 ];
useEffect( () => {
if ( ! chapter || ! chapter.src ) {
return;
}
// Wait for the token when the video is private.
if ( isPrivate && ! token ) {
return;
}
const queryString = token
? `?${ new URLSearchParams( { metadata_token: token } ).toString() }`
: '';
const chapterUrl = `https://videos.files.wordpress.com/${ guid }/${ chapter.src }${ queryString }`;
try {
fetch( chapterUrl )
.then( function ( response ) {
response.text().then( function ( text ) {
if ( ! text ) {
return;
}
const isAutoGeneratedChaptersFile = /videopress-chapters-auto-generated/.test( text );
if ( isAutoGeneratedChaptersFile ) {
debug( 'Chapter %o auto-generated detected', chapter.src );
}
setIsAutoGeneratedChapter( isAutoGeneratedChaptersFile );
} );
} )
.catch( function ( error ) {
// eslint-disable-next-line no-console
console.error( error );
} );
} catch ( error ) {
throw new Error( error?.message ?? error );
}
}, [ chapter, guid, token, isPrivate ] );
const { videoData, isRequestingVideoData, error: syncError } = useSyncMedia(
attributes,
setAttributes,
{
isAutoGeneratedChapter,
}
);
const { filename } = videoData;
// Get video preview status.
const defaultPreview = { html: null, scripts: [], width: null, height: null };
const { preview, isRequestingEmbedPreview } = useSelect(
select => {
if ( ! videoPressUrl ) {
return {
preview: defaultPreview,
isRequestingEmbedPreview: false,
};
}
return {
preview: select( coreStore ).getEmbedPreview( videoPressUrl ) || defaultPreview,
isRequestingEmbedPreview:
select( coreStore ).isRequestingEmbedPreview( videoPressUrl ) || false,
};
},
[ videoPressUrl ]
);
// Pick video properties from preview.
const { html: previewHtml, scripts, width: previewWidth, height: previewHeight } = preview;
/*
* Store the preview markup and video thumbnail image
* into a block `html` and `thumbnail` attributes respectively.
*
* `html` will be used to render the player asap,
* while a fresh preview is going fetched from the server,
* via the core store selectors.
*
* `thumbnail` will be shown as a fallback image
* until the fetching preview process finishes.
*/
useEffect( () => {
if ( ! previewHtml || previewHtml === cacheHtml ) {
return;
}
setAttributes( { cacheHtml: previewHtml } );
}, [ previewHtml, cacheHtml, setAttributes ] );
const html = previewHtml || cacheHtml;
// Store the video ratio to define the initial height of the video.
useEffect( () => {
if ( ! previewWidth || ! previewHeight ) {
return;
}
const ratio = ( previewHeight / previewWidth ) * 100;
if ( ratio === videoRatio ) {
return;
}
setAttributes( { videoRatio: ratio } );
}, [ videoRatio, previewWidth, previewHeight, setAttributes ] );
// Helper to invalidate the preview cache.
const invalidateResolution = useDispatch( coreStore ).invalidateResolution;
const invalidateCachedEmbedPreview = useCallback( () => {
invalidateResolution( 'getEmbedPreview', [ videoPressUrl ] );
}, [ videoPressUrl, invalidateResolution ] );
/*
* Getting VideoPress preview.
* The following code tries to handle issues
* when the preview is not available even when
* the VideoPress URL is gotten.
* It attempts every two seconds to get the so desired video preview.
*/
const [ generatingPreviewCounter, setGeneratingPreviewCounter ] = useState( 0 );
const rePreviewAttemptTimer = useRef< NodeJS.Timeout | void >();
/**
* Clean the generating process timer.
*
* @todo improve doc
*/
function cleanRegeneratingProcessTimer() {
if ( ! rePreviewAttemptTimer?.current ) {
return;
}
/*
* Clean the timer, and updates the reference
* to force a new attempt in case the preview is not available.
*/
rePreviewAttemptTimer.current = clearInterval( rePreviewAttemptTimer.current );
}
useEffect( () => {
if ( generatingPreviewCounter >= VIDEO_PREVIEW_ATTEMPTS_LIMIT ) {
debug( 'Generating preview ➡ attempts number reached out 😪', generatingPreviewCounter );
return cleanRegeneratingProcessTimer();
}
// VideoPress URL is not defined. Bail early and cleans the time.
if ( ! videoPressUrl ) {
debug( 'Generating preview ➡ No URL Provided 👋🏻' );
return cleanRegeneratingProcessTimer();
}
// Bail early (clean the timer) if the preview is already being requested.
if ( isRequestingEmbedPreview ) {
debug( 'Generating preview ➡ Requesting… ⌛' );
return cleanRegeneratingProcessTimer();
}
// Bail early (clean the timer) when preview is defined.
if ( preview.html ) {
debug( 'Generating preview ➡ Preview achieved 🎉 %o', preview );
return cleanRegeneratingProcessTimer();
}
// Bail early when it has been already started.
if ( rePreviewAttemptTimer?.current ) {
debug( 'Generating preview ➡ Process already requested ⌛' );
return;
}
rePreviewAttemptTimer.current = setTimeout( () => {
// Abort whether the preview is already defined.
if ( preview.html ) {
debug( 'Generating preview ➡ Preview already achieved 🎉 %o', preview );
setGeneratingPreviewCounter( 0 ); // reset counter.
return;
}
setGeneratingPreviewCounter( v => v + 1 );
debug(
'Generating preview ➡ Not achieved so far. Start attempt %o 🔥',
generatingPreviewCounter + 1 // +1 because the counter is updated after the effect.
);
invalidateCachedEmbedPreview();
}, 2000 );
return cleanRegeneratingProcessTimer;
}, [
generatingPreviewCounter,
rePreviewAttemptTimer,
invalidateCachedEmbedPreview,
preview,
videoPressUrl,
isRequestingEmbedPreview,
] );
const { className: blockMainClassName, ...blockProps } = useBlockProps( {
className: 'wp-block-jetpack-videopress',
} );
// Setting video media process
const [ isUploadingFile, setIsUploadingFile ] = useState( ! guid );
const [ fileToUpload, setFileToUpload ] = useState( null );
const { replaceBlock } = useDispatch( blockEditorStore );
// Replace video state
const [ isReplacingFile, setIsReplacingFile ] = useState< {
isReplacing: boolean;
prevAttrs: VideoBlockAttributes;
} >( {
isReplacing: false,
prevAttrs: {},
} );
// Cancel replace video handler
const cancelReplacingVideoFile = () => {
setAttributes( isReplacingFile.prevAttrs );
setIsReplacingFile( { isReplacing: false, prevAttrs: {} } );
setIsUploadingFile( false );
};
// Render Example block view
if ( isExample ) {
return (
<img
style={ {
width: '100%',
height: 'auto',
backgroundSize: 'cover',
} }
className="wp-block-jetpack-videopress__example"
src={ src }
alt={ caption }
/>
);
}
// Render uploading block view
if ( isUploadingFile ) {
const handleDoneUpload = newVideoData => {
setIsUploadingFile( false );
if ( isReplacingFile.isReplacing ) {
const newBlockAttributes = {
...attributes,
...newVideoData,
};
// Delete attributes that are not needed.
delete newBlockAttributes.poster;
setIsReplacingFile( { isReplacing: false, prevAttrs: {} } );
replaceBlock( clientId, createBlock( 'videopress/video', newBlockAttributes ) );
return;
}
setAttributes( { id: newVideoData.id, guid: newVideoData.guid, title: newVideoData.title } );
};
return (
<div { ...blockProps } className={ blockMainClassName }>
<VideoPressUploader
setAttributes={ setAttributes }
attributes={ attributes }
handleDoneUpload={ handleDoneUpload }
fileToUpload={ fileToUpload }
isReplacing={ isReplacingFile?.isReplacing }
onReplaceCancel={ cancelReplacingVideoFile }
/>
</div>
);
}
// Generating video preview.
if (
( isRequestingEmbedPreview || ! preview.html ) &&
generatingPreviewCounter > 0 &&
generatingPreviewCounter < VIDEO_PREVIEW_ATTEMPTS_LIMIT
) {
return (
<div { ...blockProps } className={ blockMainClassName }>
<PlaceholderWrapper disableInstructions>
<div className="loading-wrapper">
<Spinner />
{ __( 'Generating preview…', 'jetpack-videopress-pkg' ) }
<strong> { generatingPreviewCounter }</strong>
</div>
</PlaceholderWrapper>
</div>
);
}
// 5 - Generating video preview failed.
if ( generatingPreviewCounter >= VIDEO_PREVIEW_ATTEMPTS_LIMIT && ! preview.html ) {
return (
<div { ...blockProps } className={ blockMainClassName }>
<PlaceholderWrapper
errorMessage={ __(
'Impossible to get a video preview after ten attempts.',
'jetpack-videopress-pkg'
) }
onNoticeRemove={ invalidateResolution }
>
<div className="videopress-uploader__error-actions">
<Button variant="primary" onClick={ invalidateResolution }>
{ __( 'Try again', 'jetpack-videopress-pkg' ) }
</Button>
<Button
variant="secondary"
onClick={ () => {
setAttributes( { src: undefined, id: undefined, guid: undefined } );
} }
>
{ __( 'Cancel', 'jetpack-videopress-pkg' ) }
</Button>
</div>
</PlaceholderWrapper>
</div>
);
}
// Show VideoPress player.
return (
<div
{ ...blockProps }
className={ classNames( blockMainClassName, {
[ `align${ align }` ]: align,
'is-updating-preview': ! previewHtml,
} ) }
>
<BlockControls group="block">
<PosterImageBlockControl
attributes={ attributes }
setAttributes={ setAttributes }
clientId={ clientId }
/>
<TracksControl attributes={ attributes } setAttributes={ setAttributes } />
</BlockControls>
<BlockControls group="other">
<ReplaceControl
setAttributes={ setAttributes }
attributes={ attributes }
onUploadFileStart={ media => {
// Store current attributes in case we wanto to cancel the replacing.
setIsReplacingFile( {
isReplacing: true,
prevAttrs: attributes,
} );
setIsUploadingFile( true );
// Clean relevant attributes to show the uploader placeholder.
setAttributes( { id: null, guid: null, cacheHtml: '', videoRatio: null } );
// Pass, through local state, the new file to upload.
setFileToUpload( media );
} }
onSelectVideoFromLibrary={ media => {
// Depending on the endpoint, `videopress_guid` can be an array or a string.
const mediaGuid = Array.isArray( media.videopress_guid )
? media.videopress_guid[ 0 ]
: media.videopress_guid;
if ( ! mediaGuid ) {
debug( 'No media guid provided' );
return;
}
setAttributes( {
guid: mediaGuid,
id: media.id,
src: media.url,
title: media.title,
description: media.description,
} );
} }
onSelectURL={ videoSource => {
const videoUrlData = buildVideoPressURL( videoSource );
if ( ! videoUrlData ) {
debug( 'Invalid URL. No video GUID provided' );
return;
}
// Update guid based on the URL.
setAttributes( { guid: videoUrlData.guid, src: videoUrlData.url } );
} }
/>
</BlockControls>
<InspectorControls>
<DetailsPanel
filename={ filename }
chapter={ chapter }
isAutoGeneratedChapter={ isAutoGeneratedChapter }
updateError={ syncError }
isRequestingVideoData={ isRequestingVideoData }
{ ...{ attributes, setAttributes } }
/>
<PlaybackPanel { ...{ attributes, setAttributes, isRequestingVideoData } } />
<PrivacyAndRatingPanel { ...{ attributes, setAttributes, isRequestingVideoData } } />
<ColorPanel { ...{ attributes, setAttributes, isRequestingVideoData } } />
</InspectorControls>
<VideoPressPlayer
html={ html }
isRequestingEmbedPreview={ isRequestingEmbedPreview }
scripts={ scripts }
attributes={ attributes }
setAttributes={ setAttributes }
isSelected={ isSelected }
preview={ preview }
/>
</div>
);
}