figma-utils.ts•2.08 kB
import type { Component, ComponentSet } from "@figma/rest-api-spec";
/**
* Removes null and undefined values from an array.
*/
export const compact = (arr: any[]): any[] => {
return arr.filter((item) => item !== null && item !== undefined && item !== "");
};
/**
* Extracts file key and node ID from a Figma URL.
*/
export const getFigmaFileKeyAndNodeId = (
url: string
): { fileKey: string | null; nodeId: string | null } => {
const urlObj = new URL(url);
const searchParams = urlObj.searchParams;
const pathnames = urlObj.pathname.split("/");
const fileKey = pathnames[2];
const nodeId = searchParams.get("node-id");
return {
fileKey: fileKey && fileKey.length > 0 ? fileKey : null,
nodeId: nodeId ?? null,
};
};
/**
* Determines if an element is visible.
*/
export const isVisible = (element: { visible?: boolean }): boolean => {
return element.visible ?? true;
};
/**
* Simplifies component data from Figma API response.
* Extracts only the necessary properties needed for component processing.
*/
export const sanitizeComponents = (
aggregatedComponents: Record<string, Component>
): Record<
string,
{
id: string;
key: string;
name: string;
componentSetId: string | null | undefined;
}
> => {
return Object.fromEntries(
Object.entries(aggregatedComponents).map(([id, comp]) => [
id,
{
id,
key: comp.key,
name: comp.name,
componentSetId: comp.componentSetId,
},
])
);
};
/**
* Simplifies component set data from Figma API response.
* Extracts only the necessary properties needed for component set processing.
*/
export const sanitizeComponentSets = (
aggregatedComponentSets: Record<string, ComponentSet>
): Record<
string,
{ id: string; key: string; name: string; description: string | undefined }
> => {
return Object.fromEntries(
Object.entries(aggregatedComponentSets).map(([id, set]) => [
id,
{
id,
key: set.key,
name: set.name,
description: set.description,
},
])
);
};