@@ -14,33 +14,42 @@ import AmpPreviewButton from '../components/amp-preview-button';
14
14
*/
15
15
function WrappedAmpPreviewButton ( ) {
16
16
const root = useRef ( null ) ;
17
- const postPublishButton = useRef ( null ) ;
17
+ const referenceNode = useRef ( null ) ;
18
18
19
19
const isViewable = useSelect (
20
20
( select ) => select ( 'core' ) . getPostType ( select ( 'core/editor' ) . getEditedPostAttribute ( 'type' ) ) ?. viewable ,
21
21
[ ] ,
22
22
) ;
23
23
24
24
useEffect ( ( ) => {
25
- if ( ! root . current && ! postPublishButton . current ) {
26
- postPublishButton . current = document . querySelector ( '.editor-post-publish-button' ) ;
25
+ if ( ! root . current && ! referenceNode . current ) {
26
+ // At first, we try finding the post preview button that is visible only on small screens.
27
+ // If found, we will use its next sibling so that `insertBefore` gets us to the exact location
28
+ // we are looking for.
29
+ referenceNode . current = document . querySelector ( '.editor-post-preview' ) ?. nextSibling ;
27
30
28
- // Insert the AMP preview button immediately after the post preview button.
29
- if ( postPublishButton . current ) {
31
+ // Since the mobile post preview button is rendered with a delay, we are using the post publish/update
32
+ // button as a fallback. Because it is rendered early, our AMP preview button will be visible immediately.
33
+ if ( ! referenceNode . current ) {
34
+ referenceNode . current = document . querySelector ( '.editor-post-publish-button' ) ;
35
+ }
36
+
37
+ if ( referenceNode . current ) {
30
38
root . current = document . createElement ( 'div' ) ;
31
39
root . current . className = 'amp-wrapper-post-preview' ;
32
- postPublishButton . current . parentNode . insertBefore ( root . current , postPublishButton . current ) ;
40
+ referenceNode . current . parentNode . insertBefore ( root . current , referenceNode . current ) ;
33
41
}
34
42
}
35
43
36
44
return ( ) => {
37
- if ( postPublishButton . current && root . current ) {
38
- postPublishButton . current . parentNode . removeChild ( root . current ) ;
45
+ if ( referenceNode . current && root . current ) {
46
+ referenceNode . current . parentNode . removeChild ( root . current ) ;
39
47
root . current = null ;
40
- postPublishButton . current = null ;
48
+ referenceNode . current = null ;
41
49
}
42
50
} ;
43
- } , [ ] ) ;
51
+ // We use `isViewable` as a dependency in order to reposition the preview button once the block editor is fully loaded.
52
+ } , [ isViewable ] ) ;
44
53
45
54
// It is unlikely that AMP would be enabled for a non-viewable post type. This is why the Preview button will
46
55
// always be displayed initially (when `isViewable` is undefined), preventing horizontal layout shift.
0 commit comments