Skip to main content

04 - Prototyping: from Figma to code in 5 steps

From design to code with a token file, a converter that rejects broken references and a check that flags drift, fixed colours and contrast.

What do you think about this article?

04 - Prototyping: from Figma to code in 5 steps
Human-Computer Interactionfedericocalo.dev

At a Glance

From design to code with a token file, a converter that rejects broken references and a check that flags drift, fixed colours and contrast.

This article is part of the Human-Computer Interaction series. See the series index.

Where the gap between design and code comes from

Design and code drift apart when the values the designer picks (the colour of a button, the space between two fields, the weight of a heading) are copied by hand from one side to the other. Every copy is a chance to be off by one digit, and nobody notices until someone puts the two screens side by side. The cure is not a tool that "translates Figma into code": it is a file of values that both sides read, plus an automatic check that fails when the code moves away from that file.

The five steps of this article follow that idea: first you fix the values (tokens), then you draw the structure (wireframe), then you compose the mockup with components that use those values, then you try the prototype with a few people, and finally you hand over the code with a check that keeps it aligned. Only step 5 is demonstrated here with a program. Everything about Figma rests on the official documentation read on 2026-11-13: I did not use any Figma account, API or plugin, so no screen or behaviour of the tool was executed.

Step 1: tokens, in a format machines can read

A design token is a value with a name: color.action.primary instead of #0b5cad. The advantage is that the name tells the intent ("the colour of the main action") and the value can change without anyone having to hunt down every place where it appears. The interchange format between tools has a public specification, the one from the Design Tokens Community Group: JSON files where every token has a $value and a $type, and where a token can be an alias of another one with the syntax {color.base.blue-600}.

The status of the document is declared in the specification itself: it is not a W3C standard and it is not on the standards track, it is a report of a community group (the version I read is the final one of 2025-10-28).

Inside Figma the equivalent is variables: the official guide presents them as reusable values that you apply to design properties, suited to representing tokens and to switching context with "modes" (for example light and dark theme).

The guide states that publishing variables in a team library requires a Professional plan or higher, and the documentation of the REST API for variables requires a full seat in an Enterprise organisation. For a small team this means that automatic export from Figma to the token file may not be available: in that case the JSON file is updated with a third-party tool or by hand, and that is exactly why the check of step 5 is needed.

The file below is the token set of this article's test project, written in the format of the specification. There are two levels: the "base" colours, which name a value (blue-600), and the "action" colours, which name a use and point to the base with an alias. Dimensions use the { "value", "unit" } object prescribed by the specification, which admits only px and rem. The hex field next to the components is optional and only serves human reading: the converter of step 5 compares it with the components and stops if they do not match.

{
  "color": {
    "$type": "color",
    "base": {
      "white": { "$value": { "colorSpace": "srgb", "components": [1, 1, 1], "hex": "#ffffff" } },
      "blue-600": { "$value": { "colorSpace": "srgb", "components": [0.0431, 0.3608, 0.6784], "hex": "#0b5cad" } },
      "blue-800": { "$value": { "colorSpace": "srgb", "components": [0.0314, 0.2902, 0.549], "hex": "#084a8c" } },
      "grey-300": { "$value": { "colorSpace": "srgb", "components": [0.7686, 0.7882, 0.8157], "hex": "#c4c9d0" } },
      "grey-600": { "$value": { "colorSpace": "srgb", "components": [0.3569, 0.3922, 0.4392], "hex": "#5b6470" } }
    },
    "action": {
      "primary": { "$value": "{color.base.blue-600}" },
      "primary-hover": { "$value": "{color.base.blue-800}" },
      "on-primary": { "$value": "{color.base.white}" },
      "focus-ring": { "$value": "{color.base.blue-800}" },
      "disabled-bg": { "$value": "{color.base.grey-300}" },
      "disabled-text": { "$value": "{color.base.grey-600}" }
    },
    "surface": {
      "page": { "$value": "{color.base.white}" }
    }
  },
  "space": {
    "$type": "dimension",
    "sm": { "$value": { "value": 8, "unit": "px" } },
    "md": { "$value": { "value": 16, "unit": "px" } },
    "lg": { "$value": { "value": 24, "unit": "px" } }
  },
  "radius": {
    "md": { "$value": { "value": 8, "unit": "px" }, "$type": "dimension" }
  },
  "font": {
    "body": { "$value": ["Inter", "Helvetica Neue", "sans-serif"], "$type": "fontFamily" },
    "weight-strong": { "$value": 600, "$type": "fontWeight" }
  }
}

