Repository navigation
Expand file tree
/
Copy pathsync.ts
More file actions
342 lines (318 loc) · 10.5 KB
/
Copy pathsync.ts
File metadata and controls
342 lines (318 loc) · 10.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
339
340
341
342
// Orchestrates the create / sync / review flows on top of figma-styles.
import {
FigmaLetterSpacing,
FigmaLineHeight,
PluginConfig,
ReviewItem,
SyncMode,
SyncSummary,
} from '@/lib/types'
import {
StyleTarget,
adoptStyle,
applyResolvedToStyle,
buildTargets,
diffResolved,
findStyleByName,
hasManualEdits,
liveResolved,
readMetadata,
resolveFontName,
} from './figma-styles'
const emptySummary = (): SyncSummary => ({
created: [],
updated: [],
adopted: [],
skipped: [],
skippedUnmanaged: [],
errors: [],
review: [],
})
const errMsg = (err: unknown): string =>
err instanceof Error ? err.message : String(err)
const applyTarget = (target: StyleTarget, style: TextStyle): Promise<void> =>
applyResolvedToStyle(style, target.resolved, {
styleKind: target.kind,
semanticName: target.semanticName,
composite: target.composite,
})
/** Create only styles that don't yet exist. Never touches existing styles. */
export const createMissing = async (
config: PluginConfig
): Promise<SyncSummary> => {
const summary = emptySummary()
for (const target of buildTargets(config)) {
try {
const existing = await findStyleByName(target.name)
if (existing) {
// Already present: record why we're leaving it alone so a name
// collision is visible instead of silently swallowed.
if (readMetadata(existing)) summary.skipped.push(target.name)
else summary.skippedUnmanaged.push(target.name)
continue
}
const style = figma.createTextStyle()
style.name = target.name
await applyTarget(target, style)
summary.created.push(target.name)
} catch (err) {
summary.errors.push({
styleName: target.name,
message: errMsg(err),
})
}
}
return summary
}
/**
* Adopt existing, unmanaged styles whose name matches a target. Stamps this
* plugin's metadata onto them (snapshotting their current values) so future
* syncs manage them. Never changes their appearance and never touches styles
* that are already managed or don't exist yet.
*/
export const adoptStyles = async (
config: PluginConfig
): Promise<SyncSummary> => {
const summary = emptySummary()
for (const target of buildTargets(config)) {
try {
const existing = await findStyleByName(target.name)
if (!existing) continue
if (readMetadata(existing)) continue // already managed
adoptStyle(existing, target)
summary.adopted.push(target.name)
} catch (err) {
summary.errors.push({
styleName: target.name,
message: errMsg(err),
})
}
}
return summary
}
/**
* Sync managed styles.
* - 'safe': create missing, update unmodified managed styles, skip manually
* edited ones.
* - 'force': create missing and overwrite ALL managed styles regardless of
* manual edits.
*/
export const syncStyles = async (
config: PluginConfig,
mode: SyncMode
): Promise<SyncSummary> => {
const summary = emptySummary()
for (const target of buildTargets(config)) {
try {
const existing = await findStyleByName(target.name)
if (!existing) {
const style = figma.createTextStyle()
style.name = target.name
await applyTarget(target, style)
summary.created.push(target.name)
continue
}
const meta = readMetadata(existing)
if (!meta) {
// Unmanaged style with the same name: never touch it.
summary.skippedUnmanaged.push(target.name)
continue
}
if (mode === 'safe' && hasManualEdits(existing, meta)) {
summary.skipped.push(target.name)
continue
}
await applyTarget(target, existing)
summary.updated.push(target.name)
} catch (err) {
summary.errors.push({
styleName: target.name,
message: errMsg(err),
})
}
}
return summary
}
/**
* Review: compute what WOULD change without writing anything. Manually-edited
* managed styles are returned as review items; clean ones with pending changes
* are counted in `updated` as "will update".
*/
export const reviewStyles = async (
config: PluginConfig
): Promise<SyncSummary> => {
const summary = emptySummary()
for (const target of buildTargets(config)) {
const existing = await findStyleByName(target.name)
if (!existing) {
summary.created.push(target.name)
continue
}
const meta = readMetadata(existing)
if (!meta) {
summary.skippedUnmanaged.push(target.name)
continue
}
const live = liveResolved(existing)
const drift = diffResolved(live, meta.lastApplied)
const pending = diffResolved(meta.lastApplied, target.resolved)
if (drift.length > 0) {
// Manually edited -> needs an explicit decision.
const item: ReviewItem = {
styleName: target.name,
styleId: existing.id,
drift,
pending,
}
summary.review.push(item)
} else if (pending.length > 0) {
summary.updated.push(target.name)
} else {
summary.skipped.push(target.name)
}
}
return summary
}
/** Apply per-style decisions coming back from the Review UI. */
export const applyReviewDecisions = async (
config: PluginConfig,
decisions: { styleName: string; update: boolean }[]
): Promise<SyncSummary> => {
const summary = emptySummary()
const decided = new Map(decisions.map(d => [d.styleName, d.update]))
for (const target of buildTargets(config)) {
const decision = decided.get(target.name)
if (decision === undefined) continue // not part of this review batch
try {
const existing = await findStyleByName(target.name)
if (!existing) continue
if (!decision) {
summary.skipped.push(target.name)
continue
}
await applyTarget(target, existing)
summary.updated.push(target.name)
} catch (err) {
summary.errors.push({
styleName: target.name,
message: errMsg(err),
})
}
}
return summary
}
/**
* Apply a semantic Text Style to the currently selected text nodes. Ensures the
* style exists first (creating it if needed), loads fonts, and uses
* setTextStyleIdAsync so layers reference the shared style.
*/
export const applyToSelection = async (
config: PluginConfig,
semanticName: string
): Promise<SyncSummary> => {
const summary = emptySummary()
const target = buildTargets(config).find(t => t.name === semanticName)
if (!target) {
summary.errors.push({
styleName: semanticName,
message: 'Unknown semantic style',
})
return summary
}
// Ensure the style exists.
let style = await findStyleByName(semanticName)
if (!style) {
style = figma.createTextStyle()
style.name = semanticName
await applyTarget(target, style)
summary.created.push(semanticName)
}
const textNodes = figma.currentPage.selection.filter(
(n): n is TextNode => n.type === 'TEXT'
)
if (textNodes.length === 0) {
summary.errors.push({
styleName: semanticName,
message: 'Select one or more text layers first.',
})
return summary
}
// Load the font the style uses before assigning it.
const fontName = await resolveFontName(
target.resolved.fontFamily,
target.resolved.fontWeight
)
await figma.loadFontAsync(fontName)
for (const node of textNodes) {
try {
await node.setTextStyleIdAsync(style.id)
summary.updated.push(node.name || semanticName)
} catch (err) {
summary.errors.push({ styleName: node.name, message: errMsg(err) })
}
}
return summary
}
/**
* Load every font used by a text node. Figma requires all fonts in a node to be
* loaded before any text property (line height, letter spacing, …) can be set.
*/
const loadNodeFonts = async (node: TextNode): Promise<void> => {
const len = node.characters.length
const fonts =
len > 0
? node.getRangeAllFontNames(0, len)
: [node.fontName as FontName]
await Promise.all(fonts.map(f => figma.loadFontAsync(f)))
}
/**
* Apply a single text-property mutation to every selected text layer, loading
* each node's fonts first. Used to push one Tailwind token (a line height or
* letter spacing) straight onto the selection, without going through a Text
* Style.
*/
const applyToSelectedText = async (
mutate: (node: TextNode) => void
): Promise<SyncSummary> => {
const summary = emptySummary()
const nodes = figma.currentPage.selection.filter(
(n): n is TextNode => n.type === 'TEXT'
)
if (nodes.length === 0) {
summary.errors.push({
styleName: 'selection',
message: 'Select one or more text layers first.',
})
return summary
}
for (const node of nodes) {
try {
await loadNodeFonts(node)
mutate(node)
summary.updated.push(node.name)
} catch (err) {
summary.errors.push({ styleName: node.name, message: errMsg(err) })
}
}
return summary
}
/** Set the line height (already converted to a Figma value) on the selection. */
export const applyLineHeightToSelection = (
lineHeight: FigmaLineHeight
): Promise<SyncSummary> =>
applyToSelectedText(node => {
node.lineHeight =
lineHeight.unit === 'AUTO'
? { unit: 'AUTO' }
: { value: lineHeight.value, unit: lineHeight.unit }
})
/** Set the letter spacing (already converted) on the selection. */
export const applyLetterSpacingToSelection = (
letterSpacing: FigmaLetterSpacing
): Promise<SyncSummary> =>
applyToSelectedText(node => {
node.letterSpacing = {
value: letterSpacing.value,
unit: letterSpacing.unit,
}
})