UNPKG

2.63 kBJavaScriptView Raw
1import addToMapSet from './add-to-map-set.js'
2import morphFontAsReactDom from './morph/react-dom/morph-font.js'
3import morphFontAsReactNative from './morph/react-native/morph-fonts.js'
4import path from 'path'
5import sort from 'bubblesort'
6import relativise from './relativise.js'
7import ensureDir from './ensure-dir.js'
8
9let morphFont = {
10 'react-dom': morphFontAsReactDom,
11 'react-native': morphFontAsReactNative,
12 'react-pdf': morphFontAsReactNative,
13}
14
15export async function ensureFontsDirectory(src) {
16 await ensureDir(path.join(src, 'DesignSystem', 'Fonts'))
17}
18
19export let getFontId = file => path.basename(file, path.extname(file))
20
21let fontsOrder = ['eot', 'woff2', 'woff', 'ttf', 'svg', 'otf']
22
23let sortFonts = fonts => {
24 return new Set(
25 sort(
26 [...fonts],
27 (a, b) => fontsOrder.indexOf(b.type) - fontsOrder.indexOf(a.type)
28 )
29 )
30}
31
32export function processCustomFonts({ customFonts, filesFontCustom }) {
33 for (let file of filesFontCustom) {
34 addToMapSet(customFonts, getFontId(file), file)
35 }
36 for (let [id, fonts] of customFonts) {
37 customFonts.set(id, sortFonts(fonts))
38 }
39}
40
41export function morphAllFonts({
42 as,
43 customFonts,
44 filesView,
45 src,
46 viewsToFiles,
47}) {
48 let fontsDirectory = path.join(src, 'DesignSystem', 'Fonts')
49 let fontsInUse = new Set()
50
51 let mapCustomFont = file => ({
52 type: FONT_TYPES[path.extname(file)],
53 file: file.replace(fontsDirectory, '.'),
54 })
55
56 for (let file of filesView) {
57 let view = viewsToFiles.get(file)
58
59 if (view.custom) continue
60
61 view.parsed.fonts.forEach(font => {
62 fontsInUse.add(font.id)
63 })
64 }
65
66 return [...fontsInUse].map(font => {
67 let [family, weight, style = 'normal'] = font.split('-')
68
69 let customFontSources = []
70 if (customFonts.has(font)) {
71 customFontSources = [...customFonts.get(font)].map(mapCustomFont)
72 }
73
74 return {
75 file: path.join(src, 'DesignSystem', 'Fonts', `${font}.js`),
76 content: morphFont[as](
77 {
78 id: font,
79 family,
80 style,
81 weight,
82 },
83 customFontSources
84 ),
85 }
86 })
87}
88
89// let removeFont = file => {
90// let id = getFontId(file)
91// instance.customFonts = instance.customFonts.filter(font => font.id !== id)
92// }
93
94let FONT_TYPES = {
95 '.otf': 'opentype',
96 '.eot': 'eot',
97 '.svg': 'svg',
98 '.ttf': 'truetype',
99 '.woff': 'woff',
100 '.woff2': 'woff2',
101}
102
103export let makeGetFontImport = src => (font, view) =>
104 `import "${relativise(
105 view.file,
106 path.join(src, 'DesignSystem', 'Fonts', `${font}.js`)
107 )}"`
108
109// let isFont = f => Object.keys(FONT_TYPES).includes(path.extname(f))