-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
554 lines (487 loc) · 19.1 KB
/
Copy pathbuild.js
File metadata and controls
554 lines (487 loc) · 19.1 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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import StyleDictionary from 'style-dictionary';
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
// Strips "px" or "%" units from token values and returns a plain number string.
const toNumber = (val) => parseFloat(String(val).replace('px', '').replace('%', ''));
const hexToRGB = (hex) => {
const h = hex.replace('#', '');
return {
r: (parseInt(h.slice(0, 2), 16) / 255).toFixed(3),
g: (parseInt(h.slice(2, 4), 16) / 255).toFixed(3),
b: (parseInt(h.slice(4, 6), 16) / 255).toFixed(3),
};
};
const fileHeader = (filename) =>
`//
// ${filename}
// MDS
//
// Auto-generated by Style Dictionary. Do not edit manually.
//
import UIKit
`;
StyleDictionary.registerFormat({
name: 'ios/swift-color-base',
format: ({ dictionary }) => {
let output = fileHeader('BaseColor.swift');
output += '// MARK: - Base Color\n\n';
output += '@_spi(MDSCatalog) public enum BaseColor {\n';
for (const token of dictionary.allTokens) {
const colorName = token.path[2];
const shade = token.path[token.path.length - 1];
const hex = token.$value ?? token.value;
const { r, g, b } = hexToRGB(hex);
output += ` public static let ${colorName}${shade} = UIColor(red: ${r}, green: ${g}, blue: ${b}, alpha: 1)\n`;
}
output += '}\n';
return output;
}
});
StyleDictionary.registerFormat({
name: 'ios/swift-typography',
format: ({ dictionary }) => {
let output = fileHeader('BaseTypography.swift');
output += '// MARK: - Base Typography\n\n';
output += '@_spi(MDSCatalog) public enum BaseTypography {\n';
const groups = {};
for (const token of dictionary.allTokens) {
const cat = token.path[2];
if (!groups[cat]) groups[cat] = [];
groups[cat].push(token);
}
for (const [cat, tokens] of Object.entries(groups)) {
output += `\n // MARK: ${capitalize(cat)}\n`;
output += ` public enum ${capitalize(cat)} {\n`;
for (const token of tokens) {
const last = token.path[token.path.length - 1];
let name;
if (cat === 'size' || cat === 'lineHeight') {
name = last;
} else if (last === 'default') {
name = '`default`';
} else {
name = last;
}
output += ` public static let ${name}: CGFloat = ${toNumber(token.$value ?? token.value)}\n`;
}
output += ` }\n`;
}
output += '}\n';
return output;
}
});
StyleDictionary.registerFormat({
name: 'ios/swift-spacing',
format: ({ dictionary }) => {
let output = fileHeader('BaseSpacing.swift');
output += '// MARK: - Base Spacing\n\n';
output += 'public enum BaseSpacing {\n';
const groups = {};
for (const token of dictionary.allTokens) {
const cat = token.path[1];
if (!groups[cat]) groups[cat] = [];
groups[cat].push(token);
}
for (const [cat, tokens] of Object.entries(groups)) {
output += `\n // MARK: ${capitalize(cat)}\n`;
output += ` public enum ${capitalize(cat)} {\n`;
for (const token of tokens) {
const last = token.path[token.path.length - 1];
output += ` public static let ${last}: CGFloat = ${toNumber(token.$value ?? token.value)}\n`;
}
output += ` }\n`;
}
output += '}\n';
return output;
}
});
StyleDictionary.registerFormat({
name: 'ios/swift-radius',
format: ({ dictionary }) => {
let output = fileHeader('BaseRadius.swift');
output += '// MARK: - Base Radius\n\n';
output += 'public enum BaseRadius {\n';
const groups = {};
for (const token of dictionary.allTokens) {
const cat = token.path[1]; // "base"
if (!groups[cat]) groups[cat] = [];
groups[cat].push(token);
}
for (const [cat, tokens] of Object.entries(groups)) {
output += `\n // MARK: ${capitalize(cat)}\n`;
output += ` public enum ${capitalize(cat)} {\n`;
for (const token of tokens) {
const last = token.path[token.path.length - 1];
output += ` public static let ${last}: CGFloat = ${toNumber(token.$value ?? token.value)}\n`;
}
output += ` }\n`;
}
output += '}\n';
return output;
}
});
const weightMap = {
'bold': { fontName: 'SUIT-Bold', swiftWeight: '.bold' },
'semibold': { fontName: 'SUIT-SemiBold', swiftWeight: '.semibold' },
'regular': { fontName: 'SUIT-Regular', swiftWeight: '.regular' },
};
const TYPOGRAPHY_REF_PATTERN = /^\{typography\.base\.([^.]+)\.([^.}]+)\}$/;
const refToBaseTypography = (ref, tokenPath, fieldName) => {
const match = typeof ref === 'string' && ref.match(TYPOGRAPHY_REF_PATTERN);
if (!match) {
throw new Error(
`Token "${tokenPath}": "${fieldName}" 참조가 유효하지 않음 (값: ${JSON.stringify(ref)})\n` +
` 예상 형식: {typography.base.<category>.<key>}`
);
}
const cat = capitalize(match[1]);
const key = match[2] === 'default' ? '`default`' : match[2];
return `BaseTypography.${cat}.${key}`;
};
StyleDictionary.registerFormat({
name: 'ios/swift-typography-semantic',
format: ({ dictionary }) => {
let output = fileHeader('Typography.swift');
output += '// MARK: - Semantic Typography\n\n';
output += 'public enum Typography {\n';
for (const token of dictionary.allTokens) {
const cat = token.path[1];
const num = token.path[2];
const name = `${cat}${num}`;
const orig = token.original.$value ?? token.original.value;
const weightRef = orig.fontWeight?.match(TYPOGRAPHY_REF_PATTERN)?.[2];
const { fontName, swiftWeight } = weightMap[weightRef] ?? weightMap['regular'];
const tokenPath = token.path.join('.');
const fontSizeRef = refToBaseTypography(orig.fontSize, tokenPath, 'fontSize');
const lineHeightRef = refToBaseTypography(orig.lineHeight, tokenPath, 'lineHeight');
const letterSpacingRef = refToBaseTypography(orig.letterSpacing, tokenPath, 'letterSpacing');
output += ` public static let ${name} = MDSFont(\n`;
output += ` font: FontLoader.font(name: "${fontName}", size: ${fontSizeRef}, fallbackWeight: ${swiftWeight}),\n`;
output += ` lineHeight: ${lineHeightRef},\n`;
output += ` letterSpacing: ${fontSizeRef} * (${letterSpacingRef} / 100)\n`;
output += ` )\n`;
}
output += '}\n';
return output;
}
});
const toSwiftName = (str) => {
const camel = str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
return camel === 'default' ? '`default`' : camel;
};
const resolveBaseTokenPath = (value) => {
if (typeof value !== 'string') return '';
const match = value.match(/^\{color\.base\.([^.]+)\.([^.}]+)\}$/);
if (!match) return '';
return `color.base.${match[1]}.${match[2]}`;
};
const resolveBaseColorReference = (value) => {
if (typeof value !== 'string') return null;
const match = value.match(/^\{color\.base\.([^.]+)\.([^.}]+)\}$/);
if (!match) return null;
const colorName = match[1];
const shade = match[2];
return `BaseColor.${colorName}${shade}`;
};
const STATE_SUFFIXES = ['hover', 'pressed', 'disabled', 'focused'];
const isStateSuffix = (str) => STATE_SUFFIXES.includes(str);
const parseTokenName = (name) => {
const parts = name.split('-');
const last = parts[parts.length - 1];
if (isStateSuffix(last)) {
return {
base: parts.slice(0, -1).join('-'),
state: last,
};
}
return { base: name, state: null };
};
StyleDictionary.registerFormat({
name: 'ios/swift-color-base-catalog',
format: ({ dictionary }) => {
let output = fileHeader('BaseColorCatalogData.swift');
output += '// MARK: - Base Color Catalog Data\n\n';
output += '@_spi(MDSCatalog) public struct BaseColorCatalogEntry: @unchecked Sendable {\n';
output += ' public let name: String\n';
output += ' public let color: UIColor\n';
output += '}\n\n';
output += '@_spi(MDSCatalog) public enum BaseColorCatalogData {\n';
const groups = new Map();
for (const token of dictionary.allTokens) {
const colorName = token.path[2];
const shade = token.path[token.path.length - 1];
if (!groups.has(colorName)) groups.set(colorName, []);
groups.get(colorName).push(shade);
}
for (const [colorName, shades] of groups.entries()) {
output += ` public static let ${colorName}: [BaseColorCatalogEntry] = [\n`;
for (const shade of shades) {
output += ` .init(name: "${colorName}.${shade}", color: BaseColor.${colorName}${shade}),\n`;
}
output += ` ]\n`;
}
output += '\n public static let groups: [(paletteName: String, entries: [BaseColorCatalogEntry])] = [\n';
for (const [colorName] of groups.entries()) {
output += ` ("${capitalize(colorName)}", ${colorName}),\n`;
}
output += ' ]\n';
output += '}\n';
return output;
}
});
StyleDictionary.registerFormat({
name: 'ios/swift-typography-catalog',
format: ({ dictionary }) => {
let output = fileHeader('BaseTypographyCatalogData.swift');
output += '// MARK: - Base Typography Catalog Data\n\n';
output += '@_spi(MDSCatalog) public struct BaseTypographyCatalogEntry: Sendable {\n';
output += ' public let name: String\n';
output += ' public let value: CGFloat\n';
output += '}\n\n';
output += '@_spi(MDSCatalog) public enum BaseTypographyCatalogData {\n';
const groups = new Map();
for (const token of dictionary.allTokens) {
const cat = token.path[2];
if (!groups.has(cat)) groups.set(cat, []);
groups.get(cat).push(token);
}
for (const [cat, tokens] of groups.entries()) {
output += ` public static let ${cat}: [BaseTypographyCatalogEntry] = [\n`;
for (const token of tokens) {
const last = token.path[token.path.length - 1];
const swiftKey = last === 'default' ? '`default`' : last;
output += ` .init(name: "${last}", value: BaseTypography.${capitalize(cat)}.${swiftKey}),\n`;
}
output += ` ]\n`;
}
output += '\n public static let groups: [(categoryName: String, entries: [BaseTypographyCatalogEntry])] = [\n';
for (const [cat] of groups.entries()) {
output += ` ("${cat}", ${cat}),\n`;
}
output += ' ]\n';
output += '}\n';
return output;
}
});
StyleDictionary.registerFormat({
name: 'ios/swift-color-semantic-datasource',
format: ({ dictionary }) => {
let output = '//\n// ColorTokenDataSource.swift\n// MDSStoryBook\n//\n';
output += '// Auto-generated by Style Dictionary. Do not edit manually.\n//\n\n';
output += 'import MDS\n\n';
output += 'enum ColorTokenDataSource {\n';
output += ' static let sections: [ColorTokenSection] = [\n';
const level1Map = new Map();
for (const token of dictionary.allTokens) {
const level1 = token.path[1];
const level2 = token.path[2];
const variant = token.path[3];
if (!level1Map.has(level1)) level1Map.set(level1, new Map());
const level2Map = level1Map.get(level1);
if (!level2Map.has(level2)) level2Map.set(level2, { base: [], state: [] });
const rawValue = token.original?.$value ?? token.original?.value ?? token.$value ?? token.value;
const baseTokenPath = resolveBaseTokenPath(rawValue);
const { base, state } = parseTokenName(variant);
const level1Cap = capitalize(level1);
const level2Cap = capitalize(level2);
if (state) {
const swiftRef = `SemanticColor.${level1Cap}.${level2Cap}.${toSwiftName(capitalize(base))}.${state}`;
level2Map.get(level2).state.push({ displayName: `${base} · ${state}`, swiftRef, baseTokenPath });
} else {
const swiftRef = `SemanticColor.${level1Cap}.${level2Cap}.${toSwiftName(base)}`;
level2Map.get(level2).base.push({ displayName: base, swiftRef, baseTokenPath });
}
}
for (const [level1, level2Map] of level1Map.entries()) {
const level1Cap = capitalize(level1);
for (const [level2, { base, state }] of level2Map.entries()) {
const level2Cap = capitalize(level2);
output += ` ColorTokenSection(title: "${level1Cap} / ${level2Cap}", items: [\n`;
for (const item of [...base, ...state]) {
output += ` ColorTokenItem(name: "${item.displayName}", color: ${item.swiftRef}, baseTokenPath: "${item.baseTokenPath}"),\n`;
}
output += ` ]),\n`;
}
}
output += ' ]\n}\n';
return output;
}
});
StyleDictionary.registerFormat({
name: 'ios/swift-typography-semantic-datasource',
format: ({ dictionary }) => {
let output = '//\n// TypographyTokenDataSource.swift\n// MDSStoryBook\n//\n';
output += '// Auto-generated by Style Dictionary. Do not edit manually.\n//\n\n';
output += 'import MDS\n\n';
output += 'enum TypographyTokenDataSource {\n';
output += ' static let sections: [TypographyTokenSection] = [\n';
const groups = new Map();
for (const token of dictionary.allTokens) {
const cat = token.path[1];
const num = token.path[2];
if (!groups.has(cat)) groups.set(cat, []);
groups.get(cat).push(num);
}
for (const [cat, nums] of groups.entries()) {
output += ` .init(title: "${capitalize(cat)}", items: [\n`;
for (const num of nums) {
output += ` .init(name: "${cat}${num}", mdsFont: Typography.${cat}${num}),\n`;
}
output += ` ]),\n`;
}
output += ' ]\n}\n';
return output;
}
});
StyleDictionary.registerFormat({
name: 'ios/swift-color-semantic',
format: ({ dictionary }) => {
let output = fileHeader('SemanticColor.swift');
output += '// MARK: - Semantic Color\n\n';
output += 'public enum SemanticColor {\n';
const level1Groups = {};
for (const token of dictionary.allTokens) {
const level1 = token.path[1];
if (!level1Groups[level1]) level1Groups[level1] = [];
level1Groups[level1].push(token);
}
for (const [level1, tokens] of Object.entries(level1Groups)) {
output += `\n public enum ${capitalize(level1)} {\n`;
const level2Groups = {};
for (const token of tokens) {
const level2 = token.path[2];
if (!level2Groups[level2]) level2Groups[level2] = [];
level2Groups[level2].push(token);
}
for (const [level2, innerTokens] of Object.entries(level2Groups)) {
output += `\n public enum ${capitalize(level2)} {\n`;
// base 토큰이랑 state 토큰 분리
const baseTokens = [];
const stateGroups = {}; // { "default": { hover: token, pressed: token, ... } }
for (const token of innerTokens) {
const variant = token.path[3];
const { base, state } = parseTokenName(variant);
if (state) {
if (!stateGroups[base]) stateGroups[base] = {};
stateGroups[base][state] = token;
} else {
baseTokens.push(token);
}
}
// base static let 먼저
for (const token of baseTokens) {
const variant = token.path[3];
const name = toSwiftName(variant);
const rawValue = token.original?.$value ?? token.original?.value ?? token.$value ?? token.value;
const baseRef = resolveBaseColorReference(rawValue);
if (!baseRef) throw new Error(`Cannot resolve base color reference for token "${token.path.join('.')}" (value: ${JSON.stringify(rawValue)})`);
output += ` public static let ${name} = ${baseRef}\n`;
}
// state enum
for (const [base, states] of Object.entries(stateGroups)) {
const enumName = toSwiftName(capitalize(base));
output += `\n public enum ${enumName} {\n`;
for (const [state, token] of Object.entries(states)) {
const rawValue = token.original?.$value ?? token.original?.value ?? token.$value ?? token.value;
const baseRef = resolveBaseColorReference(rawValue);
if (!baseRef) throw new Error(`Cannot resolve base color reference for token "${token.path.join('.')}" (value: ${JSON.stringify(rawValue)})`);
output += ` public static let ${state} = ${baseRef}\n`;
}
output += ` }\n`;
}
output += ` }\n`;
}
output += ` }\n`;
}
output += '}\n';
return output;
}
});
const sd = new StyleDictionary({
usesDtcg: true,
log: { warnings: 'disabled' },
source: ['tokens/**/*.json'],
platforms: {
swift: {
transforms: [],
buildPath: 'MDS/Sources/Foundation/Base/',
files: [
{
destination: 'BaseTypography.swift',
format: 'ios/swift-typography',
filter: (token) => token.path[0] === 'typography' && typeof (token.$value ?? token.value) !== 'object'
},
{
destination: 'BaseSpacing.swift',
format: 'ios/swift-spacing',
filter: (token) => token.path[0] === 'spacing'
},
{
destination: 'BaseColor.swift',
format: 'ios/swift-color-base',
filter: (token) => token.path[0] === 'color' && token.path[1] === 'base'
},
{
destination: 'BaseRadius.swift',
format: 'ios/swift-radius',
filter: (token) => token.path[0] === 'radius'
}
]
},
swiftCatalog: {
transforms: [],
buildPath: 'MDS/Sources/Catalog/',
files: [
{
destination: 'BaseColorCatalogData.swift',
format: 'ios/swift-color-base-catalog',
filter: (token) => token.path[0] === 'color' && token.path[1] === 'base'
},
{
destination: 'BaseTypographyCatalogData.swift',
format: 'ios/swift-typography-catalog',
filter: (token) => token.path[0] === 'typography' && typeof (token.$value ?? token.value) !== 'object'
}
]
},
swiftStoryBook: {
transforms: [],
buildPath: 'MDSStoryBook/MDSStoryBook/Token/Color/',
files: [
{
destination: 'ColorTokenDataSource.swift',
format: 'ios/swift-color-semantic-datasource',
filter: (token) => token.path[0] === 'color' && token.path[1] !== 'base'
}
]
},
swiftStoryBookTypography: {
transforms: [],
buildPath: 'MDSStoryBook/MDSStoryBook/Token/Typography/',
files: [
{
destination: 'TypographyTokenDataSource.swift',
format: 'ios/swift-typography-semantic-datasource',
filter: (token) => token.path[0] === 'typography' && typeof (token.$value ?? token.value) === 'object'
}
]
},
swiftSemantic: {
transforms: [],
buildPath: 'MDS/Sources/Tokens/',
files: [
{
destination: 'Typography.swift',
format: 'ios/swift-typography-semantic',
filter: (token) => token.path[0] === 'typography' && typeof (token.$value ?? token.value) === 'object'
},
{
destination: 'SemanticColor.swift',
format: 'ios/swift-color-semantic',
filter: (token) => token.path[0] === 'color' && token.path[1] !== 'base'
}
]
},
}
});
await sd.buildAllPlatforms();
console.log('Design tokens built successfully.');