Ultimate Prompt: Automate Sanity Schema & UI Component Generation from Figma Prompt: Act…
- User
Ultimate Prompt: Automate Sanity Schema & UI Component Generation from Figma
Prompt:
Act like a senior full-stack engineer, automation architect, and Sanity.io expert. You have deep expertise in developer tooling, API orchestration, Figma plugin development, and schema-driven component architectures. You also specialize in bridging design-to-code workflows by extracting design semantics from Figma and transforming them into structured backend (CMS) and frontend codebases. Objective:
Design a complete automation workflow that uses the Figma API and Python scripting to automatically:
Extract relevant design data from a Figma file. Classify each design layer or component as either a Sanity document or Sanity object schema. Generate Sanity schema code files. Generate matching reusable UI components (e.g., React/Next.js). Output everything into a ready-to-use folder structure compatible with Sanity Studio and modern frontends.Automation Goals & Technologies:
Use Figma API with an API key to extract frames, layers, component metadata, and design names. Use a Python script to orchestrate: API calls JSON parsing of Figma file data Schema inference logic Code generation for both Sanity schema and frontend components Auto-generate: /schemas/ folder with all schema files (document, object) /components/ folder with React components mapped to schema structures sanity.config.js with the right importsStep-by-Step Tasks:
Figma Parsing Layer: Describe how the Figma API can extract: Page-level frames (candidate documents) Nested layers/components (candidate objects) Element types (text, image, boolean toggles, arrays, auto-layouts) Provide code examples for parsing a Figma JSON structure. Sanity Schema Classification Logic: Write rules to classify each layer: Top-level frames named like “Home”, “About”, “Product” → document Reused components, groups, or blocks like “Hero”, “Card”, “Testimonial” → object Map Figma elements: Text → string or block Image → image Frame with repeating children → array Switches/toggles → boolean Output schema objects using proper Sanity conventions. Schema Code Generation Layer: Show Python logic (or pseudo-code) that writes: schemas/hero.js schemas/page.js with nested references Ensure correct use of Sanity’s type, fields, name, title, and nested of/type blocks. UI Component Generator: For each schema object, generate a React component with props based on the schema. Example: HeroBanner schema → HeroBanner.jsx component Use props like title, image, cta, etc. Add logic to infer layout hints (flex, grid, alignment) from Figma auto-layout settings. Folder & Output Structure: /schemas/ page.js heroBanner.js testimonialCard.js /components/ Page.jsx HeroBanner.jsx TestimonialCard.jsx sanity.config.js generate.py (automation runner script) Error Handling & Edge Cases: What happens if a Figma layer lacks a name or doesn't map clearly? Propose fallback schema types or use a YAML config file for manual overrides. Optional Enhancements: Add schema hash to each component to track sync state. Auto-generate preview components for Sanity Studio. Integrate this workflow into a CI/CD pipeline (e.g., GitHub Actions or CLI hook).Expected Output:
A working Python automation pipeline that connects to Figma, parses layers, and outputs schema/component files. A reusable methodology to infer design structure from visual layout into headless CMS data models and frontend components. Sample code snippets for both schema and component generation.Take a deep breath and work on this problem step-by-step.
Assistant
Alright, let's architect a robust automation workflow to bridge Figma designs with Sanity.io CMS and React components. This requires a deep dive into design semantics, API orchestration, and code generation.
As a senior full-stack engineer and automation architect, my approach will focus on modularity, clear classification rules, and pragmatic code generation. We'll build a
generate.pyscript as the orchestrator.The Sanity-Figma Automation Pipeline
Objective: Automatically generate Sanity schemas and corresponding React components from Figma design files, outputting them into a production-ready folder structure.
Core Philosophy: Extract design intent and structure from Figma rather than pixel-perfect replication. This translates visual hierarchy into a structured data model and reusable UI elements.
1. Figma Parsing Layer
The Figma API is our gateway to design data. We'll use the
GET /v1/files/:file_keyendpoint, which returns a comprehensive JSON representation of the Figma file.Extraction Strategy:
-
Top-Level Pages/Frames (Candidate Documents):
- Iterate through
document.childrenwhich represent top-level pages. - Within each page, look for
FRAMEnodes, especially those named like "Home Page", "About Us", "Product Details". These are strong candidates for Sanity document schemas.
- Iterate through
-
Nested Layers/Components (Candidate Objects/Fields):
- Recursively traverse the
childrenarray of eachFRAMEorGROUPnode. - Identify
COMPONENTandINSTANCEnodes. These are excellent candidates for Sanity object schemas, representing reusable UI blocks (e.g., Hero, Card, Testimonial). - Primitive
TEXT,RECTANGLE(often used for images),BOOLEAN_OPERATIONnodes will map to Sanity fields.
- Recursively traverse the
-
Element Type Mapping & Semantics:
-
Text (
TEXTnode):characters: The actual text content.style(e.g.,fontSize,lineHeightPx): Can hint at headings vs. body text.fills: Color information.- Inference:
- If
characterscontain multiple lines or seem like body copy (e.g.,lineHeightPxis standard for paragraphs), classify as Sanityblock(Portable Text). - If single-line, short, or clearly a label/heading, classify as Sanity
string. - A regex check for common headings (H1, H2) in
nameproperty can also help.
- If
-
Image (
RECTANGLEwith imagefillsor specific "Image" components):fills: Look for objects withtype: 'IMAGE'andimageRef.- Inference: Sanity
imagetype. We might need to storesrcoralttext. Figma doesn't directly store alt text, so it often needs manual input or is derived from layer names.
-
Boolean Toggles (
COMPONENTorINSTANCEnamed "Toggle", "Switch", "Checkbox"):- Figma doesn't have a native "boolean" type. Designers typically use two component variants (e.g., "Toggle/On", "Toggle/Off") or simple
RECTANGLEshapes with differentfillsstates. - Inference: If a component name contains "Toggle", "Switch", "Checkbox", or it's a small element with two clear visual states, suggest Sanity
boolean.
- Figma doesn't have a native "boolean" type. Designers typically use two component variants (e.g., "Toggle/On", "Toggle/Off") or simple
-
Arrays (
FRAMEwith Auto Layout and repeating children):layoutMode: 'VERTICAL'or'HORIZONTAL'.itemSpacing: Indicates a list.- Crucially, if the
childrenarray contains multiple instances of the same component type (e.g., several "Card" instances), it strongly suggests an array of that component's Sanity object type. - Inference: Sanity
arrayof a specific object type.
-
Auto Layout Hints (
layoutMode,primaryAxisAlignItems,counterAxisAlignItems,padding,itemSpacing): These properties within aFRAMEnode are invaluable for inferring CSS Flexbox or Grid properties.
-
Code Example (Simplified Figma JSON Parsing):
import requests import json import re # Figma API configuration FIGMA_API_BASE_URL = "https://api.figma.com/v1/files/" FIGMA_FILE_KEY = "YOUR_FIGMA_FILE_KEY" # e.g., "abcdefg123456" FIGMA_ACCESS_TOKEN = "YOUR_FIGMA_PERSONAL_ACCESS_TOKEN" HEADERS = { "X-Figma-Token": FIGMA_ACCESS_TOKEN } def fetch_figma_file(file_key): """Fetches the Figma file content.""" url = f"{FIGMA_API_BASE_URL}{file_key}" response = requests.get(url, headers=HEADERS) response.raise_for_status() return response.json() def camel_case(s): """Converts a string to camelCase.""" s = re.sub(r'[^a-zA-Z0-9_]', '', s.strip()) # Remove invalid chars if not s: return "" return s[0].lower() + re.sub(r'[^a-zA-Z0-9]', '', s[1:]).replace(" ", "").replace("-", "").replace("/", "").title() def snake_case(s): """Converts a string to snake_case.""" s = re.sub(r'[^a-zA-Z0-9_]', '', s.strip()) # Remove invalid chars s = re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower() return re.sub(r'[\s\W]+', '_', s) def parse_figma_node(node, parent_type=None): """Recursively parses a Figma node and extracts relevant data.""" parsed_data = { "id": node.get('id'), "name": node.get('name'), "type": node.get('type'), "children": [], "properties": {} # To store inferred schema properties } # Extract common properties if node.get('type') == 'TEXT': parsed_data['properties']['content'] = node.get('characters', '') # Heuristic for block vs string: If newline characters or very long if '\n' in parsed_data['properties']['content'] or len(parsed_data['properties']['content']) > 100: parsed_data['inferred_sanity_type'] = 'block' else: parsed_data['inferred_sanity_type'] = 'string' if node.get('style', {}).get('fontSize') and node.get('style', {}).get('fontSize') >= 24: # Heuristic for headings if any(re.match(r'h[1-6]', node.get('name', '').lower()) for i in range(1,7)): parsed_data['inferred_sanity_type'] = 'string' # Keep headings as string, block for body else: parsed_data['inferred_sanity_type'] = 'string' # Assume headings are string for titles elif node.get('type') == 'RECTANGLE': # Check for image fills for fill in node.get('fills', []): if fill.get('type') == 'IMAGE' and fill.get('imageRef'): parsed_data['inferred_sanity_type'] = 'image' # parsed_data['properties']['image_ref'] = fill['imageRef'] # Could store this for asset mapping break if 'inferred_sanity_type' not in parsed_data: # Default to generic object if not image parsed_data['inferred_sanity_type'] = 'object' # Generic shape elif node.get('type') == 'FRAME' or node.get('type') == 'GROUP': if node.get('layoutMode') in ['VERTICAL', 'HORIZONTAL']: parsed_data['properties']['layoutMode'] = node['layoutMode'] parsed_data['properties']['primaryAxisAlignItems'] = node.get('primaryAxisAlignItems') parsed_data['properties']['counterAxisAlignItems'] = node.get('counterAxisAlignItems') parsed_data['properties']['padding'] = { "top": node.get('paddingTop', 0), "right": node.get('paddingRight', 0), "bottom": node.get('paddingBottom', 0), "left": node.get('paddingLeft', 0), } parsed_data['properties']['itemSpacing'] = node.get('itemSpacing', 0) # Heuristic for arrays: Frame with auto-layout and multiple similar children if (node.get('layoutMode') in ['VERTICAL', 'HORIZONTAL'] and len(node.get('children', [])) > 1 and len(set(c.get('type') for c in node['children'])) == 1): # All children are same type # More sophisticated check needed here for *similar components* pass # Defer array classification to schema logic layer elif node.get('type') == 'COMPONENT' or node.get('type') == 'INSTANCE': # Attempt to infer boolean from name if re.search(r'(toggle|switch|checkbox)', node.get('name', ''), re.IGNORECASE): parsed_data['inferred_sanity_type'] = 'boolean' else: parsed_data['inferred_sanity_type'] = 'object' # Generally, components become objects # Store component variants if available if node.get('componentProperties'): parsed_data['properties']['componentProperties'] = node['componentProperties'] # Recursively parse children if node.get('children'): for child in node['children']: parsed_data['children'].append(parse_figma_node(child, node.get('type'))) return parsed_data # --- Main Parsing Execution --- # figma_data = fetch_figma_file(FIGMA_FILE_KEY) # document = figma_data['document'] # parsed_figma_tree = parse_figma_node(document) # print(json.dumps(parsed_figma_tree, indent=2))
2. Sanity Schema Classification Logic
This is the core "intelligence" of our automation. We'll traverse the parsed Figma tree and apply rules to decide what becomes a Sanity document, object, or field.
Key Principles:
- Top-Down Identification: Start with documents, then identify nested objects and their fields.
- Naming Conventions: Figma layer/component names are crucial hints.
- Structural Cues: Auto layout, repeating patterns, and component instances reveal schema relationships.
- Sanity Conventions: Use
name(camelCase for internal use),title(human-readable),type,fields,of.
Classification Rules:
-
Document vs. Object:
- Document Rule: Any top-level
FRAMEnode on a page (identified bydocument.children[i].type == 'CANVAS') whosenameclearly implies a distinct page (e.g., "Home", "About", "Product Page", "Article Details").- Example:
Home,AboutUs,BlogPost.
- Example:
- Object Rule:
- Any
COMPONENTdefinition in Figma (figma_data['components']orfigma_data['componentSets']). Each unique master component should correspond to a Sanity object schema. - Any
FRAMEorGROUPwithin a document that groups other fields and is conceptually a "section" or "block" (e.g., "Hero Section", "Product Card", "Call to Action"). - These objects will be referenced by documents or other objects, often within arrays of blocks.
- Any
- Document Rule: Any top-level
-
Field Type Mapping:
-
Text Field (
TEXTnode):- If
inferred_sanity_typeisblock:type: 'block'. - If
inferred_sanity_typeisstring:type: 'string'. - Naming: Use the Figma layer
name(e.g., "Hero Title" ->heroTitle, "Body Copy" ->bodyCopy).
- If
-
Image Field (
RECTANGLEwith image fill, or explicit "Image" component):type: 'image'.- Naming: e.g., "Hero Image" ->
heroImage.
-
Boolean Field (Inferred from "Toggle", "Switch" components):
type: 'boolean'.- Naming: e.g., "Is Active" ->
isActive.
-
Array Field (
FRAMEwith Auto Layout and repeating instances of a recognized component/object):- If
FRAMEAcontains multipleINSTANCEofCOMPONENTB:FRAME Abecomes anarrayfield.of: [{ type: 'reference', to: [{ type: 'componentBSanityObjectName' }] }]ifBis a document, orof: [{ type: 'componentBSanityObjectName' }]ifBis an object.
- Naming: e.g., "Testimonial List" ->
testimonials.
- If
-
References/Portable Text Blocks (
arrayof polymorphic types):- If a document contains multiple conceptual sections (e.g., Hero, Features, Testimonials), and these are distinct Figma components, the document will have a
bodyfield oftype: 'array'withofclauses for each possible section type. of: [{ type: 'block' }, { type: 'heroSection' }, { type: 'featuresGrid' }].
- If a document contains multiple conceptual sections (e.g., Hero, Features, Testimonials), and these are distinct Figma components, the document will have a
-
Schema Inference Logic (Python Pseudo-code):
# Assuming parsed_figma_tree is available from parse_figma_node() def infer_sanity_schemas(parsed_figma_tree): schemas = {} # { schema_name: { type: 'document/object', fields: [] } } # Track identified reusable components (master components) component_schemas = {} # { figma_component_id: sanity_object_name } # First Pass: Identify Master Components as Sanity Objects # We'd typically get these from figma_data['components'] or by finding unique component IDs # For simplicity, let's assume we find top-level instances used repeatedly # A more robust approach would pre-process figma_data['components'] # For now, let's derive them during traversal. def process_node_for_schemas(node, path=""): node_name = camel_case(node.get('name', 'unnamed_node')) # If it's a Figma COMPONENT definition (from master components, not instances) # We need to map Figma component IDs to Sanity object names. # This requires traversing figma_data['components'] directly. # For this example, let's simplify and assume any 'INSTANCE' or 'COMPONENT' type node *could* become an object. if node.get('type') in ['COMPONENT', 'INSTANCE'] and node_name not in component_schemas: # This is a candidate for a reusable Sanity object object_name = node_name object_title = node.get('name', 'Unnamed Component') component_schemas[node.get('id')] = object_name # Map Figma ID to Sanity name schemas[object_name] = { 'type': 'object', 'name': object_name, 'title': object_title, 'fields': [] } # Add fields based on children recursively for child in node['children']: field_name = camel_case(child.get('name', 'unnamed_field')) field_type = child.get('inferred_sanity_type', 'string') # Default fallback # If a child is an instance of another component, it becomes a reference or nested object if child.get('type') == 'INSTANCE' and component_schemas.get(child.get('id')): # This won't work correctly as ID is of instance # This logic needs to link Figma instance to its MASTER component, not the instance itself # Simplified: If an instance or component is identified as an object, its fields will point to its own schema. # A real impl would check child.componentId against figma_data['components'] pass else: schemas[object_name]['fields'].append({ 'name': field_name, 'title': child.get('name'), 'type': field_type, # Add 'of' for arrays, 'to' for references etc. later }) # Recursive processing for children for child in node['children']: process_node_for_schemas(child, f"{path}/{node_name}") # Step 1: Identify all potential reusable components (objects) # This needs to be done by looking at figma_data['components'] or by collecting unique instances # For this simplified example, let's process the main document and try to infer # Let's refine: Identify top-level frames on pages as documents. # Any reusable *component* in Figma becomes an object. documents_to_process = [] for page_node in parsed_figma_tree['children']: if page_node['type'] == 'CANVAS': # A Figma Page for frame_node in page_node['children']: if frame_node['type'] == 'FRAME': # A top-level frame on a page doc_name = camel_case(frame_node['name'].replace(' Page', '').replace(' Details', '')) if doc_name and doc_name not in schemas: schemas[doc_name] = { 'type': 'document', 'name': doc_name, 'title': frame_node['name'], 'fields': [] } documents_to_process.append((doc_name, frame_node)) # Step 2: Populate fields for documents and objects all_known_object_names = set() # To track objects that can be referenced def populate_schema_fields(schema_name, node): current_schema = schemas[schema_name] for child_node in node['children']: child_name = camel_case(child_node.get('name', 'unnamed_field')) child_title = child_node.get('name', 'Unnamed Field') field_definition = { 'name': child_name, 'title': child_title, } # --- Field Type Inference --- if child_node.get('type') == 'TEXT': field_definition['type'] = child_node.get('inferred_sanity_type', 'string') if field_definition['type'] == 'block': field_definition['of'] = [{ 'type': 'block' }] # Standard Portable Text config elif child_node.get('type') == 'RECTANGLE' and child_node.get('inferred_sanity_type') == 'image': field_definition['type'] = 'image' field_definition['options'] = { 'hotspot': True } # Common image option elif child_node.get('inferred_sanity_type') == 'boolean': field_definition['type'] = 'boolean' elif child_node.get('type') in ['COMPONENT', 'INSTANCE', 'FRAME', 'GROUP'] and child_node.get('name'): # Heuristic: If it's a known component, reference it. Else, create an inline object. # This part is tricky. A robust solution needs a pre-pass to register all master components. # Simplified: If the child's name matches an existing schema name, it's a reference/nested object child_schema_candidate_name = camel_case(child_node['name']) # Array inference: If a frame/group has auto-layout AND multiple children of the SAME type if child_node.get('type') in ['FRAME', 'GROUP'] and child_node.get('layoutMode') in ['VERTICAL', 'HORIZONTAL']: if len(child_node['children']) > 1 and len(set(c.get('name') for c in child_node['children'] if c.get('name'))) == 1: # This is a strong candidate for an array of a specific object type item_name_singular = camel_case(child_node['children'][0]['name'].replace('Card', '').replace('Item', '').strip()) if not item_name_singular: # Fallback if item name is too generic item_name_singular = camel_case(child_node['name'] + 'Item') # Ensure the object schema for the item exists or is created item_object_name = item_name_singular if item_object_name not in schemas: # Create a placeholder object schema for the array item if not already discovered schemas[item_object_name] = { 'type': 'object', 'name': item_object_name, 'title': child_node['children'][0]['name'], 'fields': [] # Fields will be populated by recursively processing the first child } populate_schema_fields(item_object_name, child_node['children'][0]) # Populate fields for the array item field_definition['type'] = 'array' field_definition['of'] = [{ 'type': item_object_name }] # Array of the inferred object type field_definition['title'] = child_node['name'] field_definition['name'] = camel_case(child_node['name']) all_known_object_names.add(item_object_name) # Mark as known object else: # It's a group/frame, not an array. Potentially an inline object or a reference. # If a sub-component already exists as a schema, use it. if child_schema_candidate_name in schemas and schemas[child_schema_candidate_name]['type'] == 'object': # It's a reference to an already defined object field_definition['type'] = schemas[child_schema_candidate_name]['type'] # Or if it's designed to be reusable across documents, make it a reference # field_definition['type'] = 'reference' # field_definition['to'] = [{ 'type': child_schema_candidate_name }] populate_schema_fields(child_schema_candidate_name, child_node) # Populate its fields all_known_object_names.add(child_schema_candidate_name) # Mark as known object else: # It's an inline object that hasn't been defined yet. Define it. field_definition['type'] = 'object' field_definition['fields'] = [] # Populate fields below # For simplicity, we create an inline object. # More advanced: If it's a COMPONENT, make it a top-level object schema. # For now, if it's an instance, just define its fields inline. # Recursively populate fields for this inline object populate_schema_fields_inline(field_definition['fields'], child_node) else: # Default for unclassified nodes or simple shapes field_definition['type'] = 'string' # Fallback to string or object if no other type print(f"Warning: Could not infer type for {child_node.get('name', 'unnamed_node')} ({child_node.get('type')}). Defaulting to 'string'.") # Add field definition to the current schema current_schema['fields'].append(field_definition) # Recursively populate fields for children within object definitions # This is where we define nested fields if the parent is an object or document if child_node.get('type') not in ['TEXT', 'RECTANGLE', 'BOOLEAN_OPERATION']: # Primitives # If child_node was identified as a separate top-level object schema, populate it. if child_schema_candidate_name in schemas and schemas[child_schema_candidate_name]['type'] == 'object' and child_schema_candidate_name not in all_known_object_names: populate_schema_fields(child_schema_candidate_name, child_node) all_known_object_names.add(child_schema_candidate_name) def populate_schema_fields_inline(fields_list, node): """Helper to populate fields for inline objects.""" for child_node in node['children']: child_name = camel_case(child_node.get('name', 'unnamed_field')) child_title = child_node.get('name', 'Unnamed Field') field_definition = { 'name': child_name, 'title': child_title, } if child_node.get('type') == 'TEXT': field_definition['type'] = child_node.get('inferred_sanity_type', 'string') if field_definition['type'] == 'block': field_definition['of'] = [{ 'type': 'block' }] elif child_node.get('type') == 'RECTANGLE' and child_node.get('inferred_sanity_type') == 'image': field_definition['type'] = 'image' elif child_node.get('inferred_sanity_type') == 'boolean': field_definition['type'] = 'boolean' elif child_node.get('type') in ['FRAME', 'GROUP', 'COMPONENT', 'INSTANCE']: # If it's a nested group/component, treat as inline object for simplicity field_definition['type'] = 'object' field_definition['fields'] = [] populate_schema_fields_inline(field_definition['fields'], child_node) # Recursive call for nested inline object else: field_definition['type'] = 'string' # Fallback fields_list.append(field_definition) # First, identify all potential *top-level* objects by name for future reference # This is a pre-pass to handle cross-referencing correctly. # Realistically, you'd iterate `figma_data['components']` here. # For this example, we'll scan the whole tree and look for well-named FRAME/GROUP/COMPONENT nodes # that are likely reusable. potential_objects_from_design = {} def find_potential_objects(node): if node.get('type') in ['COMPONENT', 'FRAME', 'GROUP'] and node.get('name'): node_name = camel_case(node['name']) # Heuristic: If it looks like a section/block name, consider it a top-level object if any(s in node_name.lower() for s in ['hero', 'card', 'testimonial', 'cta', 'section', 'feature', 'header', 'footer']): if node_name not in potential_objects_from_design: potential_objects_from_design[node_name] = node for child in node['children']: find_potential_objects(child) find_potential_objects(parsed_figma_tree) for obj_name, obj_node in potential_objects_from_design.items(): if obj_name not in schemas: # Only add if not already added as a document schemas[obj_name] = { 'type': 'object', 'name': obj_name, 'title': obj_node['name'], 'fields': [] } populate_schema_fields(obj_name, obj_node) all_known_object_names.add(obj_name) # Mark as known for references # Now, process documents and their content, allowing them to reference known objects for doc_name, doc_node in documents_to_process: # Docs often contain a 'body' array of polymorphic content blocks # This is where we map Figma page sections to Sanity Portable Text / block content # We need to collect all sections/blocks found on the page page_sections = [] for child in doc_node['children']: child_name = camel_case(child.get('name')) if child_name in all_known_object_names: # If it's a recognized reusable object page_sections.append({ 'type': 'reference', 'to': [{ 'type': child_name }] }) elif child.get('inferred_sanity_type') == 'block': page_sections.append({ 'type': 'block' }) # If it's a unique group/frame not registered as a reusable object, treat it as an inline object elif child.get('type') in ['FRAME', 'GROUP']: # This is a tricky part. For now, we will add its fields directly to the document. # A more advanced setup would make this an inline object type within 'body' or a dedicated field. # For this example, we'll simplify and only add already known objects to the 'body' array. pass # Skip for now to keep the `body` field clean if page_sections: schemas[doc_name]['fields'].append({ 'name': 'body', 'title': 'Page Content', 'type': 'array', 'of': page_sections # Array of block content and references to defined objects }) # Also add individual fields that might be directly on the document (e.g., page title, slug) # For simplicity, we'll rely on the `body` array for most content. # But if there's a distinct 'Page Title' text node not part of a section, add it. # Example: Add a 'title' string and 'slug' for documents if doc_name in schemas: schemas[doc_name]['fields'].insert(0, { 'name': 'slug', 'title': 'Slug', 'type': 'slug', 'options': { 'source': 'title' } }) schemas[doc_name]['fields'].insert(0, { 'name': 'title', 'title': 'Title', 'type': 'string' }) return schemas # Example Usage: # figma_data = fetch_figma_file(FIGMA_FILE_KEY) # parsed_figma_tree = parse_figma_node(figma_data['document']) # inferred_schemas = infer_sanity_schemas(parsed_figma_tree) # print(json.dumps(inferred_schemas, indent=2))Refinement Note: The schema inference is the most complex part. A real-world system would likely require a more explicit mapping configuration (e.g., "Figma component 'X' maps to Sanity object 'Y'"). The heuristic above is a starting point based purely on names and structure.
3. Schema Code Generation Layer
Now, we translate the inferred schema objects into actual JavaScript files compatible with Sanity Studio.
Python Logic:
We'll use f-strings to generate the JavaScript content.
import os def generate_schema_js(schema_name, schema_def): """Generates a Sanity schema JavaScript file.""" schema_type = schema_def['type'] schema_title = schema_def['title'] # Sanity schema definition string fields_str = [] for field in schema_def['fields']: field_name = field['name'] field_title = field['title'] field_type = field['type'] field_options = "" if field_type == 'image' and field.get('options', {}).get('hotspot'): field_options = ", options: { hotspot: true }" elif field_type == 'slug' and field.get('options', {}).get('source'): field_options = f", options: {{ source: '{field['options']['source']}' }}" field_line = f" {{\n name: '{field_name}',\n title: '{field_title}',\n type: '{field_type}'{field_options}" if field_type == 'array' and field.get('of'): of_types = [] for item_type in field['of']: if item_type['type'] == 'block': of_types.append(" { type: 'block' }") elif item_type['type'] == 'reference': to_types = ', '.join([f"{{ type: '{t['type']}' }}" for t in item_type['to']]) of_types.append(f" {{ type: 'reference', to: [{to_types}] }}") else: # It's a specific object type of_types.append(f" {{ type: '{item_type['type']}' }}") field_line += f",\n of: [\n{ ',\n'.join(of_types)}\n ]" elif field_type == 'object' and field.get('fields'): # Inline object nested_fields_str = generate_nested_fields(field['fields']) field_line += f",\n fields: [\n{nested_fields_str}\n ]" field_line += "\n }" fields_str.append(field_line) all_fields_str = ',\n'.join(fields_str) # Main schema template js_content = f"""// schemas/{schema_name}.js import {{ defineType }} from 'sanity'; export default defineType({{ name: '{schema_name}', title: '{schema_title}', type: '{schema_type}', fields: [ {all_fields_str} ] }}); """ return js_content def generate_nested_fields(fields): """Helper to generate fields for nested objects recursively.""" nested_fields_str = [] for field in fields: field_name = field['name'] field_title = field['title'] field_type = field['type'] field_line = f" {{\n name: '{field_name}',\n title: '{field_title}',\n type: '{field_type}'" if field_type == 'array' and field.get('of'): of_types = [] for item_type in field['of']: if item_type['type'] == 'block': of_types.append(" { type: 'block' }") elif item_type['type'] == 'reference': to_types = ', '.join([f"{{ type: '{t['type']}' }}" for t in item_type['to']]) of_types.append(f" {{ type: 'reference', to: [{to_types}] }}") else: # It's a specific object type of_types.append(f" {{ type: '{item_type['type']}' }}") field_line += f",\n of: [\n{ ',\n'.join(of_types)}\n ]" elif field_type == 'object' and field.get('fields'): nested_fields_str_inner = generate_nested_fields(field['fields']) field_line += f",\n fields: [\n{nested_fields_str_inner}\n ]" field_line += "\n }" nested_fields_str.append(field_line) return ',\n'.join(nested_fields_str) # --- Sanity.config.js Generation --- def generate_sanity_config(schema_names): """Generates sanity.config.js with schema imports.""" imports_str = [] schemas_array_str = [] for name in sorted(schema_names): imports_str.append(f"import {name} from './schemas/{name}';") schemas_array_str.append(f" {name},") imports_code = '\n'.join(imports_str) schemas_code = '\n'.join(schemas_array_str) js_content = f"""// sanity.config.js import {{ defineConfig }} from 'sanity'; import {{ structureTool }} from 'sanity/structure'; import {{ visionTool }} from '@sanity/vision'; import {{ schemaTypes }} from './schemas'; {imports_code} export default defineConfig({{ name: 'default', title: 'My Sanity Project', projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, dataset: process.env.NEXT_PUBLIC_SANITY_DATASET, plugins: [ structureTool(), visionTool(), ], schema: {{ types: [ {schemas_code} ], }}, }}); """ return js_content # --- Example Usage --- # output_dir = './output' # schemas_dir = os.path.join(output_dir, 'schemas') # os.makedirs(schemas_dir, exist_ok=True) # # Assume inferred_schemas is populated from previous step # # inferred_schemas = { # # 'home': {'type': 'document', 'title': 'Home Page', 'fields': [...]}, # # 'heroBanner': {'type': 'object', 'title': 'Hero Banner', 'fields': [...]} # # } # generated_schema_names = [] # for schema_name, schema_def in inferred_schemas.items(): # js_code = generate_schema_js(schema_name, schema_def) # with open(os.path.join(schemas_dir, f"{schema_name}.js"), 'w') as f: # f.write(js_code) # generated_schema_names.append(schema_name) # # Generate sanity.config.js # config_code = generate_sanity_config(generated_schema_names) # with open(os.path.join(output_dir, 'sanity.config.js'), 'w') as f: # f.write(config_code)
4. UI Component Generator
For each Sanity object schema (and potentially document schema if it represents a reusable layout), we'll generate a corresponding React component.
Key Design Principles:
- Prop-driven: Components receive data via props, mirroring the Sanity schema fields.
- Layout Hints: Infer Flexbox/Grid properties from Figma's Auto Layout.
- Portable Text Rendering: Use
@sanity/block-content-to-reactor@portabletext/react.
React Component Generation Logic (Python Pseudo-code):
import os def generate_react_component(schema_name, schema_def): """Generates a React/Next.js component for a given Sanity schema.""" component_name = schema_name[0].upper() + schema_name[1:] # PascalCase props_destructuring = [] prop_types = [] # For JSDoc or PropTypes jsx_content_lines = [] # Infer basic layout for top-level object if it's a FRAME with Auto Layout layout_props = schema_def.get('layout_properties', {}) # This needs to be passed from Figma parsing # Basic CSS classes for layout outer_div_classes = [] if layout_props.get('layoutMode'): outer_div_classes.append('flex') if layout_props['layoutMode'] == 'VERTICAL': outer_div_classes.append('flex-col') elif layout_props['layoutMode'] == 'HORIZONTAL': outer_div_classes.append('flex-row') # Alignments if layout_props.get('primaryAxisAlignItems') == 'MIN': outer_div_classes.append('justify-start') elif layout_props.get('primaryAxisAlignItems') == 'CENTER': outer_div_classes.append('justify-center') elif layout_props.get('primaryAxisAlignItems') == 'MAX': outer_div_classes.append('justify-end') if layout_props.get('counterAxisAlignItems') == 'MIN': outer_div_classes.append('items-start') elif layout_props.get('counterAxisAlignItems') == 'CENTER': outer_div_classes.append('items-center') elif layout_props.get('counterAxisAlignItems') == 'MAX': outer_div_classes.append('items-end') # Padding (simplified for Tailwind example) padding_classes = [] # This requires mapping Figma's individual paddings to Tailwind's `p-X`, `px-X`, `py-X`, `pt-X` etc. # For simplicity, let's just add generic class or inline style if layout_props.get('padding'): # For now, we'll keep it simple: no padding classes auto-generated directly. # This is where a proper Tailwind config or CSS-in-JS mapping would go. pass # JSX for fields for field in schema_def['fields']: field_name = field['name'] field_type = field['type'] field_title = field['title'] # For comments or labels props_destructuring.append(field_name) # JSDoc type hints (can be converted to PropTypes or TypeScript later) if field_type == 'string': prop_types.append(f"* @param {{string}} {field_name} - {field_title}") jsx_content_lines.append(f" {{ {field_name} && <p className='text-lg'>{field_name}</p> }}") elif field_type == 'block': prop_types.append(f"* @param {{object[]}} {field_name} - {field_title} (Portable Text array)") jsx_content_lines.append(f" {{ {field_name} && <PortableText value={{ {field_name} }} components={{/* custom renderers here */}} /> }}") # Need to import PortableText renderer elif field_type == 'image': prop_types.append(f"* @param {{object}} {field_name} - {field_title} (Sanity image object)") # Assuming you have a component to render Sanity images jsx_content_lines.append(f" {{ {field_name} && <SanityImage image={{ {field_name} }} alt='{field_name}' className='w-full h-auto' /> }}") # Need to import SanityImage component helper elif field_type == 'boolean': prop_types.append(f"* @param {{boolean}} {field_name} - {field_title}") jsx_content_lines.append(f" <p className='text-sm'>Is {field_name}: {{ {field_name} ? 'Yes' : 'No' }}</p>") elif field_type == 'array' and field.get('of'): item_type = field['of'][0]['type'] # Assuming homogeneous array for simplicity item_component_name = item_type[0].upper() + item_type[1:] # PascalCase prop_types.append(f"* @param {{object[]}} {field_name} - List of {item_component_name}s") jsx_content_lines.append(f" <div className='flex flex-wrap gap-4'>") jsx_content_lines.append(f" {{ {field_name}?.map((item, index) => <{item_component_name} key={{item._key || index}} {{...item}} />) }}") jsx_content_lines.append(f" </div>") # Need to import the item component if it's a custom type elif field_type == 'object' and field.get('fields'): # Inline object # For inline objects, we'd render its fields directly or pass them as props to a sub-component. # For simplicity, we'll just log its presence. A real solution needs recursive rendering. prop_types.append(f"* @param {{object}} {field_name} - {field_title} (Inline Object)") jsx_content_lines.append(f" {{ {field_name} && <div className='p-2 border border-gray-300'><h4>{field_title} (Inline Object)</h4> {/* Render inline object fields */}</div> }}") imports_str = [] if any(f['type'] == 'block' for f in schema_def['fields']): imports_str.append("import { PortableText } from '@portabletext/react';") if any(f['type'] == 'image' for f in schema_def['fields']): imports_str.append("import SanityImage from './SanityImage'; // A wrapper for Next/Sanity image rendering") if any(f['type'] == 'array' for f in schema_def['fields']): # Dynamically add imports for array item components for field in schema_def['fields']: if field['type'] == 'array' and field.get('of') and field['of'][0]['type'] != 'block': item_type = field['of'][0]['type'] item_component_name = item_type[0].upper() + item_type[1:] imports_str.append(f"import {item_component_name} from './{item_component_name}';") imports_code = '\n'.join(sorted(list(set(imports_str)))) # Use set to avoid duplicates # Component template jsx_content = f"""// components/{component_name}.jsx {imports_code} /** {'\n'.join(prop_types)} */ const {component_name} = ({{ {', '.join(props_destructuring)} }}) => {{ return ( <div className='{" ".join(outer_div_classes)} p-4 border border-gray-200 rounded-lg'> <h2 className='text-2xl font-bold mb-2'>{component_name} Component</h2> { '\n'.join(jsx_content_lines)} </div> ); }}; export default {component_name}; """ return jsx_content # --- Example SanityImage.jsx (helper) --- def generate_sanity_image_helper(): return """// components/SanityImage.jsx import Image from 'next/image'; import { useNextSanityImage } from 'next-sanity-image'; import { client } from '../lib/sanity.client'; // Adjust path to your Sanity client const SanityImage = ({ image, alt, className }) => { const imageProps = useNextSanityImage(client, image); if (!imageProps) return null; return ( <Image {...imageProps} alt={alt || image.alt || 'Sanity Image'} className={className} sizes="(max-width: 800px) 100vw, 800px" /> ); }; export default SanityImage; """ # --- Example Usage --- # components_dir = os.path.join(output_dir, 'components') # os.makedirs(components_dir, exist_ok=True) # # For each object schema (and potentially document schemas that are reusable layouts) # for schema_name, schema_def in inferred_schemas.items(): # if schema_def['type'] == 'object': # Only generate components for objects initially # # Need to pass layout properties from the Figma parsing step to this function # # For this example, we'll just pass an empty dict for now, or assume it's pre-populated # schema_def['layout_properties'] = {} # Placeholder # js_code = generate_react_component(schema_name, schema_def) # with open(os.path.join(components_dir, f"{schema_name[0].upper() + schema_name[1:]}.jsx"), 'w') as f: # f.write(js_code) # # Generate helper image component # with open(os.path.join(components_dir, 'SanityImage.jsx'), 'w') as f: # f.write(generate_sanity_image_helper())Layout Inference Caveat: Translating Figma's exact
layoutMode,padding,itemSpacing, etc., into precise Tailwind CSS or custom CSS is complex and often requires a mapping layer. The example above provides basic Flexbox class inference. For grids, complex nesting, or absolute positioning, a more sophisticated CSS generation engine (or manual refinement) is usually needed.
5. Folder & Output Structure
The
generate.pyscript will create the following structure:. ├── generate.py # The main automation runner script └── output/ # Root output directory ├── schemas/ # Sanity schema definitions │ ├── page.js │ ├── heroBanner.js │ └── testimonialCard.js ├── components/ # React UI components │ ├── Page.jsx │ ├── HeroBanner.jsx │ ├── TestimonialCard.jsx │ └── SanityImage.jsx # Helper component for rendering Sanity images └── sanity.config.js # Sanity Studio configuration
6. Error Handling & Edge Cases
- Figma Layer Lacks Name:
- Fallback: Use a generic name like
unnamed_node_ID(where ID is Figma's node ID). - Recommendation: Flag these in the output or a log file, prompting designers to name their layers consistently.
- Fallback: Use a generic name like
- Unclear Mapping:
- Fallback: Default to
stringorobjecttypes for unknown elements. - Warning: Output warnings to the console/log, detailing which layers could not be clearly mapped.
- Fallback: Default to
- Missing Figma API Key/File: Graceful exit with an error message.
- Empty Figma File/Page: Handle empty
childrenarrays without crashing. - Manual Overrides (Crucial):
- Solution: Introduce a
figma_config.yamlfile. - Content:
type_overrides: Map specific Figma layer names/IDs to Sanity types (e.g.,id_123: 'block'orlayer_name: 'HeroCTA').component_mapping: Explicitly map Figma master components to Sanity object names and their corresponding React component names.layout_defaults: Default layout properties if not inferred.ignore_layers: List of Figma layer names/IDs to completely ignore.
- Implementation: The Python script reads this YAML file before inference and uses it to override or guide the classification logic.
- Solution: Introduce a
Example
figma_config.yaml:figma_file_key: "YOUR_FIGMA_FILE_KEY" figma_access_token: "YOUR_FIGMA_PERSONAL_ACCESS_TOKEN" # Explicitly map Figma names to Sanity types type_overrides: "Body Text Section": "block" "Price": "number" "Product Available Toggle": "boolean" # Explicitly map Figma components to Sanity object schemas and React components component_mapping: "Hero/Default": sanity_name: "heroBanner" react_name: "HeroBanner" type: "object" "Card/Product": sanity_name: "productCard" react_name: "ProductCard" type: "object" # Layers to ignore during schema generation (e.g., purely decorative elements, hidden layers) ignore_layers: - "Background Overlay" - "Grid Lines" - "Header Group/Placeholder"
7. Optional Enhancements
- Schema Hash to Track Sync State:
- Implementation: After generating a schema file, calculate its MD5 hash. Store this hash alongside the generated file (e.g.,
schema_name.js.hash) or embed it as a comment in the JS file. - Workflow: On subsequent runs, compare the newly generated schema's hash with the existing one. If they differ, it indicates a change, prompting regeneration and potentially a version bump or notification. This helps track if manual edits have occurred or if a Figma design change truly updated the schema.
- Implementation: After generating a schema file, calculate its MD5 hash. Store this hash alongside the generated file (e.g.,
- Auto-generate Preview Components for Sanity Studio:
- Implementation: For each generated Sanity object schema, add a
previewproperty. Thispreviewfunction typically returns aselectobject withtitle,subtitle,mediafields. - React Previews: For more complex previews, you can define a custom React component within the Sanity Studio that renders a miniature version of your actual frontend component, leveraging its props.
- Example (in
generate_schema_js):// Inside schema definition preview: { select: { title: 'title', // Assuming 'title' field exists subtitle: 'body', // Or a summary field media: 'image', // Assuming 'image' field exists }, prepare({ title, subtitle, media }) { return { title: title || 'Unnamed ' + '{schema_title}', subtitle: subtitle ? subtitle[0]?.children[0]?.text : 'No content', // Portable Text subtitle media: media, }; }, },
- Implementation: For each generated Sanity object schema, add a
- Integrate into CI/CD Pipeline:
- GitHub Actions:
- Trigger: On
pushto adesign-updatesbranch or a manualworkflow_dispatchevent. - Steps:
- Checkout repository.
- Install Python dependencies (
pip install -r requirements.txt). - Run
python generate.py(passing Figma API key/file key as environment variables). - Commit generated files (
git add .,git commit -m "feat: Auto-generated schemas and components from Figma"). - Push changes to a new branch or the main branch (requires careful permissions).
- (Optional) Trigger a Sanity deploy webhook.
- Trigger: On
- CLI Hook: Can be added as a
pre-commithook to ensure developers generate schemas before committing, though this ties schema generation to frontend dev workflow. - Webhook: A Figma webhook (if available for file changes) could trigger a serverless function that runs the generation.
- GitHub Actions:
Full Automation Runner Script (
generate.py)import os import json import re import requests import hashlib import yaml # --- Configuration --- CONFIG_FILE = 'figma_config.yaml' def load_config(): """Loads configuration from YAML file.""" if not os.path.exists(CONFIG_FILE): print(f"Error: {CONFIG_FILE} not found. Please create one with Figma credentials.") exit(1) with open(CONFIG_FILE, 'r') as f: return yaml.safe_load(f) config = load_config() FIGMA_API_BASE_URL = "https://api.figma.com/v1/files/" FIGMA_FILE_KEY = config.get('figma_file_key') FIGMA_ACCESS_TOKEN = config.get('figma_access_token') HEADERS = { "X-Figma-Token": FIGMA_ACCESS_TOKEN } OUTPUT_DIR = './output' SCHEMAS_DIR = os.path.join(OUTPUT_DIR, 'schemas') COMPONENTS_DIR = os.path.join(OUTPUT_DIR, 'components') TYPE_OVERRIDES = config.get('type_overrides', {}) COMPONENT_MAPPING = config.get('component_mapping', {}) IGNORE_LAYERS = config.get('ignore_layers', []) # --- Utility Functions --- def camel_case(s): s = re.sub(r'[^a-zA-Z0-9_]', '', s.strip()) if not s: return "" return s[0].lower() + re.sub(r'[^a-zA-Z0-9]', '', s[1:]).replace(" ", "").replace("-", "").replace("/", "").title() def pascal_case(s): s = camel_case(s) if not s: return "" return s[0].upper() + s[1:] def snake_case(s): s = re.sub(r'[^a-zA-Z0-9_]', '', s.strip()) s = re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower() return re.sub(r'[\s\W]+', '_', s) # --- 1. Figma Parsing Layer --- def fetch_figma_file(file_key): """Fetches the Figma file content.""" print(f"Fetching Figma file: {file_key}") url = f"{FIGMA_API_BASE_URL}{file_key}" try: response = requests.get(url, headers=HEADERS) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching Figma file: {e}") exit(1) def parse_figma_node(node, parent_type=None): """Recursively parses a Figma node and extracts relevant data.""" node_name = node.get('name', f"unnamed_node_{node.get('id', 'unknown')}") if node_name in IGNORE_LAYERS or node.get('id') in IGNORE_LAYERS: return None # Skip ignored layers parsed_data = { "id": node.get('id'), "name": node_name, "type": node.get('type'), "children": [], "properties": {} # To store inferred schema properties } # Apply type overrides from config if node_name in TYPE_OVERRIDES: parsed_data['inferred_sanity_type'] = TYPE_OVERRIDES[node_name] elif node.get('id') in TYPE_OVERRIDES: parsed_data['inferred_sanity_type'] = TYPE_OVERRIDES[node.get('id')] # Extract common properties and infer Sanity types if node.get('type') == 'TEXT': parsed_data['properties']['content'] = node.get('characters', '') if 'inferred_sanity_type' not in parsed_data: # If not overridden if '\n' in parsed_data['properties']['content'] or len(parsed_data['properties']['content']) > 150: parsed_data['inferred_sanity_type'] = 'block' else: parsed_data['inferred_sanity_type'] = 'string' elif node.get('type') == 'RECTANGLE': for fill in node.get('fills', []): if fill.get('type') == 'IMAGE' and fill.get('imageRef'): if 'inferred_sanity_type' not in parsed_data: parsed_data['inferred_sanity_type'] = 'image' break if 'inferred_sanity_type' not in parsed_data: parsed_data['inferred_sanity_type'] = 'string' # Default shapes to string or ignore print(f"Warning: RECTANGLE node '{node_name}' (ID: {node['id']}) not an image. Defaulting to 'string'.") elif node.get('type') == 'FRAME' or node.get('type') == 'GROUP': parsed_data['properties']['layoutMode'] = node.get('layoutMode') parsed_data['properties']['primaryAxisAlignItems'] = node.get('primaryAxisAlignItems') parsed_data['properties']['counterAxisAlignItems'] = node.get('counterAxisAlignItems') parsed_data['properties']['padding'] = { "top": node.get('paddingTop', 0), "right": node.get('paddingRight', 0), "bottom": node.get('paddingBottom', 0), "left": node.get('paddingLeft', 0), } parsed_data['properties']['itemSpacing'] = node.get('itemSpacing', 0) if 'inferred_sanity_type' not in parsed_data: parsed_data['inferred_sanity_type'] = 'object' # Default for frames/groups elif node.get('type') == 'COMPONENT' or node.get('type') == 'INSTANCE': if 'inferred_sanity_type' not in parsed_data: if re.search(r'(toggle|switch|checkbox)', node_name, re.IGNORECASE): parsed_data['inferred_sanity_type'] = 'boolean' else: parsed_data['inferred_sanity_type'] = 'object' if node.get('componentProperties'): parsed_data['properties']['componentProperties'] = node['componentProperties'] if node.get('componentId'): # For instances, link to master component parsed_data['properties']['masterComponentId'] = node['componentId'] else: # Fallback for unhandled Figma types if 'inferred_sanity_type' not in parsed_data: parsed_data['inferred_sanity_type'] = 'string' print(f"Warning: Unhandled Figma node type '{node.get('type')}' for '{node_name}' (ID: {node['id']}). Defaulting to 'string'.") # Recursively parse children if node.get('children'): for child in node['children']: child_parsed = parse_figma_node(child, node.get('type')) if child_parsed: # Only add if not ignored parsed_data['children'].append(child_parsed) return parsed_data # --- 2. Sanity Schema Classification Logic --- def infer_sanity_schemas(parsed_figma_tree, figma_components): schemas = {} # { schema_name: { type: 'document/object', fields: [], ... } } # Store layout properties inferred during parsing node_layout_properties = {} def get_master_component_name(instance_node_id): """Looks up the master component name for a given instance ID.""" if 'components' in figma_components: master_id = figma_components['components'].get(instance_node_id, {}).get('id') if master_id: # Find master component by ID for comp_id, comp_data in figma_components['components'].items(): if comp_id == master_id: return comp_data.get('name') return None # Pre-pass: Identify all Figma master components and map them to Sanity objects # This ensures we can correctly reference them later. master_component_schemas = {} # { figma_component_id: sanity_object_name } for comp_id, comp_data in figma_components.get('components', {}).items(): # Check explicit mapping in config first mapped_data = next((m for k, m in COMPONENT_MAPPING.items() if k == comp_data.get('name') or k == comp_id), None) if mapped_data and mapped_data.get('type') == 'object': sanity_obj_name = mapped_data['sanity_name'] master_component_schemas[comp_id] = sanity_obj_name if sanity_obj_name not in schemas: schemas[sanity_obj_name] = { 'type': 'object', 'name': sanity_obj_name, 'title': mapped_data.get('title', comp_data.get('name')), 'fields': [] } print(f"Identified master component from config: {comp_data.get('name')} -> {sanity_obj_name}") # Recursively populate fields for this master component (find it in the parsed tree) # This requires a traversal of the parsed tree specifically for master component definitions # For simplicity, we assume master component definitions are "reachable" in the main tree # This part is a simplification. A real implementation would parse figma_data['components'] directly. # Here, we'll populate the fields later when we encounter an instance. else: # Heuristic for other master components comp_name_camel = camel_case(comp_data.get('name', '')) if comp_name_camel and comp_name_camel not in schemas: sanity_obj_name = comp_name_camel master_component_schemas[comp_id] = sanity_obj_name schemas[sanity_obj_name] = { 'type': 'object', 'name': sanity_obj_name, 'title': comp_data.get('name'), 'fields': [] } print(f"Identified master component: {comp_data.get('name')} -> {sanity_obj_name}") def populate_schema_fields(schema_name, node): current_schema = schemas[schema_name] node_layout_properties[node['id']] = node['properties'] # Store layout for component generation for child_node in node['children']: field_name_raw = child_node.get('name', 'unnamed_field') field_name = camel_case(field_name_raw) field_title = field_name_raw field_definition = { 'name': field_name, 'title': field_title, } # Figma instance referencing a master component if child_node.get('type') == 'INSTANCE' and child_node['properties'].get('masterComponentId'): master_id = child_node['properties']['masterComponentId'] referenced_schema_name = master_component_schemas.get(master_id) if referenced_schema_name and schemas.get(referenced_schema_name, {}).get('type') == 'object': field_definition['type'] = 'reference' field_definition['to'] = [{ 'type': referenced_schema_name }] # Ensure the referenced schema's fields are populated if it's new if not schemas[referenced_schema_name]['fields']: # Check if fields are empty # Find the master component's node in the parsed tree to populate its fields master_comp_node = find_node_by_id(parsed_figma_tree, master_id) if master_comp_node: populate_schema_fields(referenced_schema_name, master_comp_node) else: print(f"Warning: Master component node {master_id} not found for {referenced_schema_name}. Fields might be empty.") else: print(f"Warning: Could not resolve master component {master_id} for '{field_name_raw}'. Treating as inline object.") field_definition['type'] = 'object' field_definition['fields'] = [] populate_schema_fields_inline(field_definition['fields'], child_node) elif child_node.get('inferred_sanity_type') == 'string': field_definition['type'] = 'string' elif child_node.get('inferred_sanity_type') == 'block': field_definition['type'] = 'array' # Sanity Portable Text is an array of blocks field_definition['of'] = [{ 'type': 'block' }] elif child_node.get('inferred_sanity_type') == 'image': field_definition['type'] = 'image' field_definition['options'] = { 'hotspot': True } elif child_node.get('inferred_sanity_type') == 'boolean': field_definition['type'] = 'boolean' # Array inference: If a FRAME/GROUP has auto-layout AND multiple children of the SAME type/name elif child_node.get('type') in ['FRAME', 'GROUP'] and child_node['properties'].get('layoutMode') in ['VERTICAL', 'HORIZONTAL']: if len(child_node['children']) > 1 and len(set(c.get('name') for c in child_node['children'] if c.get('name'))) == 1: # Item name is the name of the first child, stripped of common suffixes item_name_singular = camel_case(child_node['children'][0]['name'].replace('Card', '').replace('Item', '').strip()) if not item_name_singular: item_name_singular = camel_case(child_node['name'] + 'Item') # Fallback # Check if this inferred item type is a known object item_obj_schema_name = item_name_singular if item_obj_schema_name not in schemas: schemas[item_obj_schema_name] = { 'type': 'object', 'name': item_obj_schema_name, 'title': child_node['children'][0]['name'], 'fields': [] } populate_schema_fields(item_obj_schema_name, child_node['children'][0]) # Recursively populate item fields field_definition['type'] = 'array' field_definition['of'] = [{ 'type': item_obj_schema_name }] else: # It's a regular frame/group, treat as inline object field_definition['type'] = 'object' field_definition['fields'] = [] populate_schema_fields_inline(field_definition['fields'], child_node) elif child_node.get('inferred_sanity_type') == 'object': # Generic object, could be inline or reference field_definition['type'] = 'object' # Default to inline object field_definition['fields'] = [] populate_schema_fields_inline(field_definition['fields'], child_node) else: field_definition['type'] = 'string' # Final fallback print(f"Warning: Could not infer specific Sanity type for '{field_name_raw}' (ID: {child_node['id']}). Defaulting to 'string'.") current_schema['fields'].append(field_definition) def populate_schema_fields_inline(fields_list, node): """Helper to populate fields for inline objects recursively.""" node_layout_properties[node['id']] = node['properties'] # Store layout for component generation for child_node in node['children']: field_name_raw = child_node.get('name', 'unnamed_field') field_name = camel_case(field_name_raw) field_title = field_name_raw field_definition = { 'name': field_name, 'title': field_title } if child_node.get('inferred_sanity_type') == 'string': field_definition['type'] = 'string' elif child_node.get('inferred_sanity_type') == 'block': field_definition['type'] = 'array'; field_definition['of'] = [{ 'type': 'block' }] elif child_node.get('inferred_sanity_type') == 'image': field_definition['type'] = 'image' elif child_node.get('inferred_sanity_type') == 'boolean': field_definition['type'] = 'boolean' elif child_node.get('inferred_sanity_type') == 'object' or child_node.get('type') in ['FRAME', 'GROUP', 'COMPONENT', 'INSTANCE']: field_definition['type'] = 'object' field_definition['fields'] = [] populate_schema_fields_inline(field_definition['fields'], child_node) # Recursive call else: field_definition['type'] = 'string' # Fallback fields_list.append(field_definition) def find_node_by_id(node, target_id): """Traverses the parsed Figma tree to find a node by its ID.""" if node['id'] == target_id: return node for child in node['children']: found = find_node_by_id(child, target_id) if found: return found return None # Step 1: Identify all top-level frames on CANVAS as documents for page_node in parsed_figma_tree['children']: if page_node['type'] == 'CANVAS': for frame_node in page_node['children']: if frame_node['type'] == 'FRAME': doc_name = camel_case(frame_node['name'].replace(' Page', '').replace(' Details', '')) if doc_name and doc_name not in schemas: schemas[doc_name] = { 'type': 'document', 'name': doc_name, 'title': frame_node['name'], 'fields': [] } # Add common document fields first schemas[doc_name]['fields'].append({ 'name': 'title', 'title': 'Title', 'type': 'string' }) schemas[doc_name]['fields'].append({ 'name': 'slug', 'title': 'Slug', 'type': 'slug', 'options': { 'source': 'title' } }) # Populate body content for documents doc_body_items = [] for child in frame_node['children']: # Check if child is a recognized master component instance if child.get('type') == 'INSTANCE' and child['properties'].get('masterComponentId'): master_id = child['properties']['masterComponentId'] referenced_schema_name = master_component_schemas.get(master_id) if referenced_schema_name: doc_body_items.append({ 'type': 'reference', 'to': [{ 'type': referenced_schema_name }] }) # Ensure the referenced schema is populated if it was just a placeholder if not schemas[referenced_schema_name]['fields']: master_comp_node = find_node_by_id(parsed_figma_tree, master_id) # This needs to be found in components list if master_comp_node: # Simplified, assumes master is in parsed tree populate_schema_fields(referenced_schema_name, master_comp_node) else: print(f"Warning: Master component node {master_id} for {referenced_schema_name} not found in parsed tree.") else: print(f"Warning: Instance '{child.get('name')}' ({child['id']}) refers to unknown master component {master_id}. Not added to body.") elif child.get('inferred_sanity_type') == 'block': doc_body_items.append({ 'type': 'block' }) else: print(f"Info: Ignoring non-block/non-component child '{child.get('name')}' in document body.") if doc_body_items: schemas[doc_name]['fields'].append({ 'name': 'body', 'title': 'Page Content', 'type': 'array', 'of': doc_body_items }) # Store layout properties for document components (if we decide to generate them) node_layout_properties[frame_node['id']] = frame_node['properties'] print(f"Identified document: {doc_name}") # Step 2: Populate fields for all identified object schemas (master components) for schema_name, schema_def in list(schemas.items()): # Use list to avoid RuntimeError during dict modification if schema_def['type'] == 'object' and not schema_def['fields']: # If it's a new object schema without fields # Find the corresponding Figma node (master component definition) in the parsed tree # This is complex. A robust solution uses figma_data['components'] as the source. # For simplicity, we find the first instance in the parsed tree to extract fields. # This means fields are derived from the *first instance* we see of that master component. master_comp_id = next((k for k, v in master_component_schemas.items() if v == schema_name), None) if master_comp_id: # Find an instance of this master component in the parsed tree to derive fields instance_node = find_node_by_id(parsed_figma_tree, master_comp_id) # This should be improved to find master component definition itself if instance_node: populate_schema_fields(schema_name, instance_node) else: print(f"Warning: Master component node {master_comp_id} for {schema_name} not found in parsed tree to derive fields.") else: print(f"Warning: Object schema '{schema_name}' has no fields and no master component ID found to derive them.") return schemas, node_layout_properties # --- 3. Schema Code Generation Layer --- def generate_schema_js(schema_name, schema_def): """Generates a Sanity schema JavaScript file.""" schema_type = schema_def['type'] schema_title = schema_def['title'] # Sanity schema definition string fields_str = [] for field in schema_def['fields']: field_name = field['name'] field_title = field['title'] field_type = field['type'] field_options = "" if field_type == 'image' and field.get('options', {}).get('hotspot'): field_options = ", options: { hotspot: true }" elif field_type == 'slug' and field.get('options', {}).get('source'): field_options = f", options: {{ source: '{field['options']['source']}' }}" field_line = f" {{\n name: '{field_name}',\n title: '{field_title}',\n type: '{field_type}'{field_options}" if field_type == 'array' and field.get('of'): of_types = [] for item_type in field['of']: if item_type['type'] == 'block': of_types.append(" { type: 'block' }") elif item_type['type'] == 'reference': to_types = ', '.join([f"{{ type: '{t['type']}' }}" for t in item_type['to']]) of_types.append(f" {{ type: 'reference', to: [{to_types}] }}") else: # It's a specific object type of_types.append(f" {{ type: '{item_type['type']}' }}") field_line += f",\n of: [\n{ ',\n'.join(of_types)}\n ]" elif field_type == 'object' and field.get('fields'): # Inline object nested_fields_str = generate_nested_fields(field['fields']) field_line += f",\n fields: [\n{nested_fields_str}\n ]" field_line += "\n }" fields_str.append(field_line) all_fields_str = ',\n'.join(fields_str) # Add preview for documents and objects preview_block = "" if schema_type == 'document' or schema_type == 'object': title_field = next((f['name'] for f in schema_def['fields'] if f['name'] == 'title' and f['type'] == 'string'), None) subtitle_field = next((f['name'] for f in schema_def['fields'] if f['type'] == 'block' or f['type'] == 'string'), None) image_field = next((f['name'] for f in schema_def['fields'] if f['type'] == 'image'), None) select_parts = [] if title_field: select_parts.append(f"title: '{title_field}'") if subtitle_field: select_parts.append(f"subtitle: '{subtitle_field}'") if image_field: select_parts.append(f"media: '{image_field}'") if select_parts: preview_block = f""", preview: {{ select: {{ {', '.join(select_parts)} }}, prepare({{ title, subtitle, media }}) {{ return {{ title: title || 'Unnamed {schema_title}', subtitle: subtitle ? (Array.isArray(subtitle) ? subtitle.map(block => block.children?.map(child => child.text)).join('') : subtitle) : '', media: media, }}; }} }}""" js_content = f"""// schemas/{schema_name}.js import {{ defineType }} from 'sanity'; export default defineType({{ name: '{schema_name}', title: '{schema_title}', type: '{schema_type}', fields: [ {all_fields_str} ]{preview_block} }}); """ return js_content def generate_nested_fields(fields, indent_level=3): """Helper to generate fields for nested objects recursively.""" indent = ' ' * indent_level nested_fields_str = [] for field in fields: field_name = field['name'] field_title = field['title'] field_type = field['type'] field_line = f"{indent}{{\n{indent} name: '{field_name}',\n{indent} title: '{field_title}',\n{indent} type: '{field_type}'" if field_type == 'array' and field.get('of'): of_types = [] for item_type in field['of']: if item_type['type'] == 'block': of_types.append(f"{indent} {{ type: 'block' }}") elif item_type['type'] == 'reference': to_types = ', '.join([f"{{ type: '{t['type']}' }}" for t in item_type['to']]) of_types.append(f"{indent} {{ type: 'reference', to: [{to_types}] }}") else: of_types.append(f"{indent} {{ type: '{item_type['type']}' }}") field_line += f",\n{indent} of: [\n{ ',\n'.join(of_types)}\n{indent} ]" elif field_type == 'object' and field.get('fields'): nested_fields_str_inner = generate_nested_fields(field['fields'], indent_level + 1) field_line += f",\n{indent} fields: [\n{nested_fields_str_inner}\n{indent} ]" field_line += f"\n{indent}}}" nested_fields_str.append(field_line) return ',\n'.join(nested_fields_str) # --- Sanity.config.js Generation --- def generate_sanity_config(schema_names): """Generates sanity.config.js with schema imports.""" imports_str = [] schemas_array_str = [] for name in sorted(schema_names): imports_str.append(f"import {name} from './schemas/{name}';") schemas_array_str.append(f" {name},") imports_code = '\n'.join(imports_str) schemas_code = '\n'.join(schemas_array_str) js_content = f"""// sanity.config.js import {{ defineConfig }} from 'sanity'; import {{ structureTool }} from 'sanity/structure'; import {{ visionTool }} from '@sanity/vision'; {imports_code} export default defineConfig({{ name: 'default', title: 'My Sanity Project', projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, dataset: process.env.NEXT_PUBLIC_SANITY_DATASET, plugins: [ structureTool(), visionTool(), ], schema: {{ types: [ {schemas_code} ], }}, }}); """ return js_content # --- 4. UI Component Generator --- def generate_react_component(schema_name, schema_def, node_layout_properties): """Generates a React/Next.js component for a given Sanity schema.""" component_name = pascal_case(schema_name) props_destructuring = [] prop_types = [] jsx_content_lines = [] node_id_for_layout = next((node_id for node_id, props in node_layout_properties.items() if pascal_case(node_id) == component_name), None) layout_props = node_layout_properties.get(node_id_for_layout, {}) # Get layout for the node that defines this schema outer_div_classes = ["p-4", "border", "border-gray-200", "rounded-lg", "shadow"] if layout_props.get('layoutMode'): outer_div_classes.append('flex') if layout_props['layoutMode'] == 'VERTICAL': outer_div_classes.append('flex-col') elif layout_props['layoutMode'] == 'HORIZONTAL': outer_div_classes.append('flex-row') outer_div_classes.append('flex-wrap') # Allow wrapping for horizontal items # Alignments if layout_props.get('primaryAxisAlignItems') == 'MIN': outer_div_classes.append('justify-start') elif layout_props.get('primaryAxisAlignItems') == 'CENTER': outer_div_classes.append('justify-center') elif layout_props.get('primaryAxisAlignItems') == 'MAX': outer_div_classes.append('justify-end') if layout_props.get('counterAxisAlignItems') == 'MIN': outer_div_classes.append('items-start') elif layout_props.get('counterAxisAlignItems') == 'CENTER': outer_div_classes.append('items-center') elif layout_props.get('counterAxisAlignItems') == 'MAX': outer_div_classes.append('items-end') if layout_props.get('itemSpacing', 0) > 0: outer_div_classes.append(f'gap-{int(layout_props["itemSpacing"] / 4)}') # Tailwind rem default is 0.25rem = 4px imports_str = [] for field in schema_def['fields']: field_name = field['name'] field_type = field['type'] field_title = field['title'] props_destructuring.append(field_name) prop_types.append(f"* @param {{{'object[]' if field_type == 'array' or field_type == 'block' else field_type}}} {field_name} - {field_title}") if field_type == 'string': jsx_content_lines.append(f" {{ {field_name} && <p className='text-lg'>{{ {field_name} }}</p> }}") elif field_type == 'array' and field.get('of') and field['of'][0]['type'] == 'block': imports_str.append("import { PortableText } from '@portabletext/react';") jsx_content_lines.append(f" {{ {field_name} && <PortableText value={{ {field_name} }} /> }}") # Add custom renderers as needed elif field_type == 'image': imports_str.append("import SanityImage from './SanityImage';") jsx_content_lines.append(f" {{ {field_name} && <SanityImage image={{ {field_name} }} alt='{field_name}' className='w-full h-auto object-cover' /> }}") elif field_type == 'boolean': jsx_content_lines.append(f" <p className='text-sm font-semibold'>Is {field_title}: {{ {field_name} ? 'Yes' : 'No' }}</p>") elif field_type == 'array' and field.get('of') and field['of'][0]['type'] != 'block': item_type = field['of'][0]['type'] item_component_name = pascal_case(item_type) imports_str.append(f"import {item_component_name} from './{item_component_name}';") jsx_content_lines.append(f" <div className='flex flex-wrap gap-4'>") jsx_content_lines.append(f" {{ {field_name}?.map((item, index) => <{item_component_name} key={{item._key || index}} {{...item}} />) }}") jsx_content_lines.append(f" </div>") elif field_type == 'object': # For inline objects, render their fields or a placeholder jsx_content_lines.append(f" {{ {field_name} && <div className='p-2 border border-gray-300 rounded-md mt-2'>") jsx_content_lines.append(f" <h5 className='font-bold text-sm'>{{'{field_title}'}} (Inline Object)</h5>") # Recursively render nested fields for inline objects - this would require a helper function # For simplicity, we just show a placeholder jsx_content_lines.append(f" {/* Render fields of nested object here, e.g., <p>{{JSON.stringify({field_name})}}</p> */}") jsx_content_lines.append(f" </div> }}") elif field_type == 'reference': # For references, we assume the component takes a full object ref_to = field['to'][0]['type'] # Assuming single reference type ref_component_name = pascal_case(ref_to) imports_str.append(f"import {ref_component_name} from './{ref_component_name}';") jsx_content_lines.append(f" {{ {field_name} && <{ref_component_name} {{...{field_name}}} /> }}") # Pass the whole object as props imports_code = '\n'.join(sorted(list(set(imports_str)))) jsx_content = f"""// components/{component_name}.jsx {imports_code} /** * @typedef {{ { '*\n'.join(prop_types)} * }} {component_name}Props */ /** * Auto-generated React component for Sanity schema: {schema_name} * @param {{ {component_name}Props }} props */ const {component_name} = ({{ {', '.join(props_destructuring)} }}) => {{ return ( <section className='{" ".join(outer_div_classes)}'> <h2 className='text-xl font-semibold mb-2'>{{'{component_name}'}}</h2> {/* Render fields based on schema */} { '\n'.join(jsx_content_lines)} </section> ); }}; export default {component_name}; """ return jsx_content def generate_sanity_image_helper(): return """// components/SanityImage.jsx import Image from 'next/image'; import { useNextSanityImage } from 'next-sanity-image'; import { client } from '../lib/sanity.client'; // Adjust this path to your Sanity client setup /** * @typedef {{ * image: object, * alt?: string, * className?: string * }} SanityImageProps */ /** * Renders a Sanity image using next/image and next-sanity-image. * @param {SanityImageProps} props */ const SanityImage = ({ image, alt, className }) => { // You'll need to configure your Sanity client in '../lib/sanity.client.js' // For example: // import { createClient } from 'next-sanity'; // export const client = createClient({ // projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, // dataset: process.env.NEXT_PUBLIC_SANITY_DATASET, // useCdn: true, // apiVersion: '2023-05-03', // }); if (!client) { console.error("Sanity client not configured. Please check '../lib/sanity.client.js'"); return null; } const imageProps = useNextSanityImage(client, image); if (!imageProps) return null; return ( <Image {...imageProps} alt={alt || image.alt || 'Sanity Image'} className={className} sizes="(max-width: 800px) 100vw, 800px" /> ); }; export default SanityImage; """ # --- Main Automation Runner --- def run_automation(): print("Starting Figma to Sanity/React Automation...") # 1. Fetch and Parse Figma File figma_data = fetch_figma_file(FIGMA_FILE_KEY) if not figma_data: return parsed_figma_tree = parse_figma_node(figma_data['document']) if not parsed_figma_tree: print("Error: Could not parse Figma document.") return # 2. Infer Sanity Schemas inferred_schemas, node_layout_properties = infer_sanity_schemas(parsed_figma_tree, figma_data) print("\nInferred Sanity Schemas:") for name, schema in inferred_schemas.items(): print(f" - {name} ({schema['type']}) with {len(schema['fields'])} fields") # print(json.dumps(inferred_schemas, indent=2)) # Uncomment to debug schemas # Ensure output directories exist os.makedirs(SCHEMAS_DIR, exist_ok=True) os.makedirs(COMPONENTS_DIR, exist_ok=True) # 3. Generate Sanity Schema Files generated_schema_names = [] print("\nGenerating Sanity Schema files...") for schema_name, schema_def in inferred_schemas.items(): js_code = generate_schema_js(schema_name, schema_def) schema_file_path = os.path.join(SCHEMAS_DIR, f"{schema_name}.js") # Schema hash check current_hash = hashlib.md5(js_code.encode('utf-8')).hexdigest() hash_file_path = schema_file_path + '.hash' should_write = True if os.path.exists(hash_file_path): with open(hash_file_path, 'r') as f: old_hash = f.read().strip() if old_hash == current_hash: print(f" - Schema '{schema_name}.js' unchanged. Skipping write.") should_write = False else: print(f" - Schema '{schema_name}.js' changed. Updating...") if should_write: with open(schema_file_path, 'w') as f: f.write(js_code) with open(hash_file_path, 'w') as f: f.write(current_hash) print(f" - Generated {schema_name}.js") generated_schema_names.append(schema_name) # Generate sanity.config.js config_code = generate_sanity_config(generated_schema_names) config_file_path = os.path.join(OUTPUT_DIR, 'sanity.config.js') with open(config_file_path, 'w') as f: f.write(config_code) print(f"Generated {os.path.basename(config_file_path)}") # 4. Generate React UI Components print("\nGenerating React UI Components...") for schema_name, schema_def in inferred_schemas.items(): if schema_def['type'] == 'object' or schema_def['type'] == 'document': # Generate components for both jsx_code = generate_react_component(schema_name, schema_def, node_layout_properties) component_file_path = os.path.join(COMPONENTS_DIR, f"{pascal_case(schema_name)}.jsx") # Component hash check (similar to schema) current_hash = hashlib.md5(jsx_code.encode('utf-8')).hexdigest() hash_file_path = component_file_path + '.hash' should_write = True if os.path.exists(hash_file_path): with open(hash_file_path, 'r') as f: old_hash = f.read().strip() if old_hash == current_hash: # print(f" - Component '{pascal_case(schema_name)}.jsx' unchanged. Skipping write.") should_write = False else: print(f" - Component '{pascal_case(schema_name)}.jsx' changed. Updating...") if should_write: with open(component_file_path, 'w') as f: f.write(jsx_code) with open(hash_file_path, 'w') as f: f.write(current_hash) print(f" - Generated {pascal_case(schema_name)}.jsx") # Generate helper SanityImage component sanity_image_helper_path = os.path.join(COMPONENTS_DIR, 'SanityImage.jsx') with open(sanity_image_helper_path, 'w') as f: f.write(generate_sanity_image_helper()) print(f" - Generated {os.path.basename(sanity_image_helper_path)}") print("\nAutomation complete! Check the 'output' directory.") if __name__ == "__main__": run_automation()
To Run This Automation:
- Save the Python script: Save the entire Python code block above as
generate.py. - Create
figma_config.yaml: In the same directory asgenerate.py, create this file:figma_file_key: "YOUR_FIGMA_FILE_KEY" # Replace with your Figma file's key from its URL figma_access_token: "YOUR_PERSONAL_ACCESS_TOKEN" # Get from Figma Developer Settings # Optional overrides and mappings: # type_overrides: # "My Figma Text Box": "block" # component_mapping: # "MyComponent/VariantA": # sanity_name: "myVariantAComponent" # react_name: "MyVariantAComponent" # type: "object" # ignore_layers: # - "Helper Lines" - Install dependencies:
pip install requests PyYAML - Run the script:
python generate.py
This pipeline provides a solid foundation for automating the design-to-code workflow between Figma and Sanity.io, focusing on structured data and reusable components. Further enhancements would involve more sophisticated AI-driven layout analysis, precise style mapping (e.g., Tailwind CSS class generation), and potentially a visual verification step.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.