The reason for the two levels is maintenance. If tomorrow action.primary has to point to another blue, you change one line and all the components that use the semantic token follow; if instead the components used blue-600 directly, every change of intent would require finding them one by one. The price is one more level of indirection to read. That is why the file above stops at two levels: a third one, per component, makes sense only when a design system really needs it, as you can see in article 03 of the series on design systems.

Step 2: the wireframe decides the order, not the look

The wireframe is a discussion about where things go: how many elements fit on a screen, where the main action goes, in what order the user walks through the flow. It is done in grey, with placeholder text, precisely because colour distracts: a team that argues for an hour about the shade of a blue is avoiding the hard question, namely whether the "Create account" button should come before or after the password field. Pen and paper are enough, or the grey frames of any tool.

A good use of the wireframe is to compare it with the principles the series has already covered. Does the flow always show the system status? Can the user undo? Do the labels speak their language? These are the questions of Nielsen's heuristics, covered in article 01, and they cost very little while the design is still a grid of grey rectangles.

Step 3: the mockup, with components and their states

The high-fidelity mockup is built only with components from the library. If you need a component that is not there, you first add it to the library, with the right tokens, and only then use it on the screen: drawing it "on the fly" inside a screen produces two slightly different blue buttons in the same product, and the code will have to choose which of the two is the real one. This discipline is boring and worth exactly the time it costs.

For every interactive component the designer draws the states, because they are the only way to tell the developer what must exist in the code. For a button there are at least five: at rest, with the pointer over it (hover), pressed (active), with keyboard focus, disabled. One state that is easy to omit is keyboard focus: whoever navigates with Tab must see where they are, and success criterion 2.4.7 of WCAG 2.2 (level AA) requires a visible focus indicator; the topic is the one of article 02 on accessibility. If the mockup does not show the focus state, in the code it is usually missing.

Step 4: you try the prototype before writing code

An interactive prototype is a set of screens linked to each other, real enough to have a person click on it. It serves to discover flow errors, for example a "Cancel" placed where the user expects "Log in", when fixing them costs a tweak to the design and not a rewrite of the code. For this phase a light test is enough: a few people, one simple task ("sign up with your email"), and you watching in silence.

How many people? For a qualitative test like this, Jakob Nielsen argues that five are enough, and gives as the reason that every additional person largely repeats what the previous ones have already seen; the same page clarifies that quantitative measures need at least twenty participants. The figure is not a law: article 05 of the series recalculates it with a program, shows what it depends on and why in a study with sixty users some groups of five found only 55% of the problems. Here it is enough to remember that the prototype is not a full usability test, it is a filter against the grossest errors.

Step 5: the handover to code, with a check that fails

This is the step where the design system breaks, and where it is better to stop relying on goodwill. The test project has four files: the token file shown above, a converter that turns it into CSS variables, a small HTML/CSS prototype that uses only those variables, and a check that says whether the code is still faithful to the design. The goal is not a complete generator: it is to show how small the deterministic part is and how much the check that protects it is worth. Everything was run with Node 24.11 on 2026-11-13.

The converter reads the JSON, flattens the groups inheriting the $type from the group that declares it, resolves aliases by following them to an explicit value and stops with an error if a reference is circular or points to a token that does not exist. Then it writes one CSS variable per token: for an alias it writes var(--...) towards its target, so the two-level structure remains in the CSS, for the others it writes the value.

It handles only the four types the file uses (opaque sRGB colour, dimension, font family, weight): a type it does not know is rejected instead of guessed. It is a toy of about sixty lines, and should be read as such.

import { readFileSync, writeFileSync } from 'node:fs';

