Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | import jetpackAnalytics from '@automattic/jetpack-analytics';
import apiFetch from '@wordpress/api-fetch';
import { dispatch, select } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
import { GOOGLE_PHOTOS_PICKER_SESSION } from '../constants';
import { store as mediaStore } from '../store';
import { PickerSession } from '../store/types';
import { waitFor } from '../utils/wait-for';
import { MediaSource } from './types';
// Pexels constants
const PEXELS_ID = 'pexels';
const PEXELS_NAME = __( 'Pexels free photos', 'jetpack-external-media' );
const PEXELS_SEARCH_PLACEHOLDER = __( 'Search Pexels free photos', 'jetpack-external-media' );
const DEFAULT_PEXELS_SEARCH: MediaSearch = {
per_page: 10,
search: 'mountain',
};
// Google Photos constants
const GOOGLE_PHOTOS_ID = 'google_photos';
const GOOGLE_PHOTOS_NAME = __( 'Google Photos', 'jetpack-external-media' );
const GOOGLE_PHOTOS_SEARCH_PLACEHOLDER = __( 'Search Google Photos', 'jetpack-external-media' );
const DEFAULT_GOOGLE_PHOTOS_SEARCH: MediaSearch = {
per_page: 25,
search: '',
};
/**
* External media endpoints.
*/
enum WpcomMediaEndpoints {
List = '/wpcom/v2/external-media/list/',
}
/**
* WPCOM media type of the WPCOM Media Api.
*/
enum WpcomMediaItemType {
Image = 'image',
Video = 'video',
}
/**
* Gutenberg media category search DTO.
*/
type MediaSearch = {
per_page: number;
search: string;
};
/**
* Gutenberg media item DTO.
*/
type MediaItem = {
caption: string;
previewUrl: string;
title: string;
url: string;
};
/**
* WPCOM media list item DTO.
*/
type WpcomMediaItem = {
URL: string;
caption: string;
// Sometimes the title is null, so we need to handle that case.
title: string | null;
name: string | null;
file: string;
thumbnails: {
thumbnail: string;
};
type: WpcomMediaItemType;
};
/**
* WPCOM media list response DTO.
*/
type WpcomMediaResponse = {
found: number;
media: WpcomMediaItem[];
};
/**
* wpCookies global variable.
*/
declare global {
interface Window {
wpCookies: {
set: ( name: string, value: string, expires: number, path: string, domain?: string ) => void;
get: ( name: string ) => string | null;
remove: ( name: string, path: string, domain?: string ) => void;
};
}
}
const wpCookies = window.wpCookies;
/**
* Get media URL for a given MediaSource.
*
* @param {MediaSource} source - MediaSource to get URL for.
* @param {MediaSearch} mediaSearch - MediaCategorySearch to filter for.
* @return {string} Media URL.
*/
const getMediaApiUrl = ( source: MediaSource, mediaSearch: MediaSearch ) =>
addQueryArgs( `${ WpcomMediaEndpoints.List }${ source }`, {
...( mediaSearch.search && { search: mediaSearch.search } ),
number: mediaSearch.per_page || 25,
path: 'recent',
} );
/**
* Maps a WPCOM media item to a Gutenberg media item.
*
* @param {WpcomMediaItem} item - WPCOM media list item to map.
* @return {MediaItem} Mapped media category item.
*/
const mapWpcomMediaToMedia = ( item: WpcomMediaItem ): MediaItem => ( {
caption: item?.caption ?? '',
previewUrl: item.thumbnails.thumbnail,
title: item?.title ?? item?.name ?? item.file,
url: item.URL,
} );
/**
* Builds a Gutenberg media category object.
*
* @param {string} name - Name of the media category.
* @param {string} label - Label of the media category.
* @param {string} searchPlaceholder - Search placeholder of the media category.
* @param {MediaSource} source - MediaSource of the media category.
* @param {MediaSearch} defaultSearch - Default search of the media category.
* @return {object} Media category object.
*/
const buildMediaCategory = (
name: string,
label: string,
searchPlaceholder: string,
source: MediaSource,
defaultSearch: MediaSearch
) => ( {
name: name,
labels: {
name: label,
search_items: searchPlaceholder,
},
mediaType: 'image',
fetch: async ( mediaCategorySearch: MediaSearch ) =>
await apiFetch( {
path: getMediaApiUrl( source, {
per_page: defaultSearch.per_page,
search:
mediaCategorySearch?.search === '' ? defaultSearch.search : mediaCategorySearch.search,
} ),
method: 'GET',
} )
.then( ( response: WpcomMediaResponse ) => {
const mediaItems = response.media
.filter( wpcomMediaItem => wpcomMediaItem.type === WpcomMediaItemType.Image )
.map( mapWpcomMediaToMedia );
jetpackAnalytics.tracks.recordEvent( 'jetpack_editor_media_inserter_external_source', {
media_source: source.toString(),
results: mediaItems.length,
search:
mediaCategorySearch?.search === '' ? defaultSearch.search : mediaCategorySearch.search,
} );
return mediaItems;
} )
// Null object pattern, we don't want to break if the API fails.
.catch( () => [] ),
getReportUrl: null,
isExternalResource: true,
} );
/**
* Get Google Photos media category.
*
* @return {object} Google Photos media category.
*/
const googlePhotosProvider = () =>
buildMediaCategory(
GOOGLE_PHOTOS_ID,
GOOGLE_PHOTOS_NAME,
GOOGLE_PHOTOS_SEARCH_PLACEHOLDER,
MediaSource.GooglePhotos,
DEFAULT_GOOGLE_PHOTOS_SEARCH
);
/**
* Checks if a given MediaSource is connected and calls the callback with the response.
*
* @param {MediaSource} source - MediaSource to check.
* @return {void}
*/
const isMediaSourceConnected = async ( source: MediaSource ) =>
apiFetch< boolean | WpcomMediaResponse >( {
path: getMediaApiUrl( source, DEFAULT_PEXELS_SEARCH ),
method: 'GET',
} )
.then( response => response )
.catch( () => false );
/**
* Checks if the inserter is opened.
*
* @return {boolean} True if the inserter is opened false otherwise.
*/
const isInserterOpened = (): boolean => {
const editorIsInserterOpened = select( 'core/editor' ).isInserterOpened?.();
// The widgets editor doesn't use the `core/editor` store, so check is separately.
return editorIsInserterOpened || select( 'core/edit-widgets' )?.isInserterOpened();
};
const registerInInserter = ( mediaCategoryProvider: () => object ) =>
// Remove as soon @types/wordpress__block-editor is up to date
// eslint-disable-next-line
// @ts-ignore
dispatch( 'core/block-editor' )?.registerInserterMediaCategory?.( mediaCategoryProvider() );
/**
* Get Pexels media category.
*
* @return {object} Pexels media category.
*/
const pexelsProvider = () =>
buildMediaCategory(
PEXELS_ID,
PEXELS_NAME,
PEXELS_SEARCH_PLACEHOLDER,
MediaSource.Pexels,
DEFAULT_PEXELS_SEARCH
);
/**
* Checks if a given MediaSource is authenticated in the store.
*
* @param {MediaSource} source - MediaSource to check.
* @return {boolean} True if the MediaSource is authenticated false otherwise.
*/
const isAuthenticatedByWithMediaComponent = ( source: MediaSource ) =>
!! select( mediaStore ).isAuthenticated( source );
/**
* Adds Google Photos to the media inserter if/when it's connected.
* We will not remove Google Photos from the inserter if the user disconnects Google Photos during runtime.
*/
export const addGooglePhotosToMediaInserter = async () => {
waitFor( isInserterOpened ).then( async () => {
const isConnected = await isMediaSourceConnected( MediaSource.GooglePhotos );
if ( isConnected ) {
registerInInserter( googlePhotosProvider );
return;
}
waitFor( () => isAuthenticatedByWithMediaComponent( MediaSource.GooglePhotos ) ).then( () =>
registerInInserter( googlePhotosProvider )
);
} );
};
/**
* Adds Pexels to the media inserter. There is no need to check if it's connected because it's always connected.
*/
export const addPexelsToMediaInserter = () => {
waitFor( isInserterOpened ).then( () => registerInInserter( pexelsProvider ) );
};
/**
* Authenticates a given MediaSource.
*
* @param {MediaSource} source - MediaSource to authenticate.
* @param {boolean} isAuthenticated - True if the MediaSource is authenticated false otherwise.
*/
export const authenticateMediaSource = ( source: MediaSource, isAuthenticated: boolean ) => {
dispatch( mediaStore ).setAuthenticated( source, isAuthenticated );
};
/**
* Set Google Photos Picker session
* @param {PickerSession} session - Media URL.
*/
export const setGooglePhotosPickerSession = ( session: PickerSession ) => {
setGooglePhotosPickeCachedSessionId( session?.id || null );
dispatch( mediaStore ).mediaPhotosPickerSessionSet( session );
};
/**
* Set Google Photos Picker session id to cookies
* @param {string|null} sessionId - Session id
*/
export const setGooglePhotosPickeCachedSessionId = ( sessionId: string | null ) => {
const domain = `.${ window.location.hostname.split( '.' ).slice( -2 ).join( '.' ) }`;
if ( ! sessionId ) {
wpCookies.remove( GOOGLE_PHOTOS_PICKER_SESSION, '/', domain );
return;
}
wpCookies.set(
GOOGLE_PHOTOS_PICKER_SESSION,
sessionId,
604800, // 7 days
'/',
domain
);
};
/**
* Get Google Photos Picker session id from cookies
* @return {string | null} Google Photos Picker session id
*/
export const getGooglePhotosPickerCachedSessionId = () => {
return wpCookies.get( GOOGLE_PHOTOS_PICKER_SESSION );
};
|