-
Notifications
You must be signed in to change notification settings - Fork 4k
/
listener-hooks.js
82 lines (75 loc) · 2.14 KB
/
listener-hooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* WordPress dependencies
*/
import { useSelect, useDispatch } from '@wordpress/data';
import { useEffect, useRef } from '@wordpress/element';
import { store as blockEditorStore } from '@wordpress/block-editor';
import { store as editorStore } from '@wordpress/editor';
import { store as preferencesStore } from '@wordpress/preferences';
/**
* Internal dependencies
*/
import {
STORE_NAME,
VIEW_AS_LINK_SELECTOR,
VIEW_AS_PREVIEW_LINK_SELECTOR,
} from '../../store/constants';
/**
* This listener hook monitors for block selection and triggers the appropriate
* sidebar state.
*
* @param {number} postId The current post id.
*/
export const useBlockSelectionListener = ( postId ) => {
const { hasBlockSelection, isEditorSidebarOpened, isDistractionFree } =
useSelect(
( select ) => {
const { get } = select( preferencesStore );
return {
hasBlockSelection:
!! select( blockEditorStore ).getBlockSelectionStart(),
isEditorSidebarOpened:
select( STORE_NAME ).isEditorSidebarOpened(),
isDistractionFree: get( 'core', 'distractionFree' ),
};
},
[ postId ]
);
const { openGeneralSidebar } = useDispatch( STORE_NAME );
useEffect( () => {
if ( ! isEditorSidebarOpened || isDistractionFree ) {
return;
}
if ( hasBlockSelection ) {
openGeneralSidebar( 'edit-post/block' );
} else {
openGeneralSidebar( 'edit-post/document' );
}
}, [ hasBlockSelection, isEditorSidebarOpened ] );
};
/**
* This listener hook monitors any change in permalink and updates the view
* post link in the admin bar.
*
* @param {number} postId
*/
export const useUpdatePostLinkListener = ( postId ) => {
const { newPermalink } = useSelect(
( select ) => ( {
newPermalink: select( editorStore ).getCurrentPost().link,
} ),
[ postId ]
);
const nodeToUpdate = useRef();
useEffect( () => {
nodeToUpdate.current =
document.querySelector( VIEW_AS_PREVIEW_LINK_SELECTOR ) ||
document.querySelector( VIEW_AS_LINK_SELECTOR );
}, [ postId ] );
useEffect( () => {
if ( ! newPermalink || ! nodeToUpdate.current ) {
return;
}
nodeToUpdate.current.setAttribute( 'href', newPermalink );
}, [ newPermalink ] );
};