-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Edit Site: Enable link viewer template navigation.
- Loading branch information
Showing
3 changed files
with
95 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
packages/edit-site/src/components/navigate-to-link/index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
/** | ||
* WordPress dependencies | ||
*/ | ||
import { useState, useEffect, useMemo } from '@wordpress/element'; | ||
import { select } from '@wordpress/data'; | ||
import { Button } from '@wordpress/components'; | ||
import { __ } from '@wordpress/i18n'; | ||
|
||
/** | ||
* Browser dependencies | ||
*/ | ||
const { fetch } = window; | ||
|
||
export default function NavigateToLink( { | ||
url, | ||
templateIds, | ||
activeId, | ||
onActiveIdChange, | ||
} ) { | ||
const [ templateId, setTemplateId ] = useState(); | ||
useEffect( () => { | ||
const effect = async () => { | ||
try { | ||
const { success, data } = await fetch( | ||
`${ url }?_wp-find-template` | ||
).then( ( res ) => res.json() ); | ||
if ( success ) { | ||
let newTemplateId = data.ID; | ||
if ( newTemplateId === null ) { | ||
const { getEntityRecord } = select( 'core' ); | ||
newTemplateId = templateIds | ||
.map( ( id ) => getEntityRecord( 'postType', 'wp_template', id ) ) | ||
.find( ( template ) => template.slug === data.post_name ).id; | ||
} | ||
setTemplateId( newTemplateId ); | ||
} else { | ||
throw new Error(); | ||
} | ||
} catch ( err ) { | ||
setTemplateId( null ); | ||
} | ||
}; | ||
effect(); | ||
}, [ url, templateIds ] ); | ||
const onClick = useMemo( () => { | ||
if ( ! templateId || templateId === activeId ) { | ||
return null; | ||
} | ||
return () => onActiveIdChange( templateId ); | ||
}, [ templateId, activeId, onActiveIdChange ] ); | ||
return ( | ||
onClick && ( | ||
<Button | ||
icon="welcome-write-blog" | ||
label={ __( 'Edit Page Template' ) } | ||
onClick={ onClick } | ||
/> | ||
) | ||
); | ||
} |