-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
71 lines (60 loc) · 1.64 KB
/
index.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
/**
* WordPress dependencies
*/
import { useState, useMemo, useCallback } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import { getDisplaySrcFromFontFace, loadFontFaceInBrowser } from './utils';
import { store as editorStore } from '../../store';
function useEditorFontsResolver() {
const [ loadedFontUrls, setLoadedFontUrls ] = useState( new Set() );
const { currentTheme = {}, fontFamilies = [] } = useSelect( ( select ) => {
return {
currentTheme:
select( editorStore ).getSettings()?.__experimentalFeatures
?.currentTheme,
fontFamilies:
select( editorStore ).getSettings()?.__experimentalFeatures
?.typography?.fontFamilies,
};
}, [] );
const fontFaces = useMemo( () => {
return Object.values( fontFamilies )
.flat()
.map( ( family ) => family.fontFace )
.filter( Boolean )
.flat();
}, [ fontFamilies ] );
const loadFontFaceAsset = useCallback(
async ( fontFace, ownerDocument ) => {
if ( ! fontFace.src ) {
return;
}
const src = getDisplaySrcFromFontFace(
fontFace.src,
currentTheme?.stylesheet_uri
);
if ( ! src || loadedFontUrls.has( src ) ) {
return;
}
loadFontFaceInBrowser( fontFace, src, ownerDocument );
setLoadedFontUrls( ( prevUrls ) => new Set( prevUrls ).add( src ) );
},
[ currentTheme, loadedFontUrls ]
);
return useCallback(
( node ) => {
if ( ! node ) {
return;
}
const { ownerDocument } = node;
fontFaces.forEach( ( fontFace ) =>
loadFontFaceAsset( fontFace, ownerDocument )
);
},
[ fontFaces, loadFontFaceAsset ]
);
}
export default useEditorFontsResolver;