const ALIAS = /^\{([^}]+)\}$/;

function flatten(node, path = [], inherited) {
  const type = node.$type ?? inherited;
  if ('$value' in node) return [{ path, type, value: node.$value }];
  return Object.entries(node)
    .filter(([key]) => !key.startsWith('$'))
    .flatMap(([key, child]) => flatten(child, [...path, key], type));
}

function resolve(byPath, token, seen = []) {
  const alias = typeof token.value === 'string' && token.value.match(ALIAS);
  if (!alias) return token;
  const name = alias[1];
  if (seen.includes(name)) throw new Error(`circular reference: ${[...seen, name].join(' -> ')}`);
  const target = byPath.get(name);
  if (!target) throw new Error(`${token.path.join('.')}: the reference {${name}} does not exist`);
  return resolve(byPath, target, [...seen, name]);
}

function toHex({ colorSpace, components, alpha = 1, hex }) {
  if (colorSpace !== 'srgb' || alpha !== 1) throw new Error('only opaque sRGB is handled');
  const out = '#' + components.map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('');
  if (hex && hex.toLowerCase() !== out) throw new Error(`hex ${hex} does not match the components (${out})`);
  return out;
}

function toCss(type, value) {
  switch (type) {
    case 'color': return toHex(value);
    case 'dimension': return `${value.value}${value.unit}`;
    case 'fontFamily': return [].concat(value).map((n) => (/\s/.test(n) ? `"${n}"` : n)).join(', ');
    case 'fontWeight': return String(value);
    default: throw new Error(`unhandled type: ${type}`);
  }
}

export function loadTokens(tree) {
  const tokens = flatten(tree);
  const byPath = new Map(tokens.map((t) => [t.path.join('.'), t]));
  return tokens.map((token) => {
    const end = resolve(byPath, token);
    const type = end.type ?? token.type;
    const name = '--' + token.path.join('-');
    const alias = typeof token.value === 'string' && token.value.match(ALIAS);
    const css = alias ? `var(--${alias[1].replaceAll('.', '-')})` : toCss(type, token.value);
    return { name, type, css, resolved: toCss(type, end.value) };
  });
}

export function buildCss(tree) {
  const lines = loadTokens(tree).map((t) => `  ${t.name}: ${t.css};`);
  return `/* Generated by build-tokens.mjs from tokens.json. Do not edit by hand. */\n:root {\n${lines.join('\n')}\n}\n`;
}

if (import.meta.main) {
  const [, , input, output] = process.argv;
  writeFileSync(output, buildCss(JSON.parse(readFileSync(input, 'utf8'))));
  console.log(`written ${output}`);
}

Two lines matter more than the others. In resolve the seen list is what stops two aliases pointing at each other from making the program loop forever; in toHex the comparison with the hex field catches the case where someone has touched the components but not the human-readable label (or vice versa). I tried them: with two tokens that refer to each other the error is "circular reference: b -> a -> b", with an alias to a name that does not exist it is "a: the reference {zz} does not exist", with a hex wrong by one digit it is "hex #fffffe does not match the components (#ffffff)". Called with node build-tokens.mjs tokens.json tokens.css, it produces the file below, identical in two consecutive runs.

/* Generated by build-tokens.mjs from tokens.json. Do not edit by hand. */
:root {
  --color-base-white: #ffffff;
  --color-base-blue-600: #0b5cad;
  --color-base-blue-800: #084a8c;
  --color-base-grey-300: #c4c9d0;
  --color-base-grey-600: #5b6470;
  --color-action-primary: var(--color-base-blue-600);
  --color-action-primary-hover: var(--color-base-blue-800);
  --color-action-on-primary: var(--color-base-white);
  --color-action-focus-ring: var(--color-base-blue-800);
  --color-action-disabled-bg: var(--color-base-grey-300);
  --color-action-disabled-text: var(--color-base-grey-600);
  --color-surface-page: var(--color-base-white);
  --space-sm: 8px;
  --space-md: 16px;
  --space-lg: 24px;
  --radius-md: 8px;
  --font-body: Inter, "Helvetica Neue", sans-serif;
  --font-weight-strong: 600;
}

