Skip to content

Commit

Permalink
Font Library: Load/Unload the font face in browser when toggling the …
Browse files Browse the repository at this point in the history
…variants
  • Loading branch information
arthur791004 committed Feb 15, 2024
1 parent e3f3c3d commit d12325c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
setUIValuesNeeded,
mergeFontFamilies,
loadFontFaceInBrowser,
unloadFontFaceInBrowser,
getDisplaySrcFromFontFace,
makeFontFacesFormData,
makeFontFamilyFormData,
Expand Down Expand Up @@ -410,6 +411,23 @@ function FontLibraryProvider( { children } ) {
...fontFamilies,
[ font.source ]: newFonts,
} );

const activatedFont = newFonts.find( ( f ) => f.slug === font.slug );
const isFaceActivated = activatedFont?.fontFace?.find(
( f ) =>
f.fontWeight === face.fontWeight &&
f.fontStyle === face.fontStyle
);
if ( isFaceActivated ) {
// Load font faces just in the iframe because they already are in the document.
loadFontFaceInBrowser(
face,
getDisplaySrcFromFontFace( face.src ),
'all'
);
} else {
unloadFontFaceInBrowser( face, 'all' );
}
};

const loadFontFaceAsset = async ( fontFace ) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,38 @@ export async function loadFontFaceInBrowser( fontFace, source, addTo = 'all' ) {
}
}

/*
* Unloads the font face and remove it from the browser.
* It also removes it from the iframe document.
*
* Note that Font faces that were added to the set using the CSS @font-face rule
* remain connected to the corresponding CSS, and cannot be deleted.
*/
export function unloadFontFaceInBrowser( fontFace, addTo = 'all' ) {
const unloadFontFace = ( fonts ) => {
fonts.forEach( ( f ) => {
if (
f.family === fontFace.fontFamily &&
f.weight === fontFace.fontWeight &&
f.style === fontFace.fontStyle
) {
fonts.delete( f );
}
} );
};

if ( addTo === 'document' || addTo === 'all' ) {
unloadFontFace( document.fonts );
}

if ( addTo === 'iframe' || addTo === 'all' ) {
const iframeDocument = document.querySelector(
'iframe[name="editor-canvas"]'
).contentDocument;
unloadFontFace( iframeDocument.fonts );
}
}

export function getDisplaySrcFromFontFace( input, urlPrefix ) {
if ( ! input ) {
return;
Expand Down

0 comments on commit d12325c

Please sign in to comment.