@figma-vars/hooks 1.3.3 → 1.4.3

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.
Files changed (46) hide show
  1. package/README.md +85 -19
  2. package/dist/figma-vars-hooks.js +312 -296
  3. package/dist/figma-vars-hooks.umd.cjs +3 -3
  4. package/dist/src/api/fetcher.d.ts +28 -0
  5. package/dist/src/api/index.d.ts +25 -0
  6. package/dist/src/api/mutator.d.ts +33 -0
  7. package/dist/src/api/mutator.test.d.ts +1 -0
  8. package/dist/src/constants/index.d.ts +89 -0
  9. package/dist/src/contexts/FigmaVarsProvider.d.ts +56 -0
  10. package/dist/src/contexts/index.d.ts +21 -0
  11. package/dist/src/hooks/index.d.ts +143 -0
  12. package/dist/src/hooks/useBulkUpdateVariables.d.ts +46 -0
  13. package/dist/src/hooks/useCreateVariable.d.ts +45 -0
  14. package/dist/src/hooks/useDeleteVariable.d.ts +33 -0
  15. package/dist/src/hooks/useFigmaToken.d.ts +21 -0
  16. package/dist/src/hooks/useMutation.d.ts +53 -0
  17. package/dist/src/hooks/useUpdateVariable.d.ts +40 -0
  18. package/dist/src/hooks/useVariableCollections.d.ts +35 -0
  19. package/dist/src/hooks/useVariableModes.d.ts +32 -0
  20. package/dist/src/hooks/useVariables.d.ts +32 -0
  21. package/dist/src/index.d.ts +80 -0
  22. package/dist/src/types/contexts.d.ts +77 -0
  23. package/dist/src/types/figma.d.ts +244 -0
  24. package/dist/src/types/hooks.d.ts +67 -0
  25. package/dist/src/types/index.d.ts +30 -0
  26. package/dist/src/types/mutations.d.ts +314 -0
  27. package/dist/src/utils/filterVariables.d.ts +31 -0
  28. package/dist/src/utils/index.d.ts +21 -0
  29. package/dist/tests/FigmaVarsProvider.test.d.ts +1 -0
  30. package/dist/tests/api/fetcher.test.d.ts +1 -0
  31. package/dist/tests/api/mutator.test.d.ts +1 -0
  32. package/dist/tests/constants/index.test.d.ts +1 -0
  33. package/dist/tests/hooks/useBulkUpdateVariables.test.d.ts +1 -0
  34. package/dist/tests/hooks/useCreateVariable.test.d.ts +1 -0
  35. package/dist/tests/hooks/useDeleteVariable.test.d.ts +1 -0
  36. package/dist/tests/hooks/useMutation.test.d.ts +1 -0
  37. package/dist/tests/hooks/useUpdateVariable.test.d.ts +1 -0
  38. package/dist/tests/hooks/useVariableCollections.test.d.ts +1 -0
  39. package/dist/tests/hooks/useVariableModes.test.d.ts +1 -0
  40. package/dist/tests/hooks/useVariables.test.d.ts +1 -0
  41. package/dist/tests/mocks/variables.d.ts +2 -0
  42. package/dist/tests/setup.d.ts +0 -0
  43. package/dist/tests/test-utils.d.ts +10 -0
  44. package/dist/tests/test-utils.test.d.ts +1 -0
  45. package/package.json +4 -2
  46. package/dist/index.d.ts +0 -1221
