Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ export default function LinkPreview( {
hasRichPreviews = false,
} ) {
// Avoid fetching if rich previews are not desired.
const maybeRemoteURL = hasRichPreviews ? value?.url : null;
const showRichPreviews = hasRichPreviews ? value?.url : null;

const { richData, isFetching } = useRichUrlData( maybeRemoteURL );
const { richData, isFetching } = useRichUrlData( showRichPreviews );

// Rich data may be an empty object so test for that.
const hasRichData = richData && Object.keys( richData ).length;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs, prependHTTP } from '@wordpress/url';
import {
addQueryArgs,
prependHTTP,
isURL,
getProtocol,
isValidProtocol,
} from '@wordpress/url';

/**
* A simple in-memory cache for requests.
Expand All @@ -26,25 +32,43 @@ const CACHE = new Map();
* @param {Object?} options any options to pass to the underlying fetch.
* @example
* ```js
* import { __experimentalFetchRemoteUrlData as fetchRemoteUrlData } from '@wordpress/core-data';
* import { __experimentalFetchUrlData as fetchUrlData } from '@wordpress/core-data';
*
* //...
*
* export function initialize( id, settings ) {
*
* settings.__experimentalFetchRemoteUrlData = (
* settings.__experimentalFetchUrlData = (
* url
* ) => fetchRemoteUrlData( url );
* ) => fetchUrlData( url );
* ```
* @return {Promise< WPRemoteUrlData[] >} Remote URL data.
*/
const fetchRemoteUrlData = async ( url, options = {} ) => {
const fetchUrlData = async ( url, options = {} ) => {
const endpoint = '/__experimental/url-details';

const args = {
url: prependHTTP( url ),
};

if ( ! isURL( url ) ) {
return Promise.reject( `${ url } is not a valid URL.` );
}

// Test for "http" based URL as it is possible for valid
// yet unusable URLs such as `tel:123456` to be passed.
const protocol = getProtocol( url );

if (
! isValidProtocol( protocol ) ||
! protocol.startsWith( 'http' ) ||
! /^https?:\/\/[^\/\s]/i.test( url )
) {
return Promise.reject(
`${ url } does not have a valid protocol. URLs must be "http" based`
);
}

if ( CACHE.has( url ) ) {
return CACHE.get( url );
}
Expand All @@ -58,4 +82,4 @@ const fetchRemoteUrlData = async ( url, options = {} ) => {
} );
};

export default fetchRemoteUrlData;
export default fetchUrlData;
2 changes: 1 addition & 1 deletion packages/core-data/src/fetch/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { default as __experimentalFetchLinkSuggestions } from './__experimental-fetch-link-suggestions';
export { default as __experimentalFetchRemoteUrlData } from './__experimental-fetch-remote-url-data';
export { default as __experimentalFetchUrlData } from './__experimental-fetch-url-data';
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
/**
* Internal dependencies
*/
import fetchRemoteUrlData from '../__experimental-fetch-remote-url-data';
import fetchUrlData from '../__experimental-fetch-url-data';
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';

jest.mock( '@wordpress/api-fetch' );

