-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
338 lines (338 loc) · 15.5 KB
/
Copy pathcode.js
File metadata and controls
338 lines (338 loc) · 15.5 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
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
// Width is fixed; height is driven by the UI, which measures its own content
// and posts a `resize` message (see ui.html). The initial height is just a
// starting point before the first measurement arrives.
const PLUGIN_WIDTH = 500;
figma.showUI(__html__, { themeColors: true, width: PLUGIN_WIDTH, height: 200 });
// The color migration (see ../color-migration-helper) reshapes the variables:
// pre-migration uses a `Main color` and a `Support color` collection, with
// variables prefixed `color/main/`. Post-migration these fold into a single
// `Color` collection (Support color is deleted) and the prefix is stripped.
const LEGACY_COLOR_PREFIX = 'color/main/';
function getSyntaxCollections(state) {
if (state === 'post') {
return ['Color', 'Semantic', 'Size', 'Theme'];
}
// A half-migrated file may contain both the old (`Main color` / `Support
// color`) and new (`Color`) color collections at once. We process the union;
// `targetCollections` filters to those that actually exist. Writing syntax /
// scopes is idempotent and the color output is identical pre/post migration,
// so handling whichever collections are present is safe.
if (state === 'half') {
return ['Color', 'Main color', 'Support color', 'Semantic', 'Size', 'Theme'];
}
return ['Main color', 'Semantic', 'Support color', 'Size', 'Theme'];
}
function getScopeCollections(state) {
return [...getSyntaxCollections(state), 'Color scheme', 'Typography'];
}
// Mirrors the migration plugin's `checkPrimeStatus`: decides whether the file
// is in its pre-migration shape, fully migrated, half-migrated (ambiguous), or
// not a Designsystemet library file at all.
function detectMigrationState(collections, variablesByCollectionId) {
var _a;
const hasMainColor = collections.some((c) => c.name === 'Main color');
const hasSupportColor = collections.some((c) => c.name === 'Support color');
const hasColor = collections.some((c) => c.name === 'Color');
// Variables still carrying the legacy prefix, in either the pre-rename
// (`Main color`) or post-rename (`Color`) collection.
let prefixedCount = 0;
for (const collection of collections) {
if (collection.name !== 'Main color' && collection.name !== 'Color') {
continue;
}
const variables = (_a = variablesByCollectionId.get(collection.id)) !== null && _a !== void 0 ? _a : [];
for (const variable of variables) {
if (variable.name.startsWith(LEGACY_COLOR_PREFIX)) {
prefixedCount++;
}
}
}
if (!hasColor && !hasMainColor && !hasSupportColor) {
return 'not-library';
}
// Clean post-migration: `Color` exists, no legacy collections, no residual prefix.
if (hasColor && !hasMainColor && !hasSupportColor && prefixedCount === 0) {
return 'post';
}
// Legacy shape: `Main color`/`Support color` present and `Color` not yet created.
// The `color/main/` prefix is expected here, so it does not count against us.
if (!hasColor && (hasMainColor || hasSupportColor)) {
return 'pre';
}
// Anything else (both shapes coexist, or `Color` with leftover prefixed vars)
// is a half-finished migration.
return 'half';
}
function getFormattedName(variable) {
var _a;
const fullName = variable.name.toLowerCase();
const name = ((_a = variable.name.split('/').pop()) === null || _a === void 0 ? void 0 : _a.replace(/\s+/g, '-').toLowerCase()) || '';
return { fullName, name };
}
function getScopes(collectionName, resolvedType, fullName) {
if (resolvedType === 'COLOR') {
if (collectionName === 'Semantic' ||
collectionName === 'Main color' ||
collectionName === 'Support color' ||
collectionName === 'Color') {
// ALL_SCOPES: for a COLOR variable this covers exactly the color fields
// (fills, strokes, effects) — Figma never offers a color in number fields
// like opacity/gap. Equivalent to ALL_FILLS + STROKE_COLOR + EFFECT_COLOR
// but tidier and future-proof. Cannot be combined with other scopes.
return ['ALL_SCOPES'];
}
return [];
}
if (resolvedType === 'FLOAT') {
if (collectionName === 'Size' && fullName.includes('font-size/')) {
return ['FONT_SIZE'];
}
if (collectionName === 'Semantic') {
if (fullName.includes('opacity'))
return ['OPACITY'];
if (fullName.includes('border-width'))
return ['STROKE_FLOAT'];
if (fullName.includes('border-radius'))
return ['CORNER_RADIUS'];
if (fullName.includes('size/'))
return ['GAP', 'WIDTH_HEIGHT'];
}
return [];
}
if (resolvedType === 'STRING' && collectionName === 'Theme') {
if (fullName.includes('font-weight/'))
return ['FONT_STYLE'];
if (fullName === 'font-family')
return ['FONT_FAMILY'];
}
return [];
}
function getExpectedSyntax(collectionName, resolvedType, fullName, name) {
if (resolvedType === 'COLOR' && collectionName !== 'Theme') {
if (fullName === 'link/color/visited') {
return 'var(--ds-link-color-visited)';
}
if (fullName.includes('focus/inner')) {
return 'var(--ds-color-focus-inner)';
}
if (fullName.includes('focus/outer')) {
return 'var(--ds-color-focus-outer)';
}
// Semantic colors are locked to one color regardless of data-color/mode,
// so their CSS var always includes the color-group name (read from the
// path). Color / Main color / Support color stay group-less — the
// data-color attribute selects the actual color at runtime.
if (collectionName === 'Semantic') {
const [, colorName, ...rest] = fullName.split('/');
const semanticName = [colorName, ...rest].filter(Boolean).join('-') || name;
return `var(--ds-color-${semanticName})`;
}
return `var(--ds-color-${name})`;
}
if (resolvedType === 'FLOAT' && collectionName !== 'Theme') {
if (fullName.startsWith('_size/'))
return null;
if (fullName.includes('font-size/')) {
return `var(--ds-font-size-${name})`;
}
if (fullName.includes('border-radius')) {
return `var(--ds-border-radius-${name})`;
}
if (fullName.includes('border-width')) {
return `var(--ds-border-width-${name})`;
}
if (fullName.includes('opacity')) {
return `var(--ds-opacity-${name})`;
}
if (fullName.includes('size/')) {
return `var(--ds-size-${name})`;
}
const collectionSlug = collectionName.toLowerCase().replace(/\s+/g, '-');
return `var(--ds-${collectionSlug}-${name})`;
}
if (collectionName === 'Theme' && resolvedType === 'STRING') {
if (fullName.includes('font-weight/')) {
return `var(--ds-font-weight-${name})`;
}
if (fullName === 'font-family') {
return 'var(--ds-font-family)';
}
}
return null;
}
function normalizeScopes(scopes) {
return [...scopes].sort().join('|');
}
figma.ui.onmessage = (msg) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b, _c, _d;
if (msg.type === 'resize') {
const height = Math.max(1, Math.round(Number(msg.height) || 0));
figma.ui.resize(PLUGIN_WIDTH, height);
return;
}
if (msg.type !== 'generate-syntax' && msg.type !== 'generate-scopes' && msg.type !== 'check-health') {
return;
}
try {
const action = msg.type;
const collections = yield figma.variables.getLocalVariableCollectionsAsync();
const allVariables = yield figma.variables.getLocalVariablesAsync();
const variablesByCollectionId = new Map();
for (const variable of allVariables) {
const existing = variablesByCollectionId.get(variable.variableCollectionId);
if (existing) {
existing.push(variable);
}
else {
variablesByCollectionId.set(variable.variableCollectionId, [variable]);
}
}
const migrationState = detectMigrationState(collections, variablesByCollectionId);
let output = '';
const appendOutputLine = (line) => {
output += output ? `\n${line}` : line;
};
if (migrationState === 'not-library') {
appendOutputLine('No Designsystemet color collections found in this file.');
figma.ui.postMessage({ type: 'action-result', action, output, migrationState });
return;
}
// A half-finished migration has an ambiguous structure, but writing syntax
// and scopes is idempotent and the color output is identical pre/post
// migration, so we process whatever color collections are present rather
// than blocking. The UI shows a non-blocking note.
if (migrationState === 'half') {
appendOutputLine('Note: this file looks mid-migration (old and new color structures both detected).');
appendOutputLine('Processing the color collections that are present; finishing the migration is still recommended.');
}
const syntaxCollections = getSyntaxCollections(migrationState);
const requiredCollections = action === 'generate-syntax'
? syntaxCollections
: getScopeCollections(migrationState);
const targetCollections = collections.filter(c => requiredCollections.some(name => name === c.name));
// In a half-migrated file the color collection set is inherently partial
// (only some of Color / Main color / Support color exist), so a missing
// color collection is expected and should not be warned about.
const colorCollectionNames = ['Color', 'Main color', 'Support color'];
const missingCollections = requiredCollections.filter(name => !collections.some(c => c.name === name) &&
!(migrationState === 'half' && colorCollectionNames.indexOf(name) !== -1));
if (missingCollections.length > 0) {
appendOutputLine('Warning: The following collections are missing:');
missingCollections.forEach(name => appendOutputLine(`- ${name}`));
}
if (targetCollections.length === 0) {
appendOutputLine('No relevant collections found.');
figma.ui.postMessage({ type: 'action-result', action, output, migrationState });
return;
}
let updatedCount = 0;
let scopeChangedCount = 0;
let scopeUnchangedCount = 0;
let noScopeCount = 0;
let checkedSyntax = 0;
let syntaxMissing = 0;
let syntaxMismatch = 0;
let checkedScopes = 0;
let scopeMismatch = 0;
for (const collection of targetCollections) {
const variables = (_a = variablesByCollectionId.get(collection.id)) !== null && _a !== void 0 ? _a : [];
for (const variable of variables) {
const { fullName, name } = getFormattedName(variable);
if (action === 'generate-scopes') {
const scopes = getScopes(collection.name, variable.resolvedType, fullName);
const actualScopes = (_b = variable.scopes) !== null && _b !== void 0 ? _b : [];
const hasScopeChange = normalizeScopes(scopes) !== normalizeScopes(actualScopes);
if (hasScopeChange) {
variable.scopes = scopes;
scopeChangedCount++;
}
else {
scopeUnchangedCount++;
}
if (scopes.length === 0) {
noScopeCount++;
}
continue;
}
if (action === 'generate-syntax') {
const expectedSyntax = getExpectedSyntax(collection.name, variable.resolvedType, fullName, name);
if (expectedSyntax) {
variable.setVariableCodeSyntax('WEB', expectedSyntax);
updatedCount++;
}
continue;
}
const expectedScopes = getScopes(collection.name, variable.resolvedType, fullName);
const actualScopes = (_c = variable.scopes) !== null && _c !== void 0 ? _c : [];
checkedScopes++;
if (normalizeScopes(expectedScopes) !== normalizeScopes(actualScopes)) {
scopeMismatch++;
}
if (syntaxCollections.indexOf(collection.name) === -1) {
continue;
}
const expectedSyntax = getExpectedSyntax(collection.name, variable.resolvedType, fullName, name);
if (!expectedSyntax) {
continue;
}
checkedSyntax++;
const actualSyntax = ((_d = variable.codeSyntax['WEB']) === null || _d === void 0 ? void 0 : _d.trim()) || '';
if (!actualSyntax) {
syntaxMissing++;
continue;
}
if (actualSyntax !== expectedSyntax) {
syntaxMismatch++;
}
}
}
if (action === 'generate-scopes') {
appendOutputLine(`Scopes changed on ${scopeChangedCount} variables.`);
appendOutputLine(`Scopes already correct on ${scopeUnchangedCount} variables.`);
appendOutputLine(`${noScopeCount} variables end with no scope.`);
}
else if (action === 'generate-syntax') {
appendOutputLine(`Updated ${updatedCount} variables with the design system CSS syntax.`);
}
else {
const syntaxIssueCount = syntaxMissing + syntaxMismatch;
appendOutputLine('Check complete.');
appendOutputLine(`Syntax: ${syntaxIssueCount === 0 ? 'OK' : `${syntaxIssueCount} issue(s)`}.`);
appendOutputLine(`Scopes: ${scopeMismatch === 0 ? 'OK' : `${scopeMismatch} issue(s)`}.`);
}
const health = action === 'check-health'
? {
scopeMismatch,
syntaxMissing,
syntaxMismatch,
syntaxChecked: checkedSyntax,
scopesChecked: checkedScopes
}
: undefined;
figma.ui.postMessage({
type: 'action-result',
action,
output,
migrationState,
health
});
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
figma.ui.postMessage({
type: 'action-result',
action: 'error',
output: `Error: ${errorMessage}`
});
}
});