-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathcontext.js
539 lines (473 loc) · 15.1 KB
/
context.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
* WordPress dependencies
*/
import { createContext, useState, useEffect } from '@wordpress/element';
import { privateApis as blockEditorPrivateApis } from '@wordpress/block-editor';
import { useSelect, useDispatch } from '@wordpress/data';
import {
useEntityRecord,
useEntityRecords,
store as coreStore,
} from '@wordpress/core-data';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import {
fetchGetFontFamilyBySlug,
fetchInstallFontFamily,
fetchUninstallFontFamily,
fetchFontCollections,
fetchFontCollection,
} from './resolvers';
import { unlock } from '../../../lock-unlock';
const { useGlobalSetting } = unlock( blockEditorPrivateApis );
import {
setUIValuesNeeded,
mergeFontFamilies,
loadFontFaceInBrowser,
unloadFontFaceInBrowser,
getDisplaySrcFromFontFace,
makeFontFacesFormData,
makeFontFamilyFormData,
batchInstallFontFaces,
checkFontFaceInstalled,
} from './utils';
import { toggleFont } from './utils/toggleFont';
import setNestedValue from '../../../utils/set-nested-value';
export const FontLibraryContext = createContext( {} );
function FontLibraryProvider( { children } ) {
const { saveEntityRecord } = useDispatch( coreStore );
const { globalStylesId } = useSelect( ( select ) => {
const { __experimentalGetCurrentGlobalStylesId } = select( coreStore );
return { globalStylesId: __experimentalGetCurrentGlobalStylesId() };
} );
const globalStyles = useEntityRecord(
'root',
'globalStyles',
globalStylesId
);
const [ isInstalling, setIsInstalling ] = useState( false );
const [ refreshKey, setRefreshKey ] = useState( 0 );
const refreshLibrary = () => {
setRefreshKey( Date.now() );
};
const { records: libraryPosts = [], isResolving: isResolvingLibrary } =
useEntityRecords( 'postType', 'wp_font_family', {
refreshKey,
_embed: true,
} );
const libraryFonts =
( libraryPosts || [] ).map( ( fontFamilyPost ) => {
return {
id: fontFamilyPost.id,
...fontFamilyPost.font_family_settings,
fontFace:
fontFamilyPost?._embedded?.font_faces.map(
( face ) => face.font_face_settings
) || [],
};
} ) || [];
// Global Styles (settings) font families
const [ fontFamilies, setFontFamilies ] = useGlobalSetting(
'typography.fontFamilies'
);
/*
* Save the font families to the database.
* This function is called when the user activates or deactivates a font family.
* It only updates the global styles post content in the database for new font families.
* This avoids saving other styles/settings changed by the user using other parts of the editor.
*
* It uses the font families from the param to avoid using the font families from an outdated state.
*
* @param {Array} fonts - The font families that will be saved to the database.
*/
const saveFontFamilies = async ( fonts ) => {
// Gets the global styles database post content.
const updatedGlobalStyles = globalStyles.record;
// Updates the database version of global styles with the edited font families in the client.
setNestedValue(
updatedGlobalStyles,
[ 'settings', 'typography', 'fontFamilies' ],
fonts
);
// Saves a new version of the global styles in the database.
await saveEntityRecord( 'root', 'globalStyles', updatedGlobalStyles );
};
// Library Fonts
const [ modalTabOpen, setModalTabOpen ] = useState( false );
const [ libraryFontSelected, setLibraryFontSelected ] = useState( null );
// Themes Fonts are the fonts defined in the global styles (database persisted theme.json data).
const themeFonts = fontFamilies?.theme
? fontFamilies.theme
.map( ( f ) => setUIValuesNeeded( f, { source: 'theme' } ) )
.sort( ( a, b ) => a.name.localeCompare( b.name ) )
: [];
const customFonts = fontFamilies?.custom
? fontFamilies.custom
.map( ( f ) => setUIValuesNeeded( f, { source: 'custom' } ) )
.sort( ( a, b ) => a.name.localeCompare( b.name ) )
: [];
const baseCustomFonts = libraryFonts
? libraryFonts
.map( ( f ) => setUIValuesNeeded( f, { source: 'custom' } ) )
.sort( ( a, b ) => a.name.localeCompare( b.name ) )
: [];
useEffect( () => {
if ( ! modalTabOpen ) {
setLibraryFontSelected( null );
}
}, [ modalTabOpen ] );
const handleSetLibraryFontSelected = ( font ) => {
// If font is null, reset the selected font
if ( ! font ) {
setLibraryFontSelected( null );
return;
}
const fonts = font.source === 'theme' ? themeFonts : baseCustomFonts;
// Tries to find the font in the installed fonts
const fontSelected = fonts.find( ( f ) => f.slug === font.slug );
// If the font is not found (it is only defined in custom styles), use the font from custom styles
setLibraryFontSelected( {
...( fontSelected || font ),
source: font.source,
} );
};
// Demo
const [ loadedFontUrls ] = useState( new Set() );
const getAvailableFontsOutline = ( availableFontFamilies ) => {
const outline = availableFontFamilies.reduce( ( acc, font ) => {
const availableFontFaces =
font?.fontFace && font.fontFace?.length > 0
? font?.fontFace.map(
( face ) => `${ face.fontStyle + face.fontWeight }`
)
: [ 'normal400' ]; // If the font doesn't have fontFace, we assume it is a system font and we add the defaults: normal 400
acc[ font.slug ] = availableFontFaces;
return acc;
}, {} );
return outline;
};
const getActivatedFontsOutline = ( source ) => {
switch ( source ) {
case 'theme':
return getAvailableFontsOutline( themeFonts );
case 'custom':
default:
return getAvailableFontsOutline( customFonts );
}
};
const isFontActivated = ( slug, style, weight, source ) => {
if ( ! style && ! weight ) {
return !! getActivatedFontsOutline( source )[ slug ];
}
return !! getActivatedFontsOutline( source )[ slug ]?.includes(
style + weight
);
};
const getFontFacesActivated = ( slug, source ) => {
return getActivatedFontsOutline( source )[ slug ] || [];
};
async function installFonts( fontFamiliesToInstall ) {
setIsInstalling( true );
try {
const fontFamiliesToActivate = [];
let installationErrors = [];
for ( const fontFamilyToInstall of fontFamiliesToInstall ) {
let isANewFontFamily = false;
// Get the font family if it already exists.
let installedFontFamily = await fetchGetFontFamilyBySlug(
fontFamilyToInstall.slug
);
// Otherwise create it.
if ( ! installedFontFamily ) {
isANewFontFamily = true;
// Prepare font family form data to install.
installedFontFamily = await fetchInstallFontFamily(
makeFontFamilyFormData( fontFamilyToInstall )
);
}
// Collect font faces that have already been installed (to be activated later)
const alreadyInstalledFontFaces =
installedFontFamily.fontFace && fontFamilyToInstall.fontFace
? installedFontFamily.fontFace.filter(
( fontFaceToInstall ) =>
checkFontFaceInstalled(
fontFaceToInstall,
fontFamilyToInstall.fontFace
)
)
: [];
// Filter out Font Faces that have already been installed (so that they are not re-installed)
if (
installedFontFamily.fontFace &&
fontFamilyToInstall.fontFace
) {
fontFamilyToInstall.fontFace =
fontFamilyToInstall.fontFace.filter(
( fontFaceToInstall ) =>
! checkFontFaceInstalled(
fontFaceToInstall,
installedFontFamily.fontFace
)
);
}
// Install the fonts (upload the font files to the server and create the post in the database).
let successfullyInstalledFontFaces = [];
let unsuccessfullyInstalledFontFaces = [];
if ( fontFamilyToInstall?.fontFace?.length > 0 ) {
const response = await batchInstallFontFaces(
installedFontFamily.id,
makeFontFacesFormData( fontFamilyToInstall )
);
successfullyInstalledFontFaces = response?.successes;
unsuccessfullyInstalledFontFaces = response?.errors;
}
// Use the successfully installed font faces
// As well as any font faces that were already installed (those will be activated)
if (
successfullyInstalledFontFaces?.length > 0 ||
alreadyInstalledFontFaces?.length > 0
) {
// Use font data from REST API not from client to ensure
// correct font information is used.
installedFontFamily.fontFace = [
...successfullyInstalledFontFaces,
];
fontFamiliesToActivate.push( installedFontFamily );
}
// If it's a system font but was installed successfully, activate it.
if (
installedFontFamily &&
! fontFamilyToInstall?.fontFace?.length
) {
fontFamiliesToActivate.push( installedFontFamily );
}
// If the font family is new and is not a system font, delete it to avoid having font families without font faces.
if (
isANewFontFamily &&
fontFamilyToInstall?.fontFace?.length > 0 &&
successfullyInstalledFontFaces?.length === 0
) {
await fetchUninstallFontFamily( installedFontFamily.id );
}
installationErrors = installationErrors.concat(
unsuccessfullyInstalledFontFaces
);
}
installationErrors = installationErrors.reduce(
( unique, item ) =>
unique.includes( item.message )
? unique
: [ ...unique, item.message ],
[]
);
if ( fontFamiliesToActivate.length > 0 ) {
// Activate the font family (add the font family to the global styles).
const activeFonts = activateCustomFontFamilies(
fontFamiliesToActivate
);
// Save the global styles to the database.
await saveFontFamilies( activeFonts );
refreshLibrary();
}
if ( installationErrors.length > 0 ) {
const installError = new Error(
__( 'There was an error installing fonts.' )
);
installError.installationErrors = installationErrors;
throw installError;
}
} finally {
setIsInstalling( false );
}
}
async function uninstallFontFamily( fontFamilyToUninstall ) {
try {
// Uninstall the font family.
// (Removes the font files from the server and the posts from the database).
const uninstalledFontFamily = await fetchUninstallFontFamily(
fontFamilyToUninstall.id
);
// Deactivate the font family if delete request is successful
// (Removes the font family from the global styles).
if ( uninstalledFontFamily.deleted ) {
const activeFonts = deactivateFontFamily(
fontFamilyToUninstall
);
// Save the global styles to the database.
await saveFontFamilies( activeFonts );
}
// Refresh the library (the library font families from database).
refreshLibrary();
return uninstalledFontFamily;
} catch ( error ) {
// eslint-disable-next-line no-console
console.error(
`There was an error uninstalling the font family:`,
error
);
throw error;
}
}
const deactivateFontFamily = ( font ) => {
// If the user doesn't have custom fonts defined, include as custom fonts all the theme fonts
// We want to save as active all the theme fonts at the beginning
const initialCustomFonts = fontFamilies?.[ font.source ] ?? [];
const newCustomFonts = initialCustomFonts.filter(
( f ) => f.slug !== font.slug
);
const activeFonts = {
...fontFamilies,
[ font.source ]: newCustomFonts,
};
setFontFamilies( activeFonts );
if ( font.fontFace ) {
font.fontFace.forEach( ( face ) => {
unloadFontFaceInBrowser( face, 'all' );
} );
}
return activeFonts;
};
const activateCustomFontFamilies = ( fontsToAdd ) => {
const fontsToActivate = cleanFontsForSave( fontsToAdd );
const activeFonts = {
...fontFamilies,
// Merge the existing custom fonts with the new fonts.
custom: mergeFontFamilies( fontFamilies?.custom, fontsToActivate ),
};
// Activate the fonts by set the new custom fonts array.
setFontFamilies( activeFonts );
loadFontsInBrowser( fontsToActivate );
return activeFonts;
};
// Removes the id from the families and faces to avoid saving that to global styles post content.
const cleanFontsForSave = ( fonts ) => {
return fonts.map( ( { id: _familyDbId, fontFace, ...font } ) => ( {
...font,
...( fontFace && fontFace.length > 0
? {
fontFace: fontFace.map(
( { id: _faceDbId, ...face } ) => face
),
}
: {} ),
} ) );
};
const loadFontsInBrowser = ( fonts ) => {
// Add custom fonts to the browser.
fonts.forEach( ( font ) => {
if ( font.fontFace ) {
font.fontFace.forEach( ( face ) => {
// Load font faces just in the iframe because they already are in the document.
loadFontFaceInBrowser(
face,
getDisplaySrcFromFontFace( face.src ),
'all'
);
} );
}
} );
};
const toggleActivateFont = ( font, face ) => {
// If the user doesn't have custom fonts defined, include as custom fonts all the theme fonts
// We want to save as active all the theme fonts at the beginning
const initialFonts = fontFamilies?.[ font.source ] ?? [];
// Toggles the received font family or font face
const newFonts = toggleFont( font, face, initialFonts );
// Updates the font families activated in global settings:
setFontFamilies( {
...fontFamilies,
[ font.source ]: newFonts,
} );
const isFaceActivated = isFontActivated(
font.slug,
face?.fontStyle,
face?.fontWeight,
font.source
);
if ( isFaceActivated ) {
unloadFontFaceInBrowser( face, 'all' );
} else {
loadFontFaceInBrowser(
face,
getDisplaySrcFromFontFace( face?.src ),
'all'
);
}
};
const loadFontFaceAsset = async ( fontFace ) => {
// If the font doesn't have a src, don't load it.
if ( ! fontFace.src ) {
return;
}
// Get the src of the font.
const src = getDisplaySrcFromFontFace( fontFace.src );
// If the font is already loaded, don't load it again.
if ( ! src || loadedFontUrls.has( src ) ) {
return;
}
// Load the font in the browser.
loadFontFaceInBrowser( fontFace, src, 'document' );
// Add the font to the loaded fonts list.
loadedFontUrls.add( src );
};
// Font Collections
const [ collections, setFontCollections ] = useState( [] );
const getFontCollections = async () => {
const response = await fetchFontCollections();
setFontCollections( response );
};
const getFontCollection = async ( slug ) => {
try {
const hasData = !! collections.find(
( collection ) => collection.slug === slug
)?.font_families;
if ( hasData ) {
return;
}
const response = await fetchFontCollection( slug );
const updatedCollections = collections.map( ( collection ) =>
collection.slug === slug
? { ...collection, ...response }
: collection
);
setFontCollections( updatedCollections );
} catch ( e ) {
// eslint-disable-next-line no-console
console.error( e );
throw e;
}
};
useEffect( () => {
getFontCollections();
}, [] );
return (
<FontLibraryContext.Provider
value={ {
libraryFontSelected,
handleSetLibraryFontSelected,
fontFamilies,
baseCustomFonts,
isFontActivated,
getFontFacesActivated,
loadFontFaceAsset,
installFonts,
uninstallFontFamily,
toggleActivateFont,
getAvailableFontsOutline,
modalTabOpen,
setModalTabOpen,
refreshLibrary,
saveFontFamilies,
isResolvingLibrary,
isInstalling,
collections,
getFontCollection,
} }
>
{ children }
</FontLibraryContext.Provider>
);
}
export default FontLibraryProvider;