@sit-onyx/figma-utils 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2023 Schwarz IT KG
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # @sit-onyx/figma-utils
2
+
3
+ Utility functions and CLI for importing data from the Figma API into CSS/SCSS variables.
4
+
5
+ ## Use as CLI
6
+
7
+ For a list of supported commands and options, run:
8
+
9
+ ```sh
10
+ npx @sit-onyx/figma-utils@latest --help
11
+ ```
12
+
13
+ ## Use as npm package
14
+
15
+ This package also provides utility functions for importing data from the Figma API.
16
+ This is useful if you want customize the CLI commands to have full control over the output.
17
+
18
+ ```sh
19
+ npm install @sit-onyx/figma-utils
20
+ ```
21
+
22
+ ### Examples
23
+
24
+ ```ts
25
+ import fs from "node:fs";
26
+ import path from "node:path";
27
+ import { fetchFigmaVariables, generateAsCSS, parseFigmaVariables } from "@sit-onyx/figma-utils";
28
+
29
+ const FILE_KEY = "your-figma-file-key";
30
+ const FIGMA_TOKEN = "your-figma-access-token";
31
+
32
+ // fetch variables from Figma API
33
+ const data = await fetchFigmaVariables(FILE_KEY, FIGMA_TOKEN);
34
+
35
+ // parse variables into a readable and normalized format
36
+ const parsedVariables = parseFigmaVariables(data);
37
+
38
+ // generate .css files for every Figma mode
39
+ parsedVariables.forEach((mode) => {
40
+ // get .css file content
41
+ const fileContent = generateAsCSS(mode);
42
+
43
+ // write content as a file
44
+ const filename = mode.modeName ? `variables-${mode.modeName}.css` : "variables.css";
45
+ const fullPath = path.join(process.cwd(), filename);
46
+ fs.writeFileSync(fullPath, fileContent);
47
+ });
48
+ ```
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import fs from "node:fs";
4
+ import { fileURLToPath, URL } from "node:url";
5
+ import { importCommand } from "./commands/import-variables.js";
6
+ const packageJson = JSON.parse(fs.readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"));
7
+ const cli = new Command();
8
+ cli.version(packageJson.version, "-v, --version").description(packageJson.description);
9
+ const availableCommands = [importCommand];
10
+ availableCommands.forEach((command) => cli.addCommand(command));
11
+ cli.parse();
@@ -0,0 +1,2 @@
1
+ import { Command } from "commander";
2
+ export declare const importCommand: Command;
@@ -0,0 +1,52 @@
1
+ import { Command } from "commander";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { DEFAULT_MODE_NAME, fetchFigmaVariables, generateAsCSS, generateAsSCSS, parseFigmaVariables, } from "../index.js";
5
+ export const importCommand = new Command("import-variables")
6
+ .description("CLI tool to import Figma variables into CSS, SCSS etc. variables.")
7
+ .requiredOption("-k, --file-key <string>", "Figma file key (required)")
8
+ .requiredOption("-t, --token <string>", "Figma access token with scope `file_variables:read` (required)")
9
+ .option("-f, --format <string>", "Output format. Supported are: CSS, SCSS", "CSS")
10
+ .option("-n, --filename <string>", "Base name of the generated variables file", "variables")
11
+ .option("-d, --dir <string>", "Working directory to use. Defaults to current working directory of the script.")
12
+ .option("-m, --modes <strings...>", "Can be used to only export specific Figma modes. If unset, all modes will be exported as a separate file.")
13
+ .action(async (options) => {
14
+ const generators = {
15
+ CSS: generateAsCSS,
16
+ SCSS: generateAsSCSS,
17
+ };
18
+ if (!(options.format in generators)) {
19
+ throw new Error(`Unknown format: ${options.format}. Supported: ${Object.keys(generators).join(", ")}`);
20
+ }
21
+ console.log("Fetching variables from Figma API...");
22
+ const data = await fetchFigmaVariables(options.fileKey, options.token);
23
+ console.log("Parsing Figma variables...");
24
+ const parsedVariables = parseFigmaVariables(data);
25
+ if (options.modes?.length) {
26
+ // verify that all modes are found
27
+ for (const mode of options.modes) {
28
+ if (parsedVariables.find((i) => i.modeName === mode))
29
+ continue;
30
+ const availableModes = parsedVariables
31
+ .map((i) => i.modeName ?? DEFAULT_MODE_NAME)
32
+ .map((mode) => `"${mode}"`);
33
+ throw new Error(`Mode "${mode}" not found. Available modes: ${Object.values(availableModes).join(", ")}`);
34
+ }
35
+ }
36
+ const outputDirectory = options.dir ?? process.cwd();
37
+ const filename = options.filename ?? "variables";
38
+ console.log(`Generating ${options.format} variables...`);
39
+ parsedVariables.forEach((data) => {
40
+ // if the user passed specific modes to be exported, we will only generate those
41
+ // otherwise all modes will be exported.
42
+ // the default mode (undefined data.modeName) is always generated because its mode name can
43
+ // not be specified by the designer in Figma
44
+ const isModeIncluded = !options.modes?.length || !data.modeName || options.modes.includes(data.modeName);
45
+ if (!isModeIncluded)
46
+ return;
47
+ const baseName = data.modeName ? `${filename}-${data.modeName}` : filename;
48
+ const fullPath = path.join(outputDirectory, `${baseName}.${options.format.toLowerCase()}`);
49
+ fs.writeFileSync(fullPath, generators[options.format](data));
50
+ });
51
+ console.log("Done.");
52
+ });
@@ -0,0 +1,4 @@
1
+ export * from "./types/figma.js";
2
+ export * from "./utils/fetch.js";
3
+ export * from "./utils/generate.js";
4
+ export * from "./utils/parse.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./types/figma.js";
2
+ export * from "./utils/fetch.js";
3
+ export * from "./utils/generate.js";
4
+ export * from "./utils/parse.js";
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Figma API response when fetching from https://api.figma.com/v1/files/${fileKey}/variables/local
3
+ */
4
+ export type FigmaVariablesApiResponse = {
5
+ meta: {
6
+ variableCollections: Record<string, VariablesCollection>;
7
+ variables: Record<string, Variable>;
8
+ };
9
+ };
10
+ export type VariablesCollection = {
11
+ defaultModeId: string;
12
+ hiddenFromPublishing: boolean;
13
+ modes: Mode[];
14
+ };
15
+ export type Mode = {
16
+ modeId: string;
17
+ name: string;
18
+ };
19
+ export type Variable = {
20
+ name: string;
21
+ variableCollectionId: string;
22
+ hiddenFromPublishing: boolean;
23
+ valuesByMode: Record<string, VariableValue>;
24
+ };
25
+ export type VariableValue = RGBAValue | ColorsAlias | number;
26
+ export type RGBAValue = {
27
+ r: number;
28
+ g: number;
29
+ b: number;
30
+ a: number;
31
+ };
32
+ export type ColorsAlias = {
33
+ type: "VARIABLE_ALIAS";
34
+ id: string;
35
+ };
36
+ export type ParsedVariable = {
37
+ /** Figma mode name or undefined if its the default mode. */
38
+ modeName?: string;
39
+ /**
40
+ * Mapping from variable name to its value.
41
+ * @example
42
+ * ```json
43
+ * {
44
+ * "primary-100": "#ffffff",
45
+ * "border-radius-s": "1rem",
46
+ * }
47
+ * ```
48
+ */
49
+ variables: Record<string, string>;
50
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import { FigmaVariablesApiResponse } from "../types/figma.js";
2
+ /**
3
+ * Fetches the Figma Variables for the given file from the Figma API v1.
4
+ *
5
+ * @param fileKey File key. Example: https://www.figma.com/file/your-file-key-here
6
+ * @param accessToken Personal access token with scope/permission `file_variables:read`
7
+ */
8
+ export declare const fetchFigmaVariables: (fileKey: string, accessToken: string) => Promise<FigmaVariablesApiResponse>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Fetches the Figma Variables for the given file from the Figma API v1.
3
+ *
4
+ * @param fileKey File key. Example: https://www.figma.com/file/your-file-key-here
5
+ * @param accessToken Personal access token with scope/permission `file_variables:read`
6
+ */
7
+ export const fetchFigmaVariables = async (fileKey, accessToken) => {
8
+ const response = await fetch(`https://api.figma.com/v1/files/${fileKey}/variables/local`, {
9
+ headers: {
10
+ "X-FIGMA-TOKEN": accessToken,
11
+ },
12
+ });
13
+ const body = await response.json();
14
+ if (response.status !== 200) {
15
+ throw new Error(`Figma API request failed. Response body: ${JSON.stringify(body)}`);
16
+ }
17
+ return body;
18
+ };
@@ -0,0 +1,24 @@
1
+ import { ParsedVariable } from "../types/figma.js";
2
+ /**
3
+ * Generates the given parsed Figma variables into CSS variables.
4
+ *
5
+ * @returns File content of the .css file
6
+ */
7
+ export declare const generateAsCSS: (data: ParsedVariable) => string;
8
+ /**
9
+ * Generates the given parsed Figma variables into SCSS variables.
10
+ *
11
+ * @returns File content of the .scss file
12
+ */
13
+ export declare const generateAsSCSS: (data: ParsedVariable) => string;
14
+ /**
15
+ * Checks whether the given variable value is an alias / variable reference to another variable.
16
+ * Alias values are enclosed by curly braces.
17
+ *
18
+ * @example "{your-variable-name}"
19
+ * @returns `isAlias` whether the variable is an alias and `variableName` the raw variable name without curly braces.
20
+ */
21
+ export declare const isAliasVariable: (variableValue: string) => {
22
+ isAlias: RegExpExecArray | null;
23
+ variableName: string;
24
+ };
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Generates the given parsed Figma variables into CSS variables.
3
+ *
4
+ * @returns File content of the .css file
5
+ */
6
+ export const generateAsCSS = (data) => {
7
+ return genericGenerator({
8
+ data,
9
+ nameTransformer: (name) => `--${name}`,
10
+ aliasTransformer: (name) => `var(--${name})`,
11
+ });
12
+ };
13
+ /**
14
+ * Generates the given parsed Figma variables into SCSS variables.
15
+ *
16
+ * @returns File content of the .scss file
17
+ */
18
+ export const generateAsSCSS = (data) => {
19
+ return genericGenerator({
20
+ data,
21
+ nameTransformer: (name) => `$${name}`,
22
+ aliasTransformer: (name) => `$${name}`,
23
+ });
24
+ };
25
+ /**
26
+ * Generic base generator for CSS, SCSS etc. files.
27
+ * Will take care of defining selectors and formatting.
28
+ */
29
+ const genericGenerator = (options) => {
30
+ const variableContent = Object.entries(options.data.variables).map(([name, value]) => {
31
+ const { isAlias, variableName } = isAliasVariable(value);
32
+ const variableValue = isAlias ? options.aliasTransformer(variableName) : value;
33
+ return ` ${options.nameTransformer(name)}: ${variableValue};`;
34
+ });
35
+ const timestamp = new Date().toUTCString();
36
+ const mode = options.data.modeName;
37
+ return `/**
38
+ * Do not edit directly.${mode ? `\n * This file contains the specific variables for the "${mode}" theme.` : ""}
39
+ * Imported from Figma API on ${timestamp}
40
+ */
41
+ :root {\n${variableContent.join("\n")}\n}\n`;
42
+ };
43
+ /**
44
+ * Checks whether the given variable value is an alias / variable reference to another variable.
45
+ * Alias values are enclosed by curly braces.
46
+ *
47
+ * @example "{your-variable-name}"
48
+ * @returns `isAlias` whether the variable is an alias and `variableName` the raw variable name without curly braces.
49
+ */
50
+ export const isAliasVariable = (variableValue) => {
51
+ const isAlias = /{.*}/.exec(variableValue);
52
+ const variableName = variableValue.replace("{", "").replace("}", "");
53
+ return { isAlias, variableName };
54
+ };
@@ -0,0 +1,42 @@
1
+ import { FigmaVariablesApiResponse, ParsedVariable, RGBAValue, Variable, VariableValue } from "../types/figma.js";
2
+ export type ParseFigmaVariablesOptions = {
3
+ /**
4
+ * Base for converting pixel in rem. Set to `false` for disabling rem conversion and use pixel values.
5
+ * @default 16
6
+ */
7
+ remBase?: number | false;
8
+ };
9
+ /** Default Figma mode name if only one mode exists and no other name is specified by the designer. */
10
+ export declare const DEFAULT_MODE_NAME: "Mode 1";
11
+ /**
12
+ * Parses Figma variables received from the Figma API to a minimal JSON.
13
+ * Numeric / pixel values will be transformed to rem.
14
+ * Variables / collections that are hidden from publishing will not be parsed.
15
+ *
16
+ * @param apiResponse Variables response body received from the Figma API.
17
+ */
18
+ export declare const parseFigmaVariables: (apiResponse: FigmaVariablesApiResponse, options?: ParseFigmaVariablesOptions) => ParsedVariable[];
19
+ /**
20
+ * Resolves the given Figma variable value to a string value. Value types:
21
+ * - number: converted to rem, e.g. 16 => "1rem"
22
+ * - color: converted to HEX color, e.g. {r:1, g: 1, b: 1, a: 1} => "#ffffff"
23
+ * - alias: referenced with variable name, e.g. "--primary-100" => "{--primary-100}"
24
+ * (curly brackets will indicate that the value is an alias / reference)
25
+ *
26
+ * @param value Figma variable value
27
+ * @param allVariables Object of all variables. Needed for variables that use aliases.
28
+ */
29
+ export declare const resolveFigmaVariableValue: (value: VariableValue, allVariables: Record<string, Variable>, remBase?: ParseFigmaVariablesOptions["remBase"]) => string;
30
+ /**
31
+ * Converts a RGBA value to a hex color.
32
+ * Transparency will only be added if its not 1, e.g. "#000000" instead of "#000000ff"
33
+ */
34
+ export declare const rgbaToHex: (value: RGBAValue) => string;
35
+ /**
36
+ * Normalizes the given variable name by apply these transformations:
37
+ * - replace slashes with "-"
38
+ * - replace whitespace with "-"
39
+ * - replace "+" with "-"
40
+ * - replace "&" with "-"
41
+ */
42
+ export declare const normalizeVariableName: (name: string) => string;
@@ -0,0 +1,98 @@
1
+ /** Default Figma mode name if only one mode exists and no other name is specified by the designer. */
2
+ export const DEFAULT_MODE_NAME = "Mode 1";
3
+ /**
4
+ * Parses Figma variables received from the Figma API to a minimal JSON.
5
+ * Numeric / pixel values will be transformed to rem.
6
+ * Variables / collections that are hidden from publishing will not be parsed.
7
+ *
8
+ * @param apiResponse Variables response body received from the Figma API.
9
+ */
10
+ export const parseFigmaVariables = (apiResponse, options) => {
11
+ const parsedData = [];
12
+ /**
13
+ * Loop through each variable and mode and create a new object.
14
+ */
15
+ Object.values(apiResponse.meta.variables).forEach((variable) => {
16
+ const collection = apiResponse.meta.variableCollections[variable.variableCollectionId];
17
+ if (variable.hiddenFromPublishing || collection.hiddenFromPublishing)
18
+ return;
19
+ // parse variable value for every mode
20
+ Object.values(collection.modes).forEach((mode) => {
21
+ const variableName = normalizeVariableName(variable.name);
22
+ const variableValue = resolveFigmaVariableValue(variable.valuesByMode?.[mode.modeId], apiResponse.meta.variables, options?.remBase);
23
+ // add/update parsed variable value
24
+ const existingIndex = parsedData.findIndex((i) => i.modeName === mode.name);
25
+ if (existingIndex !== -1) {
26
+ parsedData[existingIndex].variables[variableName] = variableValue;
27
+ }
28
+ else {
29
+ parsedData.push({
30
+ modeName: mode.name,
31
+ variables: { [variableName]: variableValue },
32
+ });
33
+ }
34
+ });
35
+ });
36
+ parsedData.forEach((data) => {
37
+ if (data.modeName === "DEFAULT_MODE_NAME")
38
+ delete data.modeName;
39
+ });
40
+ return parsedData;
41
+ };
42
+ /**
43
+ * Resolves the given Figma variable value to a string value. Value types:
44
+ * - number: converted to rem, e.g. 16 => "1rem"
45
+ * - color: converted to HEX color, e.g. {r:1, g: 1, b: 1, a: 1} => "#ffffff"
46
+ * - alias: referenced with variable name, e.g. "--primary-100" => "{--primary-100}"
47
+ * (curly brackets will indicate that the value is an alias / reference)
48
+ *
49
+ * @param value Figma variable value
50
+ * @param allVariables Object of all variables. Needed for variables that use aliases.
51
+ */
52
+ export const resolveFigmaVariableValue = (value, allVariables, remBase = 16) => {
53
+ if (typeof value === "number") {
54
+ // numeric value, parse as rem or pixel value
55
+ if (value === 0)
56
+ return "0";
57
+ if (remBase === false || remBase <= 0)
58
+ return `${value}px`;
59
+ return `${value / remBase}rem`;
60
+ }
61
+ if ("type" in value) {
62
+ // parse value as alias
63
+ if (value.type !== "VARIABLE_ALIAS") {
64
+ throw new Error(`Unknown variable value type: ${value.type}`);
65
+ }
66
+ const reference = allVariables[value.id];
67
+ if (!reference) {
68
+ throw new Error(`Could not find variables alias with ID "${value.id}"`);
69
+ }
70
+ return `{${normalizeVariableName(reference.name)}}`;
71
+ }
72
+ return rgbaToHex(value);
73
+ };
74
+ /**
75
+ * Converts a RGBA value to a hex color.
76
+ * Transparency will only be added if its not 1, e.g. "#000000" instead of "#000000ff"
77
+ */
78
+ export const rgbaToHex = (value) => {
79
+ const hex = Object.values(value)
80
+ .map((color) => Math.floor(color * 255))
81
+ .map((color) => color.toString(16))
82
+ .map((color) => color.padStart(2, "0"))
83
+ .join("")
84
+ .replace(/^/, "#");
85
+ if (value.a === 1)
86
+ return hex.substring(0, hex.length - 2);
87
+ return hex;
88
+ };
89
+ /**
90
+ * Normalizes the given variable name by apply these transformations:
91
+ * - replace slashes with "-"
92
+ * - replace whitespace with "-"
93
+ * - replace "+" with "-"
94
+ * - replace "&" with "-"
95
+ */
96
+ export const normalizeVariableName = (name) => {
97
+ return name.replaceAll("/", "-").replaceAll(" ", "-").replaceAll("+", "-").replaceAll("&", "-");
98
+ };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@sit-onyx/figma-utils",
3
+ "description": "Utility functions and CLI for importing data from the Figma API into CSS/SCSS variables",
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "bin": {
7
+ "@sit-onyx/figma-utils": "./dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "dependencies": {
22
+ "commander": "^11.1.0"
23
+ },
24
+ "scripts": {
25
+ "build": "rimraf dist && tsc",
26
+ "@sit-onyx/figma-utils": "node ./dist/cli.js"
27
+ }
28
+ }