The generated file is the only place where literal values appear. The two header lines tell whoever opens it not to edit it: if someone touches it by hand, the check that follows notices. Semantic variables such as --color-action-primary do not contain a colour but a reference to --color-base-blue-600: by changing one base line the change propagates to all uses, and var() also accepts a fallback value as a second argument, as the MDN page I consulted describes.

The prototype uses only variables. In the buttons' stylesheet there is no colour code and no spacing number: if the designer changes a token, the prototype changes without anyone touching this file. The states are those of step 3.

A real trap lies in the order of the rules: with .btn-primary:hover and .btn-primary:disabled having the same specificity, the last one in the file wins, and a disabled button would turn dark blue when the mouse passes over it. That is why hover and active are written as :hover:not(:disabled), so the order does not matter. I did not open the file in a browser: the visual rendering is declared unverified, and what the check measures is the text of the CSS and the values of the tokens.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Prototype: sign-up</title>
  <link rel="stylesheet" href="tokens.css">
  <link rel="stylesheet" href="prototype.css">
</head>
<body>
  <main class="card">
    <h1>Create your account</h1>
    <label for="email">Email</label>
    <input id="email" class="field" type="email">
    <button class="btn btn-primary" type="submit">Create account</button>
    <button class="btn btn-primary" type="button" disabled>Submitting</button>
  </main>
</body>
</html>
body { background: var(--color-surface-page); font-family: var(--font-body); }
.card { display: grid; gap: var(--space-md); max-width: 24rem; padding: var(--space-lg); }
.field { padding: var(--space-sm); border-radius: var(--radius-md); }

.btn {
  padding: var(--space-md) var(--space-lg);
  border: 0;
  border-radius: var(--radius-md);
  font-family: var(--font-body);
  font-weight: var(--font-weight-strong);
  cursor: pointer;
}
.btn-primary {
  background: var(--color-action-primary);
  color: var(--color-action-on-primary);
}
.btn-primary:hover:not(:disabled) { background: var(--color-action-primary-hover); }
.btn-primary:active:not(:disabled) { background: var(--color-action-primary-hover); }
.btn-primary:focus-visible {
  outline: 3px solid var(--color-action-focus-ring);
  outline-offset: 2px;
}
.btn-primary:disabled {
  background: var(--color-action-disabled-bg);
  color: var(--color-action-disabled-text);
  cursor: not-allowed;
}

The check is the shield against drift. It makes four verifications: it regenerates the CSS from the tokens in memory and compares it with the published file (if they differ, someone changed the design or the code without the other); it searches the prototype for any hand-written colour, that is #rrggbb, rgb( or hsl(; it verifies that the states drawn exist in the CSS; and it computes the contrast between pairs of tokens with the WCAG 2.2 formulas, that is the relative luminance and the ratio (L1 + 0.05) / (L2 + 0.05).

The threshold for text is 4.5:1 (criterion 1.4.3, level AA) and for interface elements such as the focus ring it is 3:1 (criterion 1.4.11); disabled components are exempt from the standard, and indeed they are not measured here.

import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { buildCss, loadTokens } from './build-tokens.mjs';

const dir = process.argv[2] ?? '.';
const read = (name) => readFileSync(join(dir, name), 'utf8');
const problems = [];

// 1. Is the published CSS what the tokens produce today?
const tree = JSON.parse(read('tokens.json'));
if (buildCss(tree) !== read('tokens.css')) {
  problems.push('DRIFT: tokens.css does not match tokens.json, regenerate with build-tokens.mjs');
}

// 2. No hand-written colour outside tokens.css.
const literal = /#[0-9a-fA-F]{3,8}\b|\brgba?\(|\bhsla?\(/g;
for (const file of ['prototype.css', 'prototype.html']) {
  for (const m of read(file).matchAll(literal)) problems.push(`HARDCODED COLOUR in ${file}: ${m[0]}`);
}

