Skip to content

Commit

Permalink
Implement retrieval of the post type for each smart link
Browse files Browse the repository at this point in the history
  • Loading branch information
vaurdan committed May 14, 2024
1 parent a6b0314 commit 3056819
Show file tree
Hide file tree
Showing 10 changed files with 227 additions and 49 deletions.
55 changes: 52 additions & 3 deletions src/Endpoints/content-helper/class-smart-linking-endpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,18 @@ public function __construct( Parsely $parsely ) {
* @return bool
*/
public function is_available_to_current_user( $request = null ): bool {
if ( ! $request ) {
if ( null === $request ) {
return false;
}

$post_id = $request->get_param( 'post_id' );

// Check if the current user has edit capabilities for the post.
$can_edit = current_user_can( 'edit_post', $post_id );
if ( $post_id ) {
// Check if the current user has edit capabilities for the post.
$can_edit = current_user_can( 'edit_post', $post_id );
} else {
$can_edit = current_user_can( 'edit_posts' );
}

// Check if the current user has the smart linking capability.
$has_capability = current_user_can(
Expand All @@ -74,6 +78,11 @@ public function is_available_to_current_user( $request = null ): bool {
}

public function run(): void {
$this->register_endpoint(
static::ENDPOINT . '/url-to-post-type',
'url_to_post_type',
array( 'POST' )
);
// Endpoint "[post-id]/set"
/*$this->register_endpoint(
static::ENDPOINT . '/(?P<post_id>\d+)/set',
Expand Down Expand Up @@ -103,6 +112,46 @@ public function run(): void {
'callback' => array( $this, 'add_smart_link' ),
'permission_callback' => array( $this, 'is_available_to_current_user' ),
));

}

public function url_to_post_type( WP_REST_Request $request ): WP_REST_Response {
$url = $request->get_param( 'url' );

if ( ! is_string( $url ) ) {
return new WP_REST_Response( array(
'error' => array(
'name' => 'invalid_request',
'message' => 'Invalid request body.',
),
), 400 );
}

$post_id = 0;

if ( ( $cache = wp_cache_get( $url, 'wp_parsely_smart_link_url_to_postid' ) ) === false ) {
$post_id = $cache;
} else if ( function_exists( 'wpcom_vip_url_to_postid' ) ) {
$post_id = wpcom_vip_url_to_postid( $url );
} else {
$post_id = url_to_postid( $url ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.url_to_postid_url_to_postid
}

if ( 0 === $post_id ) {
return new WP_REST_Response( array(
'error' => array(
'name' => 'invalid_url',
'message' => 'Invalid URL',
),
), 400 );
}

return new WP_REST_Response( array(
'data' => array(
'post_id' => $post_id,
'post_type' => get_post_type( $post_id ),
),
), 200 );
}

public function set_smart_links( WP_REST_Request $request ): string {
Expand Down
61 changes: 52 additions & 9 deletions src/Models/class-smart-link.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ class Smart_Link extends Base_Model {
*/
public $applied;

/**
* The post type of the suggested link.
*
* @var string The post type of the suggested link.
*/
public $post_type;

/**
* Smart Link constructor.
*
Expand All @@ -84,9 +91,49 @@ public function __construct( string $href, string $title, string $text, int $off
$this->offset = $offset;
$this->applied = false;

$this->post_id = $this->get_post_id_by_url( $href );

if ( false === $this->post_id ) {
$this->post_type = 'external';
} else {
$post_type = get_post_type( $this->post_id );
if ( false !== $post_type ) {
$this->post_type = $post_type;
} else {
$this->post_type = 'external';
}
}

parent::__construct();
}

/**
* Gets the post ID by URL.
*
* @since 3.15.0
*
* @param string $url The URL to get the post ID for.
* @return int|false The post ID of the URL, false if not found.
*/
private function get_post_id_by_url( string $url ) {
if ( ( $cache = wp_cache_get( $url, 'wp_parsely_smart_link_url_to_postid' ) ) === false ) {
return $cache;
}

if ( function_exists( 'wpcom_vip_url_to_postid' ) ) {
$post_id = wpcom_vip_url_to_postid( $url );
} else {
$post_id = url_to_postid( $url ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.url_to_postid_url_to_postid
}

if ( 0 === $post_id ) {
return false;
}

wp_cache_set( $url, $post_id, 'wp_parsely_smart_link_url_to_postid' );
return $post_id;
}

/**
* Generates a unique ID for the suggested link.
*
Expand All @@ -107,23 +154,19 @@ protected function generate_uid(): string {
*
* @since 3.15.0
*
* @return string The serialized model.
* @return array<mixed> The serialized model.
*/
public function to_array(): array {
$json = array (
return array (
'uid' => $this->uid,
'href' => $this->href,
'title' => $this->title,
'text' => $this->text,
'offset' => $this->offset,
'applied' => $this->applied
'applied' => $this->applied,
'post_type' => $this->post_type,
'post_id' => $this->post_id,
);

if ( false === $json ) {
$json = '{}';
}

return $json;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/content-helper/common/icons/ai-icon.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Path, SVG } from '@wordpress/components';

export const AiIcon = ( { size = 24, className = 'wp-parsely-icon' }: { size?: number, className: string } ): JSX.Element => {
export const AiIcon = ( { size = 24, className = 'wp-parsely-icon' }: { size?: number, className?: string } ): JSX.Element => {
return (
<SVG xmlns="http://www.w3.org/2000/svg"
className={ className }
Expand Down
11 changes: 1 addition & 10 deletions src/content-helper/editor-sidebar/smart-linking/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ export const SmartLinkingPanel = ( {
const [ numAddedLinks, setNumAddedLinks ] = useState<number>( 0 );
const [ isReviewDone, setIsReviewDone ] = useState<boolean>( false );
const [ isReviewModalOpen, setIsReviewModalOpen ] = useState<boolean>( false );
const [ isManageButtonVisible, setIsManageButtonVisible ] = useState<boolean>( false );

const { createNotice } = useDispatch( 'core/notices' );

Expand All @@ -111,7 +110,6 @@ export const SmartLinkingPanel = ( {
retrying,
retryAttempt,
smartLinks,
getSmartLinksFn,
} = useSelect( ( selectFn ) => {
const {
isReady,
Expand Down Expand Up @@ -143,7 +141,6 @@ export const SmartLinkingPanel = ( {
retrying: isRetrying(),
retryAttempt: getRetryAttempt(),
smartLinks: getSmartLinks(),
getSmartLinksFn: getSmartLinks,
};
}, [] );

Expand Down Expand Up @@ -181,7 +178,7 @@ export const SmartLinkingPanel = ( {
addSmartLinks( existingSmartLinks );
setIsReady( true );
}
}, [ ready, setIsReady ] );
}, [ addSmartLinks, ready, setIsReady ] );

/**
* Handles the ending of the review process.
Expand Down Expand Up @@ -659,12 +656,6 @@ export const SmartLinkingPanel = ( {
onClose={ () => {
setIsReviewDone( true );
setIsReviewModalOpen( false );

if ( getSmartLinksFn().length > 0 ) {
setIsManageButtonVisible( true );
} else {
setIsManageButtonVisible( false );
}
} }
/>
) }
Expand Down
14 changes: 14 additions & 0 deletions src/content-helper/editor-sidebar/smart-linking/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export type SmartLink = {
offset: number;
applied: boolean;
match?: SmartLinkMatch;
post_id?: number|false;
post_type?: string;
};

/**
Expand Down Expand Up @@ -279,4 +281,16 @@ export class SmartLinkingProvider extends BaseProvider {

return response;
}

public async getPostTypeByURL( url: string ): Promise<string> {
const response = await this.fetch<{ post_type: string }>( {
method: 'POST',
path: '/wp-parsely/v1/smart-linking/url-to-post-type',
data: {
url,
},
} );

return response.post_type;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,13 @@ const SmartLinkingReviewModalComponent = ( {
const {
smartLinks,
suggestedLinks,
getSmartLinks,
} = useSelect( ( selectFn ) => {
// eslint-disable-next-line @typescript-eslint/no-shadow
const { getSmartLinks, getSuggestedLinks } = selectFn( SmartLinkingStore );
return {
smartLinks: getSmartLinks(),
getSmartLinks,
suggestedLinks: getSuggestedLinks,
};
}, [] );
Expand All @@ -70,10 +73,7 @@ const SmartLinkingReviewModalComponent = ( {
useEffect( () => {
if ( isModalOpen && smartLinks.length === 0 ) {
onClose();
return;
}

setSelectedLink( smartLinks[ 0 ] );
}, [ isModalOpen, onClose, smartLinks ] );

const showConfirmCloseDialog = () => setShowCloseDialog( true );
Expand Down Expand Up @@ -116,12 +116,6 @@ const SmartLinkingReviewModalComponent = ( {

// Update the block.
dispatch( 'core/block-editor' ).updateBlock( blockId, block );

// Notify the API that the link was applied.
//if ( postId ) {
// const addedLink = await SmartLinkingProvider.getInstance().addSmartLink( postId, linkSuggestion );
// console.log( addedLink );
//}
};

/**
Expand All @@ -147,7 +141,9 @@ const SmartLinkingReviewModalComponent = ( {
}

// Select anchors by 'data-smartlink' attribute matching the UID.
const anchors = Array.from( contentElement.querySelectorAll( `a[data-smartlink="${ linkSuggestion.uid }"]` ) );
const anchors = Array.from(
contentElement.querySelectorAll( `a[data-smartlink="${ linkSuggestion.uid }"]` ),
);

// Check if we found the anchor with the specified UID.
if ( anchors.length > 0 ) {
Expand Down Expand Up @@ -223,14 +219,14 @@ const SmartLinkingReviewModalComponent = ( {
};

const handlePrevious = () => {
const currentIndex = smartLinks.indexOf( selectedLink );
const currentIndex = getSmartLinks().indexOf( selectedLink );
const previousIndex = currentIndex - 1;

if ( ! smartLinks[ previousIndex ] ) {
if ( ! getSmartLinks()[ previousIndex ] ) {
return;
}

setSelectedLink( smartLinks[ previousIndex ] );
setSelectedLink( getSmartLinks()[ previousIndex ] );
};

/**
Expand Down Expand Up @@ -300,7 +296,20 @@ const SmartLinkingReviewModalComponent = ( {

const block = select( 'core/block-editor' ).getBlock( selectedLink.match.blockId );
if ( block ) {
let currentSmartLinks = getSmartLinks();

// Get the selected link index, and set the selected link as the previous one, or the first one if no previous.
const currentIndex = currentSmartLinks.indexOf( selectedLink );
const previousIndex = currentIndex - 1;

removeLinkFromBlock( block, selectedLink );

currentSmartLinks = getSmartLinks();
if ( currentSmartLinks[ previousIndex ] ) {
setSelectedLink( currentSmartLinks[ previousIndex ] );
} else {
setSelectedLink( currentSmartLinks[ 0 ] );
}
}
};

Expand Down Expand Up @@ -363,8 +372,8 @@ const SmartLinkingReviewModalComponent = ( {
/>
<ReviewSuggestion
link={ selectedLink }
hasNext={ smartLinks.indexOf( selectedLink ) < smartLinks.length - 1 }
hasPrevious={ smartLinks.indexOf( selectedLink ) > 0 }
hasNext={ getSmartLinks().indexOf( selectedLink ) < getSmartLinks().length - 1 }
hasPrevious={ getSmartLinks().indexOf( selectedLink ) > 0 }
onNext={ handleNext }
onPrevious={ handlePrevious }
onAccept={ onAcceptHandler }
Expand Down Expand Up @@ -405,4 +414,3 @@ const SmartLinkingReviewModalComponent = ( {
};

export const SmartLinkingReviewModal = memo( SmartLinkingReviewModalComponent );

0 comments on commit 3056819

Please sign in to comment.