-
Notifications
You must be signed in to change notification settings - Fork 4k
/
upload-fonts.js
220 lines (206 loc) · 5.88 KB
/
upload-fonts.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
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import {
__experimentalSpacer as Spacer,
__experimentalText as Text,
__experimentalVStack as VStack,
Button,
DropZone,
Notice,
FormFileUpload,
FlexItem,
privateApis as componentsPrivateApis,
} from '@wordpress/components';
import { useContext, useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import { ALLOWED_FILE_EXTENSIONS } from './utils/constants';
import { FontLibraryContext } from './context';
import { Font } from '../../../../lib/lib-font.browser';
import makeFamiliesFromFaces from './utils/make-families-from-faces';
import { loadFontFaceInBrowser } from './utils';
import { unlock } from '../../../lock-unlock';
const { ProgressBar } = unlock( componentsPrivateApis );
function UploadFonts() {
const { installFont, notice, setNotice } = useContext( FontLibraryContext );
const [ isUploading, setIsUploading ] = useState( false );
const handleDropZone = ( files ) => {
handleFilesUpload( files );
};
const onFilesUpload = ( event ) => {
handleFilesUpload( event.target.files );
};
/**
* Filters the selected files to only allow the ones with the allowed extensions
*
* @param {Array} files The files to be filtered
* @return {void}
*/
const handleFilesUpload = ( files ) => {
setNotice( null );
setIsUploading( true );
const uniqueFilenames = new Set();
const selectedFiles = [ ...files ];
const allowedFiles = selectedFiles.filter( ( file ) => {
if ( uniqueFilenames.has( file.name ) ) {
return false; // Discard duplicates
}
// Eliminates files that are not allowed
const fileExtension = file.name.split( '.' ).pop().toLowerCase();
if ( ALLOWED_FILE_EXTENSIONS.includes( fileExtension ) ) {
uniqueFilenames.add( file.name );
return true; // Keep file if the extension is allowed
}
return false; // Discard file extension not allowed
} );
if ( allowedFiles.length > 0 ) {
loadFiles( allowedFiles );
} else {
setNotice( {
type: 'error',
message: __( 'No fonts found to install.' ),
} );
setIsUploading( false );
}
};
/**
* Loads the selected files and reads the font metadata
*
* @param {Array} files The files to be loaded
* @return {void}
*/
const loadFiles = async ( files ) => {
const fontFacesLoaded = await Promise.all(
files.map( async ( fontFile ) => {
const fontFaceData = await getFontFaceMetadata( fontFile );
await loadFontFaceInBrowser(
fontFaceData,
fontFaceData.file,
'all'
);
return fontFaceData;
} )
);
handleInstall( fontFacesLoaded );
};
// Create a function to read the file as array buffer
async function readFileAsArrayBuffer( file ) {
return new Promise( ( resolve, reject ) => {
const reader = new window.FileReader();
reader.readAsArrayBuffer( file );
reader.onload = () => resolve( reader.result );
reader.onerror = reject;
} );
}
const getFontFaceMetadata = async ( fontFile ) => {
const buffer = await readFileAsArrayBuffer( fontFile );
const fontObj = new Font( 'Uploaded Font' );
fontObj.fromDataBuffer( buffer, fontFile.name );
// Assuming that fromDataBuffer triggers onload event and returning a Promise
const onloadEvent = await new Promise(
( resolve ) => ( fontObj.onload = resolve )
);
const font = onloadEvent.detail.font;
const { name } = font.opentype.tables;
const fontName = name.get( 16 ) || name.get( 1 );
const isItalic = name.get( 2 ).toLowerCase().includes( 'italic' );
const fontWeight =
font.opentype.tables[ 'OS/2' ].usWeightClass || 'normal';
const isVariable = !! font.opentype.tables.fvar;
const weightAxis =
isVariable &&
font.opentype.tables.fvar.axes.find(
( { tag } ) => tag === 'wght'
);
const weightRange = weightAxis
? `${ weightAxis.minValue } ${ weightAxis.maxValue }`
: null;
return {
file: fontFile,
fontFamily: fontName,
fontStyle: isItalic ? 'italic' : 'normal',
fontWeight: weightRange || fontWeight,
};
};
/**
* Creates the font family definition and sends it to the server
*
* @param {Array} fontFaces The font faces to be installed
* @return {void}
*/
const handleInstall = async ( fontFaces ) => {
const fontFamilies = makeFamiliesFromFaces( fontFaces );
if ( fontFamilies.length > 1 ) {
setNotice( {
type: 'error',
message: __(
'Variants from only one font family can be uploaded at a time.'
),
} );
setIsUploading( false );
return;
}
try {
await installFont( fontFamilies[ 0 ] );
setNotice( {
type: 'success',
message: __( 'Fonts were installed successfully.' ),
} );
} catch ( error ) {
setNotice( {
type: 'error',
message: error.message,
} );
}
setIsUploading( false );
};
return (
<div className="font-library-modal__tabpanel-layout">
<DropZone onFilesDrop={ handleDropZone } />
<VStack className="font-library-modal__local-fonts">
{ notice && (
<Notice
status={ notice.type }
onRemove={ () => setNotice( null ) }
>
{ notice.message }
</Notice>
) }
{ isUploading && (
<FlexItem>
<div className="font-library-modal__upload-area">
<ProgressBar />
</div>
</FlexItem>
) }
{ ! isUploading && (
<FormFileUpload
accept={ ALLOWED_FILE_EXTENSIONS.map(
( ext ) => `.${ ext }`
).join( ',' ) }
multiple={ true }
onChange={ onFilesUpload }
render={ ( { openFileDialog } ) => (
<Button
className="font-library-modal__upload-area"
onClick={ openFileDialog }
>
{ __( 'Upload font' ) }
</Button>
) }
/>
) }
<Spacer margin={ 2 } />
<Text className="font-library-modal__upload-area__text">
{ __(
'Uploaded fonts appear in your library and can be used in your theme. Supported formats: .tff, .otf, .woff, and .woff2.'
) }
</Text>
</VStack>
</div>
);
}
export default UploadFonts;