| 67 | }; |
| 68 | |
| 69 | async function createVariableCollection(theme: FigmaTheme) { |
| 70 | const existingCollections = |
| 71 | await figma.variables.getLocalVariableCollectionsAsync(); |
| 72 | |
| 73 | let collection = existingCollections.find((c) => c.name === theme.name); |
| 74 | |
| 75 | if (collection) { |
| 76 | figma.notify("⚠️ Updating existing collection..."); |
| 77 | } else { |
| 78 | collection = figma.variables.createVariableCollection(theme.name); |
| 79 | } |
| 80 | |
| 81 | const lightMode = collection.modes[0]; |
| 82 | collection.renameMode(lightMode.modeId, "Light"); |
| 83 | |
| 84 | let darkMode = collection.modes.find((m) => m.name === "Dark"); |
| 85 | if (!darkMode) { |
| 86 | const darkModeId = collection.addMode("Dark"); |
| 87 | darkMode = collection.modes.find((m) => m.modeId === darkModeId); |
| 88 | } |
| 89 | |
| 90 | if (!darkMode) { |
| 91 | throw new Error("Failed to create dark mode"); |
| 92 | } |
| 93 | |
| 94 | const existingVars = collection.variableIds.map((id) => |
| 95 | figma.variables.getVariableById(id), |
| 96 | ); |
| 97 | |
| 98 | let totalVars = 0; |
| 99 | |
| 100 | // Create COLOR variables |
| 101 | const colorTokenNames = theme.tokens.light.colors |
| 102 | ? Object.keys(theme.tokens.light.colors) |
| 103 | : []; |
| 104 | for (const tokenName of colorTokenNames) { |
| 105 | const lightColor = theme.tokens.light.colors[tokenName]; |
| 106 | const darkColor = theme.tokens.dark.colors[tokenName]; |
| 107 | |
| 108 | if (!lightColor || !darkColor) continue; |
| 109 | |
| 110 | let variable = existingVars.find((v) => v && v.name === tokenName) as |
| 111 | | Variable |
| 112 | | undefined; |
| 113 | |
| 114 | if (!variable) { |
| 115 | variable = figma.variables.createVariable(tokenName, collection, "COLOR"); |
| 116 | } |
| 117 | |
| 118 | variable.setValueForMode(lightMode.modeId, lightColor); |
| 119 | variable.setValueForMode(darkMode.modeId, darkColor); |
| 120 | totalVars++; |
| 121 | } |
| 122 | |
| 123 | // Create NUMBER variables |
| 124 | const numberTokenNames = theme.tokens.light.numbers |
| 125 | ? Object.keys(theme.tokens.light.numbers) |
| 126 | : []; |