-
Notifications
You must be signed in to change notification settings - Fork 769
Expand file tree
/
Copy pathconvert.js
More file actions
187 lines (158 loc) · 6.85 KB
/
convert.js
File metadata and controls
187 lines (158 loc) · 6.85 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const svgr = require("@svgr/core");
const fs = require("fs");
const path = require("path");
const process = require("process");
const argv = require("yargs").boolean("selector").default("selector", false).argv;
const _ = require("lodash");
const SRC_PATH = argv.source;
const DEST_PATH = argv.dest;
const TSX_EXTENSION = '.tsx'
if (!SRC_PATH) {
throw new Error("Icon source folder not specified by --source");
}
if (!DEST_PATH) {
throw new Error("Output destination folder not specified by --dest");
}
if (!fs.existsSync(DEST_PATH)) {
fs.mkdirSync(DEST_PATH);
}
processFiles(SRC_PATH, DEST_PATH)
function processFiles(src, dest) {
/** @type string[] */
const indexContents = [];
// make file for resizeable icons
const iconPath = path.join(dest, 'icons')
const iconContents = processFolder(src, dest, true)
if (fs.existsSync(iconPath)) {
fs.rmSync(iconPath, { recursive: true, force: true } );
}
fs.mkdirSync(iconPath);
iconContents.forEach((chunk, i) => {
const chunkFileName = `chunk-${i}`
const chunkPath = path.resolve(iconPath, `${chunkFileName}.tsx`);
indexContents.push(`export * from './icons/${chunkFileName}'`);
fs.writeFileSync(chunkPath, chunk, (err) => {
if (err) throw err;
});
});
// make file for sized icons
const sizedIconPath = path.join(dest, 'sizedIcons');
const sizedIconContents = processFolder(src, dest, false)
if (fs.existsSync(sizedIconPath)) {
fs.rmSync(sizedIconPath, { recursive: true, force: true } );
}
fs.mkdirSync(sizedIconPath);
sizedIconContents.forEach((chunk, i) => {
const chunkFileName = `chunk-${i}`
const chunkPath = path.resolve(sizedIconPath, `${chunkFileName}.tsx`);
indexContents.push(`export * from './sizedIcons/${chunkFileName}'`);
fs.writeFileSync(chunkPath, chunk, (err) => {
if (err) throw err;
});
});
const indexPath = path.join(dest, 'index.tsx')
// Finally add the interface definition and then write out the index.
indexContents.push('export type { FluentIconsProps } from \'./utils/FluentIconsProps.types\'');
indexContents.push('export { default as wrapIcon } from \'./utils/wrapIcon\'');
indexContents.push('export { default as bundleIcon } from \'./utils/bundleIcon\'');
indexContents.push('export * from \'./utils/useIconState\'');
indexContents.push('export * from \'./utils/constants\'');
indexContents.push('export { IconContextProvider, useIconContext } from \'./contexts/index\'');
indexContents.push('export type { IconContextValue } from \'./contexts/index\'');
fs.writeFileSync(indexPath, indexContents.join('\n'), (err) => {
if (err) throw err;
});
}
/**
* Process a folder of svg files and convert them to React components, following naming patterns for the FluentUI System Icons
* @param {string} srcPath
* @param {boolean} resizable
* @returns { string [] } - chunked icon files to insert
*/
function processFolder(srcPath, destPath, resizable) {
var files = fs.readdirSync(srcPath)
// These options will be passed to svgr/core
// See https://react-svgr.com/docs/options/ for more info
var svgrOpts = {
template: fileTemplate,
expandProps: 'start', // HTML attributes/props for things like accessibility can be passed in, and will be expanded on the svg object at the start of the object
svgProps: { className: '{className}'}, // In order to provide styling, className will be used
replaceAttrValues: { '#212121': '{primaryFill}' }, // We are designating primaryFill as the primary color for filling. If not provided, it defaults to null.
typescript: true,
icon: true
}
var svgrOptsSizedIcons = {
template: fileTemplate,
expandProps: 'start', // HTML attributes/props for things like accessibility can be passed in, and will be expanded on the svg object at the start of the object
svgProps: { className: '{className}'}, // In order to provide styling, className will be used
replaceAttrValues: { '#212121': '{primaryFill}' }, // We are designating primaryFill as the primary color for filling. If not provided, it defaults to null.
typescript: true
}
/** @type string[] */
const iconExports = [];
files.forEach(function (file, index) {
var srcFile = path.join(srcPath, file)
if (fs.lstatSync(srcFile).isDirectory()) {
// for now, ignore subdirectories/localization, until we have a plan for handling it
// Will likely involve appending the lang/locale to the end of the friendly name for the unique component name
// var joinedDestPath = path.join(destPath, file)
// if (!fs.existsSync(joinedDestPath)) {
// fs.mkdirSync(joinedDestPath);
// }
// indexContents += processFolder(srcFile, joinedDestPath)
} else {
if(resizable && !file.includes("20")) {
return
}
var iconName = file.substr(0, file.length - 4) // strip '.svg'
iconName = iconName.replace("ic_fluent_", "") // strip ic_fluent_
iconName = resizable ? iconName.replace("20", "") : iconName
var destFilename = _.camelCase(iconName) // We want them to be camelCase, so access_time would become accessTime here
destFilename = destFilename.replace(destFilename.substring(0, 1), destFilename.substring(0, 1).toUpperCase()) // capitalize the first letter
/**
* This is a placeholder to add the check to see if the icon should be autoflipped
*
* var shouldAutoFlip = shouldFlip(rtlFile);
*/
var iconContent = fs.readFileSync(srcFile, { encoding: "utf8" })
var jsxCode = resizable ? svgr.default.sync(iconContent, svgrOpts, { filePath: file }) : svgr.default.sync(iconContent, svgrOptsSizedIcons, { filePath: file })
var jsCode =
`
export const ${destFilename} = (props: FluentIconsProps) => {
const { fill: primaryFill = 'currentColor', className } = props;
const state = useIconState(props);
${shouldAutoFlip ? 'useAutoFlippingIconStyles(state);' : ''}
return ${jsxCode};
}
${destFilename}.displayName = '${destFilename}';
`
iconExports.push(jsCode);
}
});
// chunk all icons into separate files to keep build reasonably fast
/** @type string[][] */
const iconChunks = [];
while(iconExports.length > 0) {
iconChunks.push(iconExports.splice(0, 500));
}
for(const chunk of iconChunks) {
chunk.unshift(`import { FluentIconsProps } from "../utils/FluentIconsProps.types";`)
chunk.unshift(`import * as React from "react";`)
}
/** @type string[] */
const chunkContent = iconChunks.map(chunk => chunk.join('\n'));
return chunkContent;
}
function fileTemplate(
{ template },
opts,
{ imports, interfaces, componentName, props, jsx, exports }
) {
const plugins = ['jsx', 'typescript']
const tpl = template.smart({ plugins })
componentName.name = componentName.name.substring(3)
componentName.name = componentName.name.replace('IcFluent', '')
return jsx;
}