@@ -0,0 +1,53 @@
1
+ import { MutationState, MutationResult } from '../types/mutations';
2
+ type MutationStatus = 'idle' | 'loading' | 'success' | 'error';
3
+ /**
4
+ * Internal reducer to manage async mutation state for all mutation hooks.
5
+ *
6
+ * @remarks
7
+ * Handles mutation status transitions (`loading`, `success`, `error`) and enforces consistent error/data handling across the library.
8
+ * Used by {@link useMutation} and not intended for direct use in external code.
9
+ *
10
+ * @typeParam TData - The type of data returned by the mutation.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { mutationReducer } from '@figma-vars/hooks';
15
+ * const [state, dispatch] = useReducer(mutationReducer, initialState);
16
+ * // Internal pattern for mutation state management
17
+ * ```
18
+ *
19
+ * @internal
20
+ */
21
+ export declare function mutationReducer<TData>(state: MutationState<TData>, action: {
22
+ type: MutationStatus;
23
+ payload?: TData | Error;
24
+ }): MutationState<TData>;
25
+ /**
26
+ * Internal React hook for async mutation state, status flags, and mutation trigger.
27
+ *
28
+ * @remarks
29
+ * Returns a mutation object with status, error, and result data. Preferred pattern: use higher-level hooks (e.g., `useCreateVariable`, `useUpdateVariable`) rather than using this directly in production code.
30
+ * The provided `mutationFn` must be an async function that performs the actual mutation (API call, etc). See example for pattern.
31
+ *
32
+ * @typeParam TData - Type returned by the mutation.
33
+ * @typeParam TPayload - Payload accepted by the mutation function.
34
+ * @param mutationFn - Async function performing the mutation logic.
35
+ * @returns Mutation state, status flags, and a `mutate(payload)` trigger function.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { useMutation } from '@figma-vars/hooks';
40
+ *
41
+ * // Example: use for custom async logic
42
+ * const { mutate, isLoading, isSuccess, error } = useMutation(async (payload: MyPayload) => {
43
+ * // Your async mutation logic here (e.g., API call)
44
+ * return result;
45
+ * });
46
+ *
47
+ * // Call mutate(payload) to trigger the mutation.
48
+ * ```
49
+ *
50
+ * @internal
51
+ */
52
+ export declare const useMutation: <TData, TPayload>(mutationFn: (payload: TPayload) => Promise<TData>) => MutationResult<TData, TPayload>;
53
+ export {};
@@ -0,0 +1,40 @@
1
+ import { UpdateVariableArgs } from '../types/hooks';
2
+ /**
3
+ * React hook that updates a Figma variable by its ID via the Figma Variables API.
4
+ *
5
+ * @remarks
6
+ * Returns a mutation object with status flags, error info, and a trigger function. Call `mutate({ variableId, payload })` to update a variable—provide the target variable's ID and the update payload.
7
+ * Throws if the Figma Personal Access Token (PAT) is missing from context.
8
+ * Use for advanced UI tooling or bulk edit workflows.
9
+ *
10
+ * @see {@link https://www.figma.com/developers/api#variables | Figma Variables API}
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * import { useUpdateVariable } from '@figma-vars/hooks';
15
+ *
16
+ * function UpdateVariableButton({ variableId }: { variableId: string }) {
17
+ * const { mutate, isLoading, isSuccess, error } = useUpdateVariable();
18
+ *
19
+ * const handleUpdate = () => {
20
+ * mutate({
21
+ * variableId,
22
+ * payload: {
23
+ * name: 'Updated Name',
24
+ * description: 'Updated description',
25
+ * },
26
+ * });
27
+ * };
28
+ *
29
+ * if (!mutate) return <div>Not authorized. Figma token missing.</div>;
30
+ * if (isLoading) return <div>Updating variable…</div>;
31
+ * if (error) return <div style={{ color: 'red' }}>Error: {error.message}</div>;
32
+ * if (isSuccess) return <div>Variable updated successfully!</div>;
33
+ *
34
+ * return <button onClick={handleUpdate}>Update Variable</button>;
35
+ * }
36
+ * ```
37
+ *
38
+ * @public
39
+ */
40
+ export declare const useUpdateVariable: () => import('..').MutationResult<any, UpdateVariableArgs>;
@@ -0,0 +1,35 @@
1
+ import { FigmaCollection } from 'types';
2
+ /**
3
+ * React hook that extracts and memoizes all variable collections from loaded Figma variables data.
4
+ *
5
+ * @remarks
6
+ * Returns an object with:
7
+ * - `collections`: an array of all variable collections
8
+ * - `collectionsById`: a lookup table mapping collection IDs to FigmaCollection objects
9
+ * Useful for building UI pickers, mapping, and variable management tools.
10
+ *
11
+ * Call this hook anywhere you need fast, up-to-date access to collections for the current file context.
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * import { useVariableCollections } from '@figma-vars/hooks';
16
+ *
17
+ * function CollectionList() {
18
+ * const { collections } = useVariableCollections();
19
+ * if (!collections.length) return <div>No collections found.</div>;
20
+ * return (
21
+ * <ul>
22
+ * {collections.map(col => (
23
+ * <li key={col.id}>{col.name}</li>
24
+ * ))}
25
+ * </ul>
26
+ * );
27
+ * }
28
+ * ```
29
+ *
30
+ * @public
31
+ */
32
+ export declare const useVariableCollections: () => {
33
+ collections: FigmaCollection[];
34
+ collectionsById: Record<string, FigmaCollection>;
35
+ };
@@ -0,0 +1,32 @@
1
+ import { UseVariableModesResult } from '../types/hooks';
2
+ /**
3
+ * React hook that extracts and memoizes all variable modes from loaded Figma variables data.
4
+ *
5
+ * @remarks
6
+ * Returns an object with:
7
+ * - `modes`: an array of all modes
8
+ * - `modesByCollectionId`: a lookup table mapping collection IDs to arrays of modes
9
+ * - `modesById`: a lookup table mapping mode IDs to VariableMode objects
10
+ *
11
+ * Useful for building UI pickers, mapping, advanced theme controls, or custom variable management tools. Call this hook anywhere you need fast, up-to-date access to modes for the current file context.
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * import { useVariableModes } from '@figma-vars/hooks';
16
+ *
17
+ * function ModeList() {
18
+ * const { modes } = useVariableModes();
19
+ * if (!modes.length) return <div>No modes found.</div>;
20
+ * return (
21
+ * <ul>
22
+ * {modes.map(mode => (
23
+ * <li key={mode.modeId}>{mode.name}</li>
24
+ * ))}
25
+ * </ul>
26
+ * );
27
+ * }
28
+ * ```
29
+ *
30
+ * @public
31
+ */
32
+ export declare const useVariableModes: () => UseVariableModesResult;
@@ -0,0 +1,32 @@
1
+ import { SWRResponse } from 'swr';
2
+ import { LocalVariablesResponse } from 'types';
3
+ /**
4
+ * React hook that fetches all local variables, collections, and modes for the current Figma file via the Variables API.
5
+ *
6
+ * @remarks
7
+ * Returns an object with SWR state for the Figma local variables endpoint, including:
8
+ * - `data`: the variables response object (or undefined)
9
+ * - `isLoading`: boolean loading state
10
+ * - `isValidating`: boolean validation state
11
+ * - `error`: error object (if any)
12
+ *
13
+ * Use this as the single source of truth for all variables, collections, and modes within the current file context.
14
+ *
15
+ * @see {@link https://www.figma.com/developers/api#variables | Figma Variables API}
16
+ *
17
+ * @example
18
+ * ```tsx
19
+ * import { useVariables } from '@figma-vars/hooks';
20
+ *
21
+ * function VariablesPanel() {
22
+ * const { data, isLoading, error } = useVariables();
23
+ * if (isLoading) return <span>Loading variables…</span>;
24
+ * if (error) return <span style={{ color: 'red' }}>Error: {error.message}</span>;
25
+ * if (!data) return <span>No variables found.</span>;
26
+ * return <pre>{JSON.stringify(data, null, 2)}</pre>;
27
+ * }
28
+ * ```
29
+ *
30
+ * @public
31
+ */
32
+ export declare const useVariables: () => SWRResponse<LocalVariablesResponse>;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * Entry point for **@figma-vars/hooks** — a modern, idiomatic React hooks library for Figma Variables via the REST API.
5
+ *
6
+ * @remarks
7
+ * Exposes all providers, hooks, utilities, and types needed to build robust Figma variable dashboards, plugins, and design system tools.
8
+ * Each export group below has its own summary and real-world usage example for rapid onboarding and type-safe integration.
9
+ *
10
+ * MIT Licensed. Author: Mark Learst.
11
+ * Docs: {@link https://github.com/marklearst/figma-vars-hooks}
12
+ */
13
+ /**
14
+ * React context provider for Figma API authentication and file scoping.
15
+ *
16
+ * @remarks
17
+ * Wrap your app in this provider to supply the Figma Personal Access Token and file key globally—all hooks and utilities will use this context.
18
+ * This ensures seamless, type-safe access to the Figma REST API for all child components.
19
+ *
20
+ * @example
21
+ * ```tsx
22
+ * import { FigmaVarsProvider } from '@figma-vars/hooks';
23
+ *
24
+ * function App() {
25
+ * return (
26
+ * <FigmaVarsProvider token={process.env.FIGMA_TOKEN} fileKey="your-file-key">
27
+ * <YourComponent />
28
+ * </FigmaVarsProvider>
29
+ * );
30
+ * }
31
+ * ```
32
+ */
33
+ export { FigmaVarsProvider } from 'contexts';
34
+ /**
35
+ * Core React hooks for interacting with Figma Variables.
36
+ *
37
+ * @remarks
38
+ * Hooks for fetching, creating, updating, deleting, and bulk updating Figma variables—plus selectors for collections and modes.
39
+ * All hooks share idiomatic return shapes and error handling for rapid UI and API integration.
40
+ * Use these hooks to build dashboards, plugins, and design system tools with minimal boilerplate and maximum type safety.
41
+ *
42
+ * @see {@link https://www.figma.com/developers/api#variables | Figma Variables API}
43
+ *
44
+ * @example
45
+ * ```tsx
46
+ * import { useVariables, useCreateVariable } from '@figma-vars/hooks';
47
+ *
48
+ * function Example() {
49
+ * const { data, isLoading } = useVariables();
50
+ * const { mutate } = useCreateVariable();
51
+ * // Use the hooks in your component logic
52
+ * }
53
+ * ```
54
+ */
55
+ export { useVariables, useVariableCollections, useVariableModes, useCreateVariable, useUpdateVariable, useDeleteVariable, useBulkUpdateVariables, } from 'hooks';
56
+ /**
57
+ * Utility functions for Figma Variable management.
58
+ *
59
+ * @remarks
60
+ * Helpers like `filterVariables` for searching and filtering variable lists. All utilities are stateless and type-safe—use for UI filtering, scripting, and dashboard logic.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * import { filterVariables } from '@figma-vars/hooks';
65
+ * const filtered = filterVariables(variables, { resolvedType: 'COLOR' });
66
+ * ```
67
+ */
68
+ export { filterVariables } from 'utils';
69
+ /**
70
+ * All official TypeScript types for advanced usage and type-safe integration.
71
+ *
72
+ * @remarks
73
+ * All Figma domain models, mutation payloads/results, and provider context types—imported as needed for advanced TypeScript, API wrappers, plugins, and custom hooks.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * import type { FigmaVariable, CreateVariablePayload } from '@figma-vars/hooks';
78
+ * ```
79
+ */
80
+ export * from 'types';
@@ -0,0 +1,77 @@
1
+ import { ReactNode } from 'react';
2
+ /**
3
+ * Central context shape for FigmaVars—provides authentication and file context to all hooks and consumers in the tree.
4
+ *
5
+ * @remarks
6
+ * - `token`: Figma Personal Access Token (PAT) for authenticating Figma REST API requests. You can generate a PAT in your Figma account settings (https://www.figma.com/developers/api#access-tokens).
7
+ * - `fileKey`: Figma file key uniquely identifying the current Figma file context. You can find the file key in the Figma file URL—it is the string after `/file/` and before the next `/` (e.g., https://www.figma.com/file/<fileKey>/...).
8
+ *
9
+ * This type defines the single source of truth for authentication and file context, available via the FigmaVarsProvider context and typically accessed using `useFigmaTokenContext`.
10
+ * All variable, collection, and mode hooks rely on this context to determine scope and authorization.
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * import { useFigmaTokenContext } from '@figma-vars/hooks';
15
+ *
16
+ * function TokenStatus() {
17
+ * const { token, fileKey } = useFigmaTokenContext();
18
+ * if (!token) return <div>Figma API token missing.</div>;
19
+ * return <div>
20
+ * <div>Token: {token.slice(0, 4)}... (hidden)</div>
21
+ * <div>File key: {fileKey}</div>
22
+ * </div>;
23
+ * }
24
+ * ```
25
+ *
26
+ * @public
27
+ */
28
+ export interface FigmaTokenContextType {
29
+ /**
30
+ * Figma Personal Access Token (PAT), or null if not set. Required for all authenticated Figma REST API operations.
31
+ * Generate a PAT in Figma account settings: https://www.figma.com/developers/api#access-tokens
32
+ */
33
+ token: string | null;
34
+ /**
35
+ * Figma file key for the current file context, or null if not set.
36
+ * The file key is the string after '/file/' in a Figma file URL (e.g., https://www.figma.com/file/<fileKey>/...).
37
+ */
38
+ fileKey: string | null;
39
+ }
40
+ /**
41
+ * Props for the FigmaVarsProvider component, which injects Figma API authentication and file scoping for all descendant hooks and utilities.
42
+ *
43
+ * @remarks
44
+ * - `children`: React nodes to render within the provider—this wraps your app, feature, or test tree.
45
+ * - `token`: Figma Personal Access Token (PAT) for authenticating API calls. Obtain one in your Figma account settings: https://www.figma.com/developers/api#access-tokens
46
+ * - `fileKey`: Figma file key identifying the file to scope all variable/collection operations to. Extract the file key from your Figma file URL: https://www.figma.com/file/<fileKey>/...
47
+ *
48
+ * Use this to wrap your application, dashboard, or Storybook preview, ensuring all consumers have access to the proper Figma API context and authentication.
49
+ *
50
+ * @example
51
+ * ```tsx
52
+ * import { FigmaVarsProvider } from '@figma-vars/hooks';
53
+ *
54
+ * // At the root of your app:
55
+ * <FigmaVarsProvider token={myToken} fileKey={myFileKey}>
56
+ * <App />
57
+ * </FigmaVarsProvider>
58
+ * ```
59
+ *
60
+ * @public
61
+ */
62
+ export interface FigmaVarsProviderProps {
63
+ /**
64
+ * The React nodes to render inside the provider.
65
+ */
66
+ children: ReactNode;
67
+ /**
68
+ * Figma Personal Access Token (PAT) to inject into context. Required for all authenticated API operations.
69
+ * Generate your PAT in Figma account settings: https://www.figma.com/developers/api#access-tokens
70
+ */
71
+ token: string | null;
72
+ /**
73
+ * Figma file key (ID) to provide context for all variable and collection operations.
74
+ * The file key is found in the Figma file URL, after `/file/` and before the next `/` (e.g., https://www.figma.com/file/<fileKey>/...).
75
+ */
76
+ fileKey: string | null;
77
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Enum of supported variable value types in Figma.
3
+ *
4
+ * @remarks
5
+ * Used as the `resolvedType` for Figma variables—defines if the value is a boolean, float, string, or color.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const type: ResolvedType = 'COLOR'
10
+ * ```
11
+ *
12
+ * @public
13
+ */
14
+ export type ResolvedType = 'BOOLEAN' | 'FLOAT' | 'STRING' | 'COLOR';
15
+ /**
16
+ * Enum of all valid Figma variable scopes.
17
+ *
18
+ * @remarks
19
+ * Scopes define where a variable can be referenced or applied (e.g., fills, text content, opacity, effects).
20
+ * Use this to restrict variables to certain design properties in the Figma UI or API.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const scopes: VariableScope[] = ['ALL_FILLS', 'TEXT_CONTENT']
25
+ * ```
26
+ *
27
+ * @public
28
+ */
29
+ export type VariableScope = 'ALL_SCOPES' | 'TEXT_CONTENT' | 'CORNER_RADIUS' | 'WIDTH_HEIGHT' | 'GAP' | 'STROKE_FLOAT' | 'OPACITY' | 'EFFECT_FLOAT' | 'FONT_WEIGHT' | 'FONT_SIZE' | 'LINE_HEIGHT' | 'LETTER_SPACING' | 'PARAGRAPH_SPACING' | 'PARAGRAPH_INDENT' | 'FONT_FAMILY' | 'FONT_STYLE' | 'FONT_VARIATIONS' | 'ALL_FILLS' | 'FRAME_FILL' | 'SHAPE_FILL' | 'TEXT_FILL' | 'STROKE_COLOR' | 'EFFECT_COLOR';
30
+ /**
31
+ * RGBA color value used by Figma variables of type COLOR.
32
+ *
33
+ * @remarks
34
+ * Each component is a float between 0 and 1 (inclusive), matching the Figma API spec.
35
+ * Used for color values in variable payloads and responses.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const color: Color = { r: 0.5, g: 0.8, b: 0.2, a: 1 }
40
+ * ```
41
+ *
42
+ * @public
43
+ */
44
+ export interface Color {
45
+ /** Red channel, 0–1 */
46
+ r: number;
47
+ /** Green channel, 0–1 */
48
+ g: number;
49
+ /** Blue channel, 0–1 */
50
+ b: number;
51
+ /** Alpha channel, 0–1 (opacity) */
52
+ a: number;
53
+ }
54
+ /**
55
+ * Value representing a variable alias reference in Figma.
56
+ *
57
+ * @remarks
58
+ * Used when a variable references another variable via aliasing. Type should always be 'VARIABLE_ALIAS'.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * const alias: VariableAlias = { type: 'VARIABLE_ALIAS', id: 'VariableID:123:456' }
63
+ * ```
64
+ *
65
+ * @public
66
+ */
67
+ export interface VariableAlias {
68
+ /** Type identifier for variable alias objects. Always 'VARIABLE_ALIAS'. */
69
+ type: 'VARIABLE_ALIAS';
70
+ /** The referenced variable's Figma variable ID. */
71
+ id: string;
72
+ }
73
+ /**
74
+ * Union of all supported Figma variable value types.
75
+ *
76
+ * - string, boolean, number, Color, or VariableAlias
77
+ *
78
+ * Used in payloads and responses for Figma variable APIs.
79
+ *
80
+ * @public
81
+ */
82
+ export type VariableValue = string | boolean | number | Color | VariableAlias;
83
+ /**
84
+ * Model of a single Figma variable, including metadata, values by mode, and collection info.
85
+ *
86
+ * @remarks
87
+ * Core unit for all Figma variable APIs. Includes value definitions, metadata, type info, and publishing flags. Variables are always associated with a collection and may have different values per mode.
88
+ *
89
+ * @property id - Unique Figma variable ID
90
+ * @property name - Human-readable variable name
91
+ * @property variableCollectionId - Parent collection ID
92
+ * @property resolvedType - Data type for this variable (BOOLEAN, FLOAT, STRING, or COLOR)
93
+ * @property valuesByMode - Map of mode IDs to variable values (by type)
94
+ * @property description - Optional freeform description
95
+ * @property hiddenFromPublishing - If true, this variable is hidden from publishing
96
+ * @property scopes - Array of allowed or assigned Figma variable scopes
97
+ * @property codeSyntax - Map of language IDs to code sample strings for this variable
98
+ * @property updatedAt - ISO8601 timestamp of last update
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const variable: FigmaVariable = {
103
+ * id: 'VariableID:123:456',
104
+ * name: 'Primary Color',
105
+ * variableCollectionId: 'VariableCollectionId:789:012',
106
+ * resolvedType: 'COLOR',
107
+ * valuesByMode: { 'MODE:dark': { r: 0, g: 0, b: 0, a: 1 } },
108
+ * description: 'Main brand color',
109
+ * hiddenFromPublishing: false,
110
+ * scopes: ['ALL_FILLS'],
111
+ * codeSyntax: { css: 'var(--primary-color)' },
112
+ * updatedAt: '2024-06-21T23:59:59Z',
113
+ * }
114
+ * ```
115
+ *
116
+ * @public
117
+ */
118
+ export interface FigmaVariable {
119
+ id: string;
120
+ name: string;
121
+ variableCollectionId: string;
122
+ resolvedType: ResolvedType;
123
+ valuesByMode: Record<string, VariableValue>;
124
+ description: string;
125
+ hiddenFromPublishing: boolean;
126
+ scopes: VariableScope[];
127
+ codeSyntax: Record<string, string>;
128
+ updatedAt: string;
129
+ }
130
+ /**
131
+ * Model of a Figma variable mode (e.g., Light, Dark, Custom).
132
+ *
133
+ * @remarks
134
+ * Modes are used to provide variable overrides for different states (themes, breakpoints, etc.).
135
+ * Each collection may define its own set of modes.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * const mode: VariableMode = { modeId: 'MODE:dark', name: 'Dark' }
140
+ * ```
141
+ *
142
+ * @public
143
+ */
144
+ export interface VariableMode {
145
+ /** Unique mode ID */
146
+ modeId: string;
147
+ /** Human-readable mode name */
148
+ name: string;
149
+ }
150
+ /**
151
+ * Model of a Figma variable collection (grouping of related variables and modes).
152
+ *
153
+ * @remarks
154
+ * Collections define shared settings, available modes, and membership of variables. Used as the organizing tier for all variable operations.
155
+ *
156
+ * @property id - Unique Figma collection ID
157
+ * @property name - Human-readable collection name
158
+ * @property modes - List of VariableMode objects
159
+ * @property defaultModeId - The default mode for this collection
160
+ * @property variableIds - Array of IDs of variables in this collection
161
+ * @property hiddenFromPublishing - If true, collection is hidden from publishing
162
+ * @property updatedAt - ISO8601 timestamp of last update
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const collection: FigmaCollection = {
167
+ * id: 'VariableCollectionId:789:012',
168
+ * name: 'Theme Colors',
169
+ * modes: [{ modeId: 'MODE:dark', name: 'Dark' }],
170
+ * defaultModeId: 'MODE:dark',
171
+ * variableIds: ['VariableID:123:456'],
172
+ * hiddenFromPublishing: false,
173
+ * updatedAt: '2024-06-21T23:59:59Z',
174
+ * }
175
+ * ```
176
+ *
177
+ * @public
178
+ */
179
+ export interface FigmaCollection {
180
+ id: string;
181
+ name: string;
182
+ modes: VariableMode[];
183
+ defaultModeId: string;
184
+ variableIds: string[];
185
+ hiddenFromPublishing: boolean;
186
+ updatedAt: string;
187
+ }
188
+ /**
189
+ * API response shape for the Figma Variables API local variables endpoint.
190
+ *
191
+ * @remarks
192
+ * Contains all collections and variables available in the current Figma file context.
193
+ * Use this as the source of truth for fetching and mapping Figma variable data.
194
+ *
195
+ * @property meta - Metadata object containing collections and variables.
196
+ * @property meta.variableCollections - Map of collection IDs to FigmaCollection objects.
197
+ * @property meta.variables - Map of variable IDs to FigmaVariable objects.
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * import type { LocalVariablesResponse } from '@figma-vars/hooks';
202
+ *
203
+ * function handleResponse(response: LocalVariablesResponse) {
204
+ * const collections = Object.values(response.meta.variableCollections);
205
+ * const variables = Object.values(response.meta.variables);
206
+ * }
207
+ * ```
208
+ *
209
+ * @public
210
+ */
211
+ export interface LocalVariablesResponse {
212
+ meta: {
213
+ /** Map of collection IDs to FigmaCollection objects. */
214
+ variableCollections: Record<string, FigmaCollection>;
215
+ /** Map of variable IDs to FigmaVariable objects. */
216
+ variables: Record<string, FigmaVariable>;
217
+ };
218
+ }
219
+ /**
220
+ * Standard error response shape for Figma API error objects.
221
+ *
222
+ * @remarks
223
+ * Returned by API calls when an error occurs (e.g., invalid token, not found, etc.).
224
+ *
225
+ * @property statusCode - HTTP status code returned by the Figma API.
226
+ * @property message - Human-readable error message describing the failure.
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * import type { FigmaError } from '@figma-vars/hooks';
231
+ *
232
+ * function handleError(error: FigmaError) {
233
+ * console.error(error.statusCode, error.message);
234
+ * }
235
+ * ```
236
+ *
237
+ * @public
238
+ */
239
+ export interface FigmaError {
240
+ /** HTTP status code returned by the Figma API. */
241
+ statusCode: number;
242
+ /** Human-readable error message describing the failure. */
243
+ message: string;
244
+ }
@@ -0,0 +1,67 @@
1
+ import { VariableMode } from './figma';
2
+ import { UpdateVariablePayload } from './mutations';
3
+ /**
4
+ * Arguments for updating a Figma variable via the useUpdateVariable hook.
5
+ *
6
+ * @remarks
7
+ * Use with the useUpdateVariable hook to specify which Figma variable to update and the properties to set. This enables fine-grained updates for custom UIs, bulk editors, and automation tools.
8
+ *
9
+ * @property variableId - The unique Figma variable ID to update. This can be found in variable metadata or Figma plugin dev tools.
10
+ * @property payload - The payload object with one or more variable properties to update (e.g., name, description, valuesByMode).
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import type { UpdateVariableArgs } from '@figma-vars/hooks';
15
+ *
16
+ * const args: UpdateVariableArgs = {
17
+ * variableId: 'VariableID:123:456',
18
+ * payload: { name: 'Updated Name', description: 'Updated description' }
19
+ * };
20
+ * // Pass to mutate(): mutate(args)
21
+ * ```
22
+ *
23
+ * @public
24
+ */
25
+ export interface UpdateVariableArgs {
26
+ /** The unique Figma variable ID to update. */
27
+ variableId: string;
28
+ /** The payload object with updated properties for the variable. */
29
+ payload: UpdateVariablePayload;
30
+ }
31
+ /**
32
+ * Return value of the useVariableModes hook—provides all variable modes and lookup tables for the current Figma file context.
33
+ *
34
+ * @remarks
35
+ * Returned by useVariableModes. Use this to quickly map modes by ID, by collection, or as a flat array for UI display, theming, and conditional logic.
36
+ *
37
+ * @property modes - Flat array of all VariableMode objects in the file.
38
+ * @property modesByCollectionId - Lookup map of collection IDs to arrays of VariableMode objects (for grouping modes by collection).
39
+ * @property modesById - Lookup map of mode IDs to VariableMode objects (for fast direct access).
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import { useVariableModes } from '@figma-vars/hooks';
44
+ *
45
+ * function ThemeSwitcher() {
46
+ * const { modes, modesById } = useVariableModes();
47
+ * // Build UI for switching themes based on mode names
48
+ * return (
49
+ * <select>
50
+ * {modes.map(mode => (
51
+ * <option key={mode.modeId} value={mode.modeId}>{mode.name}</option>
52
+ * ))}
53
+ * </select>
54
+ * );
55
+ * }
56
+ * ```
57
+ *
58
+ * @public
59
+ */
60
+ export interface UseVariableModesResult {
61
+ /** Flat array of all VariableMode objects in the file. */
62
+ modes: VariableMode[];
63
+ /** Lookup map of collection IDs to arrays of VariableMode objects. */
64
+ modesByCollectionId: Record<string, VariableMode[]>;
65
+ /** Lookup map of mode IDs to VariableMode objects. */
66
+ modesById: Record<string, VariableMode>;
67
+ }