Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New block: Link Preview #47765

Open
wants to merge 9 commits into
base: trunk
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions docs/reference-guides/core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,15 @@ Display a list of your most recent posts. ([Source](https://github.com/WordPress
- **Supports:** align, anchor, color (background, gradients, link, text), spacing (margin, padding), typography (fontSize, lineHeight), ~~html~~
- **Attributes:** addLinkToFeaturedImage, categories, columns, displayAuthor, displayFeaturedImage, displayPostContent, displayPostContentRadio, displayPostDate, excerptLength, featuredImageAlign, featuredImageSizeHeight, featuredImageSizeSlug, featuredImageSizeWidth, order, orderBy, postLayout, postsToShow, selectedAuthor

## Link preview

A link with a preview of the destination site. ([Source](https://github.com/WordPress/gutenberg/tree/trunk/packages/block-library/src/link-preview))

- **Name:** core/link-preview
- **Category:** embed
- **Supports:**
- **Attributes:** description, icon, image, title, url

## List

Create a bulleted or numbered list. ([Source](https://github.com/WordPress/gutenberg/tree/trunk/packages/block-library/src/list))
Expand Down
1 change: 1 addition & 0 deletions packages/block-library/src/embed/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ const EmbedEdit = ( props ) => {
tryAgain={ () => {
invalidateResolution( 'getEmbedPreview', [ url ] );
} }
onReplace={ onReplace }
/>
</View>
);
Expand Down
14 changes: 14 additions & 0 deletions packages/block-library/src/embed/embed-placeholder.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { __, _x } from '@wordpress/i18n';
import { Button, Placeholder, ExternalLink } from '@wordpress/components';
import { BlockIcon } from '@wordpress/block-editor';
import { createBlock } from '@wordpress/blocks';

const EmbedPlaceholder = ( {
icon,
Expand All @@ -14,6 +15,7 @@ const EmbedPlaceholder = ( {
cannotEmbed,
fallback,
tryAgain,
onReplace,
} ) => {
return (
<Placeholder
Expand Down Expand Up @@ -56,6 +58,18 @@ const EmbedPlaceholder = ( {
</Button>{ ' ' }
<Button variant="secondary" onClick={ fallback }>
{ _x( 'Convert to link', 'button label' ) }
</Button>{ ' ' }
<Button
variant="secondary"
onClick={ () => {
onReplace(
createBlock( 'core/link-preview', {
url: value,
} )
);
} }
>
{ _x( 'Convert to link preview', 'button label' ) }
</Button>
</div>
) }
Expand Down
2 changes: 2 additions & 0 deletions packages/block-library/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import * as html from './html';
import * as image from './image';
import * as latestComments from './latest-comments';
import * as latestPosts from './latest-posts';
import * as linkPreview from './link-preview';
import * as list from './list';
import * as listItem from './list-item';
import * as logInOut from './loginout';
Expand Down Expand Up @@ -128,6 +129,7 @@ const getAllBlocks = () =>
image,
heading,
gallery,
linkPreview,
list,
listItem,
quote,
Expand Down
30 changes: 30 additions & 0 deletions packages/block-library/src/link-preview/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 2,
"name": "core/link-preview",
"title": "Link preview",
"category": "embed",
"description": "A link with a preview of the destination site.",
"textdomain": "default",
"attributes": {
"url": {
"type": "string",
"default": "",
"__experimentalRole": "content"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"icon": {
"type": "string"
},
"image": {
"type": "string"
}
},
"editorStyle": "wp-block-link-preview-editor",
"style": "wp-block-link-preview"
}
26 changes: 26 additions & 0 deletions packages/block-library/src/link-preview/content.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export function Content( { props, attributes } ) {
const { url, title, image, icon } = attributes;
if ( ! url ) return null;
return (
<a
{ ...props }
href={ url }
className={
image ? props.className + ' has-image' : props.className
}
>
{ image && <img src={ image } alt={ title } /> }
<div>
<strong>{ title }</strong>
{ icon && (
<img
className="link-preview__icon"
src={ icon }
alt={ new URL( url ).host }
/>
) }
{ new URL( url ).host.replace( /^www\./, '' ) }
</div>
</a>
);
}
131 changes: 131 additions & 0 deletions packages/block-library/src/link-preview/edit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* WordPress dependencies
*/
import { __, _x } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';
import { useBlockProps, BlockControls } from '@wordpress/block-editor';
import { __experimentalFetchUrlData } from '@wordpress/core-data';
import {
Placeholder,
Spinner,
Button,
ToolbarGroup,
ToolbarButton,
Notice,
} from '@wordpress/components';
import { link, edit } from '@wordpress/icons';

/**
* Internal dependencies
*/
import { Content } from './content';

export default function LinkPreviewEdit( props ) {
const { attributes, setAttributes } = props;
const { url, title } = attributes;
const [ isFetching, setIsFetching ] = useState( false );
const [ isEditingUrl, setIsEditingUrl ] = useState( ! url );
const [ urlValue, setURLValue ] = useState( url );
const [ hasError, setHasError ] = useState( false );

const blockProps = useBlockProps( {
onClick: isEditingUrl
? undefined
: ( event ) => {
event.preventDefault();
},
} );

useEffect( () => {
if ( url && ! title ) {
setIsFetching( true );
__experimentalFetchUrlData( url )
.catch( () => {
setHasError( true );
} )
getdave marked this conversation as resolved.
Show resolved Hide resolved
.then( ( data ) => {
if ( ! data || ! data.title ) {
setHasError( true );
} else {
setHasError( false );
setIsEditingUrl( false );
setAttributes( {
Copy link
Member

Choose a reason for hiding this comment

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

I think we also need a couple of things if this effect is required.

  • Add __unstableMarkNextChangeAsNotPersistent before setAttributes to prevent "undo traps".
  • Add a cleanup function to prevent race conditions and memory leaks. Don't update states if the component is already unmounted.

title: data.title,
icon: data.icon,
image: data.image,
description: data.description,
} );
}
} )
.finally( () => {
setIsFetching( false );
} );
}
}, [ url, title, setAttributes ] );

if ( isEditingUrl || hasError ) {
return (
<div { ...blockProps }>
<Placeholder
icon={ link }
label={ __( 'URL' ) }
instructions={ __(
'Paste a link to the content you want to display on your site.'
) }
>
{ hasError && (
<Notice status="error" isDismissible={ false }>
{ __( 'No data found for this URL.' ) }
</Notice>
) }
<form
onSubmit={ ( event ) => {
event.preventDefault();
setAttributes( {
url: urlValue,
title: '',
icon: '',
image: '',
description: '',
} );
} }
>
<input
type="url"
value={ urlValue }
className="components-placeholder__input"
aria-label={ __( 'URL' ) }
placeholder={ __( 'Enter URL to embed here…' ) }
onChange={ ( event ) => {
setURLValue( event.target.value );
} }
/>
getdave marked this conversation as resolved.
Show resolved Hide resolved
<Button variant="primary" type="submit">
{ _x( 'Embed', 'button label' ) }
</Button>
{ isFetching && <Spinner /> }
</form>
</Placeholder>
</div>
);
}

return (
<>
<BlockControls>
<ToolbarGroup>
<ToolbarButton
className="components-toolbar__control"
label={ __( 'Edit URL' ) }
icon={ edit }
onClick={ () => {
setIsEditingUrl( true );
setURLValue( url );
} }
/>
</ToolbarGroup>
</BlockControls>
<Content props={ blockProps } attributes={ attributes } />
</>
);
}
25 changes: 25 additions & 0 deletions packages/block-library/src/link-preview/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Internal dependencies
*/
import initBlock from '../utils/init-block';
import edit from './edit';
import save from './save';
import metadata from './block.json';
import transforms from './transforms';

/**
* WordPress dependencies
*/
import { link } from '@wordpress/icons';

const { name } = metadata;
export { metadata, name };

export const settings = {
icon: link,
edit,
save,
transforms,
};

export const init = () => initBlock( { name, metadata, settings } );
6 changes: 6 additions & 0 deletions packages/block-library/src/link-preview/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import { init } from './';

export default init();
17 changes: 17 additions & 0 deletions packages/block-library/src/link-preview/save.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* WordPress dependencies
*/
import { useBlockProps } from '@wordpress/block-editor';

/**
* Internal dependencies
*/
import { Content } from './content';

export default function save( { attributes } ) {
if ( ! attributes.url ) {
return null;
}

return <Content props={ useBlockProps.save() } attributes={ attributes } />;
}
38 changes: 38 additions & 0 deletions packages/block-library/src/link-preview/style.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
a.wp-block-link-preview {
display: block;
border: 1px solid #d3d3d3;
border-radius: 2px;
font-size: smaller;

&.has-image {
height: 100px;
}

strong {
display: block;
}

> div {
padding: 1em;
}

.link-preview__icon {
height: 1em;
width: 1em;
margin-right: 0.25em;
}

> img {
float: right;
max-width: 50%;
height: 100%;
}


}

.wp-block-link-preview {
.components-notice {
margin: 0 0 1em 0;
}
}
44 changes: 44 additions & 0 deletions packages/block-library/src/link-preview/transforms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* WordPress dependencies
*/
import { createBlock } from '@wordpress/blocks';

/**
* Default transforms for generic embeds.
*/
const transforms = {
Copy link
Contributor

Choose a reason for hiding this comment

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

I tried pasting https://aheadcreative.com into the editor canvas and it turned it into an embed block. I couldn't see how to get the link preview block to work.

Copy link
Member Author

Choose a reason for hiding this comment

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

Oh, I've not added that yet. When should we convert a pasted link to a link preview? When it fails to embed?

Copy link
Contributor

Choose a reason for hiding this comment

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

If that can be achieved then yes that would seem logical 👍

to: [
{
type: 'block',
blocks: [ 'core/paragraph' ],
isMatch: ( { url } ) => !! url,
transform: ( { url } ) => {
return createBlock( 'core/paragraph', {
content: `<a href="${ url }">${ url }</a>`,
} );
},
},
{
type: 'block',
blocks: [ 'core/embed' ],
transform: ( { url } ) => {
return createBlock( 'core/embed', {
url,
} );
},
},
],
from: [
{
type: 'block',
blocks: [ 'core/embed' ],
transform: ( { url } ) => {
return createBlock( 'core/link-preview', {
url,
} );
},
},
],
};

export default transforms;
Loading