describe( 'fetchRemoteUrlData', () => {
describe( 'fetchUrlData', () => {
afterEach( () => {
apiFetch.mockReset();
} );
Expand All @@ -26,7 +26,7 @@ describe( 'fetchRemoteUrlData', () => {
apiFetch.mockReturnValueOnce( Promise.resolve( data ) );

await expect(
fetchRemoteUrlData( 'https://www.wordpress.org' )
fetchUrlData( 'https://www.wordpress.org' )
).resolves.toEqual( data );

expect( apiFetch ).toBeCalledTimes( 1 );
Expand All @@ -36,7 +36,7 @@ describe( 'fetchRemoteUrlData', () => {
apiFetch.mockReturnValueOnce( Promise.reject( 'fetch failed' ) );

await expect(
fetchRemoteUrlData( 'https://www.wordpress.org/1' )
fetchUrlData( 'https://www.wordpress.org/1' )
).rejects.toEqual( 'fetch failed' );
} );
} );
Expand All @@ -45,7 +45,7 @@ describe( 'fetchRemoteUrlData', () => {
it( 'passes options argument through to fetch API', async () => {
apiFetch.mockReturnValueOnce( Promise.resolve() );

await fetchRemoteUrlData( 'https://www.wordpress.org/2', {
await fetchUrlData( 'https://www.wordpress.org/2', {
method: 'POST',
} );

Expand Down Expand Up @@ -73,19 +73,15 @@ describe( 'fetchRemoteUrlData', () => {
};
apiFetch.mockReturnValueOnce( Promise.resolve( data ) );

await expect( fetchRemoteUrlData( targetUrl ) ).resolves.toEqual(
data
);
await expect( fetchUrlData( targetUrl ) ).resolves.toEqual( data );
expect( apiFetch ).toBeCalledTimes( 1 );

// Allow us to reassert on calls without it being polluted by first fetch
// but retains the mock implementation from earlier.
apiFetch.mockClear();

// Fetch the same URL again...should be cached.
await expect( fetchRemoteUrlData( targetUrl ) ).resolves.toEqual(
data
);
await expect( fetchUrlData( targetUrl ) ).resolves.toEqual( data );

// Should now be in cache so no need to refetch from API.
expect( apiFetch ).toBeCalledTimes( 0 );
Expand All @@ -105,17 +101,47 @@ describe( 'fetchRemoteUrlData', () => {
.mockReturnValueOnce( Promise.reject( 'fetch failed' ) )
.mockReturnValueOnce( Promise.resolve( data ) );

await expect( fetchRemoteUrlData( targetUrl ) ).rejects.toEqual(
await expect( fetchUrlData( targetUrl ) ).rejects.toEqual(
'fetch failed'
);

// Cache should not store the previous failed fetch and should retry
// with a new fetch.
await expect( fetchRemoteUrlData( targetUrl ) ).resolves.toEqual(
data
);
await expect( fetchUrlData( targetUrl ) ).resolves.toEqual( data );

expect( apiFetch ).toBeCalledTimes( 2 );
} );
} );

describe( 'URL validation', () => {
it.each( [ '#internal-link' ] )(
'errors when an invalid URL is passed',
async ( targetUrl ) => {
expect( apiFetch ).toBeCalledTimes( 0 );

await expect( fetchUrlData( targetUrl ) ).rejects.toEqual(
expect.stringContaining(
`${ targetUrl } is not a valid URL.`
)
);
}
);
it.each( [
'tel:123456',
'ftp://something',
'mailto:example@wordpress.org',
'file:somefilehere',
] )(
'errors when a non-http protocol (%s) is passed as part of URL',
async ( targetUrl ) => {
expect( apiFetch ).toBeCalledTimes( 0 );

await expect( fetchUrlData( targetUrl ) ).rejects.toEqual(
expect.stringContaining(
`${ targetUrl } does not have a valid protocol.`
)
);
}
);
} );
} );
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,20 @@ import { pick, defaultTo } from 'lodash';
/**
* WordPress dependencies
*/
import { Platform, useMemo, useCallback } from '@wordpress/element';
import { Platform, useMemo } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import {
store as coreStore,
__experimentalFetchLinkSuggestions as fetchLinkSuggestions,
__experimentalFetchRemoteUrlData as fetchRemoteUrlData,
__experimentalFetchUrlData as fetchUrlData,
} from '@wordpress/core-data';
import {
getAuthority,
isURL,
getProtocol,
isValidProtocol,
} from '@wordpress/url';

/**
* Internal dependencies
*/
import { mediaUpload } from '../../utils';
import { store as editorStore } from '../../store';

const EMPTY_DATA = {};

/**
* React hook used to compute the block editor settings to use for the post editor.
*
Expand All @@ -41,8 +33,6 @@ function useBlockEditorSettings( settings, hasTemplate ) {
reusableBlocks,
hasUploadPermissions,
canUseUnfilteredHTML,
baseUrl,
hasResolvedLocalSiteData,
} = useSelect( ( select ) => {
const { canUserUseUnfilteredHTML } = select( editorStore );
const isWeb = Platform.OS === 'web';
Expand Down Expand Up @@ -76,54 +66,6 @@ function useBlockEditorSettings( settings, hasTemplate ) {

const { undo } = useDispatch( editorStore );

// Temporary home - should this live in `core-data`?
const fetchRichUrlData = useCallback(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This intermediary function is no longer required as we will be allowing rich previews for internal URLs as well as external.

function ( url, fetchOptions = {} ) {
if ( ! isURL( url ) ) {
return Promise.reject(
new TypeError( `${ url } is not a valid URL.` )
);
}

// Test for "http" based URL as it is possible for valid
// yet unusable URLs such as `tel:123456` to be passed.
const protocol = getProtocol( url );

if (
! isValidProtocol( protocol ) ||
! protocol.startsWith( 'http' ) ||
! /^https?:\/\/[^\/\s]/i.test( url )
) {
return Promise.reject(
new TypeError( `${ url } does not have a valid protocol.` )
);
}

// If the baseUrl is still resolving then return
// empty data for this request.
if ( ! hasResolvedLocalSiteData ) {
return Promise.resolve( EMPTY_DATA );
}

// More accurate test for internal URLs to avoid edge cases
// such as baseURL being included as part of a query string
// on the target url.
const baseUrlAuthority = getAuthority( baseUrl );
const urlAuthority = getAuthority( url );

const isInternal = urlAuthority === baseUrlAuthority;

// Don't handle internal URLs (yet...).
if ( isInternal ) {
return Promise.resolve( EMPTY_DATA );
}

// If external then attempt fetch of data.
return fetchRemoteUrlData( url, fetchOptions );
},
[ baseUrl, hasResolvedLocalSiteData ]
);

return useMemo(
() => ( {
...pick( settings, [
Expand Down Expand Up @@ -170,7 +112,7 @@ function useBlockEditorSettings( settings, hasTemplate ) {
__experimentalReusableBlocks: reusableBlocks,
__experimentalFetchLinkSuggestions: ( search, searchOptions ) =>
fetchLinkSuggestions( search, searchOptions, settings ),
__experimentalFetchRichUrlData: fetchRichUrlData,
__experimentalFetchRichUrlData: fetchUrlData,
__experimentalCanUserUseUnfilteredHTML: canUseUnfilteredHTML,
__experimentalUndo: undo,
outlineMode: hasTemplate,
Expand Down