// 3. WCAG 2.2 contrast: relative luminance and ratio, as defined by the W3C.
const tokens = Object.fromEntries(loadTokens(tree).map((t) => [t.name, t.resolved]));
const luminance = (hex) => {
  const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
    .map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
const ratio = (a, b) => {
  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (hi + 0.05) / (lo + 0.05);
};
const pairs = [
  ['text on the button', '--color-action-on-primary', '--color-action-primary', 4.5],
  ['text on the button on hover', '--color-action-on-primary', '--color-action-primary-hover', 4.5],
  ['focus ring on the page', '--color-action-focus-ring', '--color-surface-page', 3],
];
for (const [label, fg, bg, min] of pairs) {
  const r = ratio(tokens[fg], tokens[bg]);
  console.log(`${label.padEnd(30)} ${r.toFixed(2)}:1 (minimum ${min}:1)`);
  if (r < min) problems.push(`CONTRAST: ${label} ${r.toFixed(2)}:1 below ${min}:1`);
}

// 4. Do the states the designer drew exist in the CSS?
const css = read('prototype.css');
for (const state of [':hover', ':active', ':focus-visible', ':disabled']) {
  if (!css.includes(`.btn-primary${state}`)) problems.push(`MISSING STATE: .btn-primary${state}`);
}

console.log(problems.length ? problems.join('\n') : 'no problems');
process.exit(problems.length ? 1 : 0);

To see it at work I simulated four moments in the life of a project with a script that copies the files into a temporary folder: A is the starting point, B is the designer changing the main blue to #58a6ff in the token file without anyone regenerating the CSS, C is the regenerated CSS, D is a developer writing a colour by hand and losing the rule for the disabled state. The ratios are computed by check.mjs; a second calculation, written separately in Python with the same formulas, gave the same values (6.67, 8.87 and 2.53) and 21.0 for black on white, which is the maximum foreseen by the WCAG definition.

#!/usr/bin/env bash
set -u
workdir=$(mktemp -d)
cp tokens.json tokens.css prototype.css prototype.html build-tokens.mjs check.mjs "$workdir"/
cd "$workdir"

echo "== A. starting point"
node check.mjs . ; echo "exit=$?"

echo "== B. the designer changes blue-600 to #58a6ff, nobody regenerates"
sed -i 's|"blue-600": .*|"blue-600": { "$value": { "colorSpace": "srgb", "components": [0.3451, 0.651, 1], "hex": "#58a6ff" } },|' tokens.json
node check.mjs . ; echo "exit=$?"

echo "== C. regenerate: the CSS follows the design"
node build-tokens.mjs tokens.json tokens.css
node check.mjs . ; echo "exit=$?"

echo "== D. a developer writes a colour by hand and removes the disabled state"
sed -i 's|^\.btn-primary:disabled|.btn-primary:xdisabled|; s|cursor: pointer;|cursor: pointer; color: #58a6ff;|' prototype.css
node check.mjs . ; echo "exit=$?"

# Output:
# == A. starting point
# text on the button             6.67:1 (minimum 4.5:1)
# text on the button on hover    8.87:1 (minimum 4.5:1)
# focus ring on the page         8.87:1 (minimum 3:1)
# no problems
# exit=0
# == B. the designer changes blue-600 to #58a6ff, nobody regenerates
# text on the button             2.53:1 (minimum 4.5:1)
# text on the button on hover    8.87:1 (minimum 4.5:1)
# focus ring on the page         8.87:1 (minimum 3:1)
# DRIFT: tokens.css does not match tokens.json, regenerate with build-tokens.mjs
# CONTRAST: text on the button 2.53:1 below 4.5:1
# exit=1
# == C. regenerate: the CSS follows the design
# written tokens.css
# text on the button             2.53:1 (minimum 4.5:1)
# text on the button on hover    8.87:1 (minimum 4.5:1)
# focus ring on the page         8.87:1 (minimum 3:1)
# CONTRAST: text on the button 2.53:1 below 4.5:1
# exit=1
# == D. a developer writes a colour by hand and removes the disabled state
# text on the button             2.53:1 (minimum 4.5:1)
# text on the button on hover    8.87:1 (minimum 4.5:1)
# focus ring on the page         8.87:1 (minimum 3:1)
# HARDCODED COLOUR in prototype.css: #58a6ff
# CONTRAST: text on the button 2.53:1 below 4.5:1
# MISSING STATE: .btn-primary:disabled
# exit=1

The most instructive result is B. The blue chosen, #58a6ff, is a pleasant colour, but with white text it gives a contrast of 2.53:1 against the 4.5:1 required: by eye it looks suitable, and only the number says it is not: the check stops it before the button reaches the screen.

Note also that B reports two different problems together: drift (the CSS was not regenerated) and contrast (the new value is inaccessible). Regenerating in step C removes the first and leaves the second, which is a design problem and not a code one, and must therefore be sent back to the designer with a number in hand.

What to automate and what not

The deterministic part of the handover, the one the test project automates, is small: names, colours, spacing, typography. Everything else requires decisions that the design does not contain: what the component is called in your framework, what local state it manages, what events it emits, how it composes with the others. Figma's Dev Mode, according to its official guide, shows the properties and generated code of an element, lets you mark frames as ready for development and link designs to tickets, documentation and code components; with Code Connect a team can replace the automatically generated code with the real code of its own components. The same guide indicates that Dev Mode is available on the Professional, Education, Organization, Government and Enterprise plans.

I did not try design-to-code generators, so I say neither good nor bad about them. I only say how to evaluate them: look at whether the code they produce uses your tokens and your components, or literal values and an invented structure. In the second case you have created a second place where design and code can diverge, and the check of step 5 would already have told you it is not right. The criterion is not "automatic or manual": it is whether there is still a single file of truth and a check that protects it.

Pitfalls

  • Unsynchronised tokens. The designer changes a value and the developer works with the old one. Remedy: the token file lives in the repository, every change goes through a visible modification and the check runs at every handover.
  • Throwaway components. Every screen redraws its own buttons. Remedy: the library is the only source; a missing component is added there before being used.
  • Missing states. The mockup shows only the button at rest. Remedy: states are drawn together with the component, and the check verifies that they exist in the CSS.
  • A prototype never shown to anyone. The flow seems obvious to whoever designed it. Remedy: five people and one task, in silence, before the code.

The four items have a common origin: a value or a decision lives in two places and nobody is in charge of keeping them aligned. The check of step 5 covers the first three; the fourth is solved only by people, and it is the one that no program replaces. If you have to choose where to start, start from the tokens, because they are the first thing that breaks and the cheapest to protect.

Exercises

  1. Copy the files of the test into a folder of your own, add a color.action.danger token (alias of a new red base colour) and a .btn-danger state with the same rules. Extend the list of pairs in check.mjs and find a red that passes 4.5:1 with white text.
  2. Deliberately break the token file in three ways (a circular alias, a reference to a name that does not exist, a wrong hex) and check that the converter gives a clear error in each case.
  3. Take a project of yours with hand-written colours, extract the values that appear more than once into a token file and replace them with variables. Then run on your project the same regular expression that check.mjs uses for hardcoded colours and count how many remain.

The third exercise is the most realistic and also the longest: in existing projects the work is not writing the converter, it is deciding the names. If after an hour you have found more than ten different colours for what is "the same" blue, you have just measured how much drift there already is in your code, and that is a result as useful as the code you will write to fix it.

What you can do now

You can describe the values of a design in a token file in the format of the Design Tokens Community Group specification, turn them into CSS variables with a converter that rejects broken references, and protect the result with a check that reports drift, hand-written colours, missing states and contrasts below the WCAG thresholds. You also know what was not demonstrated here: the behaviour of Figma and of code generators, and the visual rendering of the prototype in a browser. In article 05, the last of the series you will find how to try the prototype with real people and how to read the results without being fooled by the numbers.

Sources

Every output of the listings was obtained with Node 24.11.0 on 2026-11-13, twice with the same result. The contrast ratios were recalculated with a second program in Python. Not executed: everything concerning Figma, design-to-code generators and the display of the prototype in a browser. Colours, names and components are invented for the test.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects