We are designing a doc-to-design synchronization layer. This layer should connect:
- Documentation (specs, acceptance criteria)
- Design (components, states)
- Possibly code (but the problem says "doc-to-design", so maybe we focus on design side)
However, note that the user mentioned "component states", which suggests we are dealing with design systems and interactive components.
Let's break down:
- Specs: These are the written requirements, features, user stories, etc.
- Acceptance Criteria: The conditions that must be met for the spec to be accepted.
- Component States: The different states a UI component can be in (e.g., default, hover, active, disabled, error, etc.)
We need a synchronization layer that ensures that the documentation (specs and acceptance criteria) are in sync with the design (component states).
How might this work?
Idea:
- We have a design system with components defined (in a tool like Figma, or a code-based design system).
- Each component has a set of states.
- The specs and acceptance criteria should reference these components and states.
For example, a spec might say: "The button component must have a disabled state that is 50% opacity and non-interactive."
The acceptance criteria might be:
- Given a button in the disabled state, when the user hovers, then the button should not change appearance.
- The disabled button must have opacity 0.5.
We want to ensure that the design of the button in the disabled state matches the spec and that the acceptance criteria are testable.
Synchronization layer could be:
- A central repository (like a design system documentation site) that links to the component definitions (in design tool or code) and the specs/acceptance criteria.
How to achieve this?
Option 1: Manual linking with a tool that tracks changes and notifies when there's a mismatch.
Option 2: Automated, where the component states are defined in a machine-readable format (like JSON) and the specs are also structured (like in a testing framework). Then we can have a validation tool that checks:
a) For every state mentioned in the specs, the component has that state defined.
b) For every state in the component, the specs cover it (or at least note that it's not required?).
But acceptance criteria are more about behavior, which might not be directly in the design. So maybe we need two parts:
- Static design (visual states) -> can be checked by comparing design specifications (like style properties) with the specs.
- Dynamic behavior (interaction) -> might require testing against a prototype or code.
However, the problem says "doc-to-design", so maybe we are only concerned with the design side (static states) and the documentation of those states.
Let's reframe:
We have:
- Design: A set of components, each with a set of states and visual properties for each state.
- Documentation (specs): Describes the required states and their visual properties.
We want to keep them in sync.
Proposed solution:
Step 1: Define a schema for component states.
Example:
Component: Button
States: default, hover, active, disabled, focus
For each state, we have a set of design tokens (or style properties):
- background-color
- color
- opacity
- border, etc.
Step 2: Store the design system's component states in a machine-readable format (like JSON).
button.json:
{
"component": "Button",
"states": {
"default": {
"background-color": "#007bff",
"color": "#ffffff"
},
"disabled": {
"background-color": "#007bff",
"opacity": "0.5"
}
}
}
Step 3: Write the specs in a structured way that references these states and properties.
We could have a spec file (like YAML) that says:
spec_button.yaml:
component: Button
acceptance_criteria:
- The button must have a disabled state with opacity 0.5.
- The disabled state must not change on hover.
But note: the second one is about behavior, not visual. So we might need to split:
We could have:
visual_specs:
- state: disabled
properties:
opacity: 0.5
behavioral_specs:
- state: disabled
behavior:
hover: no-change
Step 4: Build a synchronization tool that:
a) Parses the design system's component state definitions (JSON).
b) Parses the spec files (YAML/JSON).
c) Compares:
For every state in the spec's visual_specs, check that the component has that state and that the properties match (with some tolerance?).
For every state in the component, check that it is covered in the spec (unless it's an internal state that doesn't need to be documented?).
d) For behavioral specs, we might need a different approach because behavior is not in the static design. Maybe we link to interaction prototypes or we have a separate behavior definition in the design tool (like Figma prototypes). But that's more complex.
Given the complexity of behavior, maybe we focus only on visual states for the synchronization.
Alternatively, we can have two layers:
Layer 1: Visual state synchronization (as above)
Layer 2: Behavioral synchronization (by linking acceptance criteria to prototype interactions or test cases)
But the problem says "doc-to-design", so maybe the design includes interaction design? In tools like Figma, you can define interactions (on hover, on click, etc.). So if we can export those interactions in a structured way, we could compare.
However, that might be too ambitious.
Let's stick to visual states for now.
Implementation:
We'll create a command-line tool (or a CI step) that:
- Takes a path to the design system's component state definitions (directory of JSON files).
- Takes a path to the specs (directory of YAML/JSON files).
- For each spec file, it looks for the component name and then the visual specs for each state.
- It loads the corresponding component state definition and compares.
How to handle multiple components? We can have:
design-system/
components/
button.json
input.json
specs/
button_spec.yaml
input_spec.yaml
The spec file should specify which component it is for.
Comparison rules:
- If a state is in the spec but not in the design, error.
- If a state is in the design but not in the spec, warning (maybe it's an internal state? or missing spec?).
- For each property in the spec state, check that it exists in the design state and the value matches (exact match? or we can allow ranges?).
We might need to consider that the design might have additional properties not in the spec (that's okay).
Example:
Spec: disabled state must have opacity 0.5.
Design: disabled state has opacity 0.5 and background-color #007bff.
-> Match, because the required property (opacity) is present and correct.
But what if the spec says:
disabled state must have opacity 0.5 and background-color #007bff.
and the design has:
disabled state has opacity 0.5.
-> Missing background-color, error.
So we require that all properties in the spec are present in the design with the same value.
Step 5: Output a report.
- List of components that are in sync.
- List of mismatches (with file and line numbers?).
Step 6: We might also want to generate documentation from the design system? Or keep the spec as the source of truth? This is a sync, so we want to detect drift.
But note: the spec might be the source of truth for the requirements, and the design system should implement it.
So if the design system is behind, we flag that the design is missing something.
Alternatively, we might have the design system as the source of truth for the visual design, and the spec should document it. Then if the spec is missing a state that exists in design, we flag that the spec is incomplete.
We need to decide the direction.
Since it's "doc-to-design", maybe the documentation (spec) is the source of truth for what should be built, and the design system should match it.
But in practice, design systems are often built first and then documented. So maybe we want bidirectional sync?
Let's assume:
- The design system (component states) is the source of truth for the visual implementation.
- The specs are the source of truth for the requirements.
We want them to match. So we check:
For every state in the spec, the design must have it with the same properties.
For every state in the design, it must be documented in the spec (so that the requirements are complete).
So if the design has a state that the spec doesn't mention, that's a problem because the spec is incomplete.
If the spec has a state that the design doesn't have, that's a problem because the design is incomplete.
We can have two modes:
- Strict: both must match exactly (same states and same properties for those states).
- Lenient: design can have extra states and properties, but must have at least the ones in the spec. And spec must have at least the states that are in the design? Or maybe we don't require that? Actually, if the design has a state that is not in the spec, then that state is not documented as a requirement, so it might be an implementation detail that shouldn't be exposed? Or maybe it's an internal state (like a loading state that is not part of the public API). So we might want to allow the design to have extra states that are not in the spec, but we should at least warn.
Given the complexity, let's start with:
We require that every state and property in the spec is present in the design.
We also require that every state in the design is present in the spec (so that we don't have undocumented states).
But note: the design might have multiple variations (like different sizes) and the spec might not mention size? Then we are comparing the base component? We need to define the scope.
Alternatively, we can have:
The design system defines a base component (with all states) and then variations (like sizes) are separate? Or we can have a component with multiple dimensions (state and size). Then the spec might only cover the default size? This is getting too complex.
Let's simplify:
We assume that the component in the design system is the one we are comparing, and the spec is for that component (without considering variations). If there are variations, then we might need to have multiple spec files? Or the spec covers the base and the variations are separate components?
Given the time, let's assume one component, one set of states.
Implementation steps:
-
Read all design component JSON files.
-
Read all spec files (YAML/JSON).
-
For each spec file:
- Extract the component name.
- Find the corresponding design component JSON.
- If not found, error.
- For each state in spec.visual_specs:
- Check if state exists in design component.
- For each property in the spec state, check if it exists in the design state and the value matches.
- Then, for each state in the design component:
- Check if it is in the spec.visual_specs. If not, error.
-
Print report.
Example:
design/button.json:
{
"component": "Button",
"states": {
"default": { "background-color": "#007bff", "color": "#ffffff" },
"disabled": { "background-color": "#007bff", "opacity": "0.5" }
}
}
specs/button.yaml:
component: Button
visual_specs:
- state: default
properties:
background-color: "#007bff"
color: "#ffffff"
- state: disabled
properties:
opacity: "0.5"
This would fail because the spec's disabled state does not specify background-color, but the design has it? Wait, the spec only requires opacity? Actually, the spec says for disabled state, we require opacity 0.5. The design has that and also background-color. That's okay because the spec doesn't say we cannot have background-color.
But note: the design's disabled state has background-color, but the spec doesn't require it. That's acceptable because the design can have more properties.
However, when we check the design states against the spec, we see that the design's disabled state is in the spec (state name matches) but the design has an extra property (background-color). That's okay.
But wait: the spec's disabled state only has one property. We are only checking that the design has at least those properties? Or that the design has exactly the same properties?
The requirement: the spec must be satisfied. So if the spec says "opacity must be 0.5", then as long as the design has opacity 0.5, it's okay. But if the design has opacity 0.5 and also background-color, that's fine.
However, if the spec says "disabled state must have opacity 0.5 and background-color #007bff", then the design must have both.
So we are checking that for every state in the spec, the design state must have at least the properties listed in the spec (with the same values). The design can have more.
But then, when we check that every design state is in the spec, we are only checking the state name. So if the design has a state "foo" that is not in the spec, that's an error because the spec doesn't document it.
So:
For each state in spec:
design_state = design_component.states[state_name]
if not design_state: error
for each property in spec_state.properties:
if property not in design_state: error
if design_state[property] != spec_state.properties[property]: error
Then, for each state in design_component.states:
if state not in spec.visual_specs (by state name): error
This means that the spec must list every state that the design has, even if the spec doesn't specify any properties for that state? That might be too strict. Maybe we want to allow the spec to omit states that are not required? But then the design has an undocumented state.
Alternatively, we can have:
The spec must document every state that is part of the public API. If the design has a state that is internal (like a loading state that is triggered by the component itself and not by the user), then maybe we don't want to document it? But then how do we know which states are public?
We could have a flag in the design system: public: true/false for each state? Or in the spec, we only list the states that are required by the product.
Given the ambiguity, let's assume that every state in the design must be documented in the spec. If there are internal states, they should not be in the design component's state list? Or we need a way to mark them.
Alternatively, we can change the second check to only require that every state in the design that is marked as public (if we have such a flag) is in the spec.
But we don't have that in our JSON example.
Let's extend the design JSON:
{
"component": "Button",
"states": {
"default": {
"public": true,
"background-color": "#007bff",
"color": "#ffffff"
},
"disabled": {
"public": true,
"background-color": "#007bff",
"opacity": "0.5"
},
"loading": {
"public": false,
...
}
}
}
Then we only check the states with public: true against the spec.
But the spec might not have a concept of public/private. So maybe we assume all states in the design are public, unless we have a flag.
Given the complexity, let's stick to:
We require that every state in the design (without considering public/private) is in the spec.
And if the design has a state that shouldn't be public, then the spec must document it? That doesn't make sense.
Alternatively, we can have:
The spec defines the required states (the ones that the product requires). The design may have additional states that are not required by the product (like internal states). Then we don't want to force the spec to document internal states.
So we change:
For every state in the spec, the design must have it (and with the required properties).
But we don't require that every state in the design is in the spec.
Then the tool would only check that the design meets the spec, but not the other way around.
However, the problem says "synchronization", which implies two-way.
Let's think about the use case:
The design system team might add a new state (like "loading") to the button, but the product team hasn't asked for it and doesn't want to document it. Then the design system has an extra state that is not in the spec. Is that a problem? It might be, because the product team doesn't know about it and might not test it. But if it's an internal state that the product team doesn't need to know about, then maybe it's okay.
So we need a way to distinguish.
Given the time, I propose:
We have two types of states in the design:
- Public states: must be documented in the spec.
- Internal states: may exist in the design but are not required to be in the spec.
How to mark? We can have a field in the design state: `"internal": true` or `"public": false`.
Then:
For every state in spec, the design must have a public state with that name and the required properties.
For every public state in the design, it must be in the spec.
Internal states in the design are ignored for the spec check.
This seems reasonable.
So we adjust:
In the design JSON, each state can have an optional `internal` (default false) or `public` (default true) flag.
Then:
Let design_public_states = all states in design where state.internal is not true (or state.public is true).
Then:
For each state in spec.visual_specs:
if state.name not in design_public_states: error
else:
design_state = design_public_states[state.name]
for each property in spec_state.properties:
if property not in design_state: error
if design_state[property] != spec_state.properties[property]: error
For each state_name in design_public_states:
if state_name not in [s.name for s in spec.visual_specs]: error
This way, we only care about public states.
But note: the spec might have a state that is not in the design (even as public) -> error.
And the design might have a public state that is not in the spec -> error.
Internal states are not checked.
Step 7: Behavioral specs.
We might not be able to check behavioral specs without a prototype or code. So we leave that for future extension.
Alternatively, we can have a separate tool that links acceptance criteria to interaction design (like Figma prototypes) but that's a different problem.
Given the scope, we'll focus on visual states.
Let's write a plan:
-
Define the schema for design component states (JSON) with an optional internal flag for each state.
-
Define the schema for the spec (YAML) with:
component: string
visual_specs:
- state: string
properties: dict of property: value
-
Write a script (in Python, Node, etc.) that:
-
Walks through the design directory and loads all JSON files into a dict: design_components[component_name] = { states: { state_name: { properties, internal? } } }
-
Walks through the spec directory and loads all YAML files (or JSON) into: spec_components[component_name] = { visual_specs: [ { state, properties } ] }
-
For each component in spec_components:
if component not in design_components: error and skip.
design_component = design_components[component]
design_public_states = {}
for state_name, state_data in design_component.states.items():
if not state_data.get('internal', False):
design_public_states[state_name] = state_data
For each visual_spec in spec_component.visual_specs:
state_name = visual_spec.state
if state_name not in design_public_states:
print(f"Error: State '{state_name}' in spec for component '{component}' not found in design (or is internal).")
else:
design_state = design_public_states[state_name]
for prop, value in visual_spec.properties.items():
if prop not in design_state:
print(f"Error: Property '{prop}' for state '{state_name}' in component '{component}' not found in design.")
else:
if design_state[prop] != value:
print(f"Error: Property '{prop}' for state '{state_name}' in component '{component}' has value '{design_state[prop]}' but spec requires '{value}'.")
For each state_name in design_public_states:
if state_name not in [vs.state for vs in spec_component.visual_specs]:
print(f"Error: Public state '{state_name}' in design for component '{component}' is not documented in spec.")
-
Print summary.
-
Run this in CI to catch drifts.
-
Optionally, we can generate a markdown report.
-
We might also want to generate the spec from the design? That's the opposite direction. But the problem says "doc-to-design", so we are checking that design matches the doc.
However, if the design is the source of truth for the visual, then we might want to generate the spec from the design? That would be design-to-doc.
We are building a synchronization layer, which could be bidirectional. But the user said "doc-to-design", so maybe we are only checking one way.
Let's clarify: the user says "connecting specs, acceptance criteria, and component states". So we are connecting three things. But the design is the component states, and the specs and acceptance criteria are the documentation.
So we are ensuring that the documentation (specs and acceptance criteria) are in sync with the design (component states). But the acceptance criteria might be behavioral and not state-based.
We might need to extend:
The spec file might have:
component: Button
visual_specs: [ ... ]
behavioral_specs: [ ... ]
But without a way to represent behavior in the design, we can't check behavioral_specs.
So maybe we leave behavioral_specs for future, or we assume they are in a separate system (like test cases) and we only check the visual part.
Alternatively, we can have a mapping:
behavioral_specs might reference states and actions. For example:
- Given a button in the disabled state, when clicked, then nothing happens.
We could check in the design if the disabled state has an interaction that does nothing? But that's not typically in the design system.
Given the complexity, I propose we only handle visual_specs for now.
The acceptance criteria that are about visual appearance can be in visual_specs, and the ones about behavior are out of scope.
But the user said "acceptance criteria", so we must consider them.
Another idea: acceptance criteria might be in a separate file (like in Gherkin) and we might have step definitions that reference component states. We could parse the Gherkin and check that every state mentioned in the steps exists in the design.
Example Gherkin:
Scenario: Disabled button
Given I see a button in the disabled state
When I click the button
Then nothing happens
We can extract "disabled state" and check that the button has a disabled state.
But then we also need to check that the step definitions are correct? That's too much.
So maybe we only check the states mentioned in the acceptance criteria (if we can parse them) against the design.
This is getting too broad.
Let's stick to the initial plan: we have a spec file that includes both visual and behavioral, but we only check the visual part.
And for the behavioral part, we might have a separate tool that checks against a prototype or code.
Given the time, I'll design the visual part and leave the behavioral as a TODO.
Final design:
We have:
design-system/
components/
button.json
...
specs/
button.yaml
...
The spec YAML:
component: Button
visual_specs:
- state: default
properties:
background-color: "#007bff"
color: "#ffffff"
- state: disabled
properties:
opacity: "0.5"
behavioral_specs:
- given: "button in disabled state"
when: "user clicks"
then: "no action"
We only process visual_specs.
The design JSON:
{
"component": "Button",
"states": {
"default": {
"public": true,
"background-color": "#007bff",
"color": "#ffffff"
},
"disabled": {
"public": true,
"opacity": "0.5"
},
"loading": {
"public": false,
"background-color": "#f0f0f0"
}
}
}
Then the tool will:
- Check that the spec's visual_specs for each state and property are in the design's public states.
- Check that every public state in the design is in the spec's visual_specs.
The behavioral_specs are ignored.
We can extend the tool to also check that every state mentioned in behavioral_specs (if we can parse the given/when/then) is in the design's public states? But that's a natural language processing problem.
Alternatively, we can require that the behavioral_specs reference states by name and then we can check those state names.
Example:
behavioral_specs:
- given: "button in {state: disabled} state"
But that's not standard.
Given the complexity, let's leave behavioral_specs out of the first version.
We can note that the tool currently only checks visual_specs.
We can also note that the tool assumes the spec and design are in the expected format.
We'll write the tool in Python because it's good for scripting and parsing YAML/JSON.
Steps:
pip install pyyaml
script:
import os
import json
import yaml
def load_design_components(design_dir):
components = {}
for filename in os.listdir(design_dir):
if filename.endswith('.json'):
with open(os.path.join(design_dir, filename)) as f:
data = json.load(f)
component_name = data.get('component')
if component_name:
components[component_name] = data
return components
def load_specs(specs_dir):
specs = {}
for filename in os.listdir(specs_dir):
if filename.endswith(('.yaml', '.yml')):
with open(os.path.join(specs_dir, filename)) as f:
data = yaml.safe_load(f)
component_name = data.get('component')
if component_name:
specs[component_name] = data
return specs
def main(design_dir, specs_dir):
design_components = load_design_components(design_dir)
spec_components = load_specs(specs_dir)
errors = []
for component_name, spec_data in spec_components.items():
if component_name not in design_components:
errors.append(f"Component '{component_name}' in spec not found in design.")
continue
design_data = design_components[component_name]
# Get public states from design
design_public_states = {}
for state_name, state_data in design_data.get('states', {}).items():
if not state_data.get('internal', False):
design_public_states[state_name] = state_data
# Check each visual spec
for visual_spec in spec_data.get('visual_specs', []):
state_name = visual_spec['state']
if state_name not in design_public_states:
errors.append(f"Spec for component '{component_name}' requires state '{state_name}' which is not a public state in design.")
else:
design_state = design_public_states[state_name]
for prop, value in visual_spec.get('properties', {}).items():
if prop not in design_state:
errors.append(f"Spec for component '{component_name}', state '{state_name}' requires property '{prop}' which is not in design state.")
else:
if design_state[prop] != value:
errors.append(f"Spec for component '{component_name}', state '{state_name}' property '{prop}' has value '{design_state[prop]}' but spec requires '{value}'.")
# Check that every public state in design is in spec
for state_name in design_public_states:
found = any(vs['state'] == state_name for vs in spec_data.get('visual_specs', []))
if not found:
errors.append(f"Public state '{state_name}' in design for component '{component_name}' is not documented in spec.")
if errors:
print("Errors found:")
for error in errors:
print(f" - {error}")
return 1
else:
print("All components are in sync.")
return 0
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print("Usage: sync_tool.py <design_dir> <specs_dir>")
sys.exit(1)
design_dir = sys.argv[1]
specs_dir = sys.argv[2]
sys.exit(main(design_dir, specs_dir))
This is a basic version.
Improvements:
- Allow for tolerance in value comparison (e.g., color might be in different formats?).
- More detailed error messages with file names.
- Support for JSON specs as well.
- Option to ignore certain states or properties.
But this is a starting point.
We can also consider generating a report in HTML or markdown.
And we can run this as a pre-commit hook or in CI.
Now, what about acceptance criteria? We haven't used them.
We could extend the spec format to include acceptance_criteria that reference states? For example:
acceptance_criteria:
- Given a button in the disabled state
When the user hovers
Then the button does not change
But then we need to parse the Given/When/Then to extract the state. That's NLP.
Alternatively, we can structure the acceptance criteria:
acceptance_criteria:
- state: disabled
interactions:
- event: hover
expected: no-change
Then we can check that the state 'disabled' is in the design (public) and maybe that the design defines that the disabled state does not change on hover? But the design might not have that information.
So we leave acceptance criteria for future when we have a way to represent interactions in the design.
Given the time, we'll stick to visual_specs.
This design connects:
- Specs (visual_specs) to design component states.
And we leave acceptance criteria (behavioral) as a separate future work.
We can note that the tool is for synchronizing visual specifications.
If the user wants to include acceptance criteria, we need a structured format for them and a way to represent interactions in the design.
So the answer:
We design a synchronization layer that:
1. Requires design components to be defined in JSON with states and properties, and each state can be marked as `internal` (default false) to exclude from spec checks.
2. Requires specs to be in YAML/JSON with a `component` field and a `visual_specs` array that lists states and required properties.
3. A tool that checks that every state and property in the visual_specs is present in the design's public states, and that every public state in the design is in the visual_specs.
We do not handle behavioral acceptance criteria in this version.
We can output errors and exit with non-zero if there are mismatches.
This can be integrated into CI/CD.
Let me write a more detailed example:
Example:
design/button.json:
{
"component": "Button",
"states": {
"default": {
"public": true,
"background-color": "#007bff",
"color": "#ffffff",
"border": "1px solid #007bff"
},
"disabled": {
"public": true,
"background-color": "#007bff",
"opacity": "0.5"
},
"loading": {
"public": false,
"background-color": "#f0f0f0"
}
}
}
specs/button.yaml:
component: Button
visual_specs:
- state: default
properties:
background-color: "#007bff"
color: "#ffffff"
- state: disabled
properties:
opacity: "0.5"
This would pass because:
- The spec's default state: design has background-color and color, and they match. The design has an extra property (border) which is okay.
- The spec's disabled state: design has opacity and it matches. The design has background-color but the spec doesn't require it, so okay.
- The design has two public states: default and disabled, and both are in the spec.
The loading state is internal, so it's ignored.
If we remove the disabled state from the spec, then we get an error because the design has a public state (disabled) that is not in the spec.
If we change the opacity in the spec to 0.6, then we get a mismatch error.
If we add a property in the spec for the default state that is not in the design, we get an error.
This seems to work.
Now, what about acceptance criteria? We can extend the spec to have:
acceptance_criteria:
- state: disabled
interactions:
- event: hover
expected: no-change
But without a way to represent that in the design, we can't check. So we leave it.
Alternatively, we can have a separate tool that checks acceptance criteria against a test suite? That's beyond the scope.
So the final answer:
We design a doc-to-design synchronization layer that focuses on visual specifications (component states and their properties) and ensures that the design system's public states match the specifications.
We do not handle behavioral acceptance criteria in this layer, but we leave the spec format extensible to include them for future.
The tool is run as a CI step to catch drifts.
We can also generate documentation from the design system and the spec, but that's a separate feature.
This is a practical solution for the given problem.
Let me know if you have any questions.
I'll design a comprehensive Doc-to-Design Synchronization Layer that creates bidirectional connections between product documentation (specs/acceptance criteria) and design system components (states/variants). This acts as a single source of truth bridge.
Architecture Overview
┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────┐
│ Documentation │◄──►│ Synchronization │◄──►│ Design System │
│ (Specs/AC) │ │ Layer │ │ (Components) │
└─────────────────┘ └─────────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────┐
│ Source Files │ │ Mapping Engine │ │ Design Tokens │
│ (Markdown/ │ │ • State Mapping │ │ • Variants │
│ YAML/JSON) │ │ • Property Sync │ │ • Props │
└─────────────────┘ └─────────────────────┘ └─────────────────┘
Core Components
1. Canonical Schema (The Bridge Format)
# sync-schema.yaml
component:
name: string # Design component name
source: string # Source file path/reference
states:
- name: string # e.g., "default", "error", "loading"
source_ref: string # Line/anchor in doc file
properties:
design_tokens: # Links to design tokens
- token: string # e.g., "color.border.default"
value: string # Current value
spec_requirements: # Links to acceptance criteria
- ac_id: string # AC reference ID
condition: string # "must have", "should not"
acceptance_criteria:
- id: string # Unique AC identifier
component_ref: string # Component it validates
state_ref: string # State it applies to
testable: boolean # Can be auto-validated?
validation_rule: # Machine-readable rule
type: string # "property_exists", "value_equals", etc.
path: string # JSONPath to property
expected: any
2. Mapping Engine
State Mapping Logic:
// Map doc states → design states
const STATE_MAPPINGS = {
'default': { variants: ['default', 'primary'], design_states: ['default'] },
'error': { variants: ['error', 'danger'], design_states: ['error', 'invalid'] },
'loading': { variants: ['loading', 'pending'], design_states: ['loading'] },
'disabled': { variants: ['disabled'], design_states: ['disabled'] }
};
// Property synchronization
const PROPERTY_MAPPINGS = {
'color': {
doc_pattern: /color[:\s]+(#?[a-zA-Z0-9]+)/,
design_token: 'colors.{state}.{property}'
},
'spacing': {
doc_pattern: /(padding|margin)[:\s]+(\d+(px|rem|em))/,
design_token: 'spacing.{size}'
}
};
3. Synchronization Workflow
graph LR
A[Documentation Update] --> B[Change Detector]
B --> C{Change Type}
C -->|New State| D[Create Design Variant]
C -->|Modified AC| E[Update Validation Rules]
C -->|Broken Link| F[Generate Alert]
D --> G[Update Design System]
E --> G
G --> H[Generate Diff Report]
H --> I[Review/Approve]
I --> J[Bidirectional Sync Complete]
4. Implementation Modules
A. Document Parser
class SpecParser:
def extract_components(self, content: str) -> List[ComponentRef]:
"""Parse markdown/YAML/JSON for component references"""
# Detect patterns like:
# - `[Button]`
# - `Component: Button`
# - `### Button States`
def extract_states(self, content: str, component: str) -> List[State]:
"""Extract state descriptions and AC references"""
def extract_acceptance_criteria(self, content: str) -> List[AC]:
"""Parse Gherkin or structured AC"""
B. Design System Connector
interface DesignSystemAPI {
getComponent(name: string): ComponentDefinition;
createVariant(component: string, variant: Variant): void;
updateProperties(component: string, variant: string, tokens: Token[]): void;
validateState(component: string, state: string): ValidationResult;
}
// Figma/Storybook/Sketch/Code implementation adapters
C. Validation Engine
class StateValidator:
def validate_design_matches_spec(self, component: str, state: str):
design_state = design_api.get_state(component, state)
spec_state = spec_parser.get_state(component, state)
return {
'properties_match': self.compare_properties(
design_state.properties,
spec_state.required_properties
),
'acceptance_criteria_met': self.check_ac(
spec_state.ac_refs,
design_state.implementation
),
'missing_design_tokens': self.find_missing_tokens(
spec_state.referenced_tokens
)
}
5. Data Flow & Storage
data/
├── mappings/ # Machine-readable mappings
│ ├── button.mapping.yaml # Component → states → tokens
│ └── input.mapping.json
├── cache/ # Quick lookup cache
│ └── design_tokens_index.json
├── diffs/ # Generated diff reports
│ └── 2024-01-15-button.json
└── history/ # Change history for rollback
6. CLI/CI/CD Integration
# Check sync status
npx doc-design-sync check --component=Button
# Generate missing design variants from specs
npx doc-design-sync generate --from-specs
# Validate all components
npx doc-design-sync validate --strict
# Watch mode for development
npx doc-design-sync watch --dir=./docs --design-token-file=tokens.json
7. Key Features
A. Bidirectional Linking:
- Docs can reference design tokens:
{{token:color.primary}}
- Design files can reference AC IDs via comments/metadata
B. Auto-Detection:
# In documentation:
<!-- sync:design-component="Button" -->
## Button States
- **Default**: Primary action. See [design-abc123] for implementation.
- **Error**: Shown when validation fails. Must have red border.
C. Validation Rules DSL:
validation:
- when: state == "error"
must_have:
- token: "colors.error.main"
- property: "borderWidth"
equals: 2
must_not_have:
- property: "backgroundColor"
equals: "transparent"
D. Reporting:
{
"component": "Button",
"sync_status": "drifted",
"issues": [
{
"type": "missing_property",
"state": "loading",
"property": "spinnerColor",
"doc_ref": "docs/buttons.md#loading-state",
"suggestion": "Add `spinnerColor: tokens.colors.primary`"
},
{
"type": "orphaned_design_state",
"state": "hover",
"doc_ref": null,
"message": "Design has 'hover' state but no spec reference"
}
],
"last_synced": "2024-01-15T10:30:00Z"
}
8. Integrations
| System | Integration | Direction |
|---|
| Figma | Plugin API | ↔ Bi-directional |
| Storybook | Addon/CSF | ↔ Bi-directional |
| Zeroheight | API | → Docs from Design |
| Jira/Linear | Issue links | → AC tracking |
| GitHub | PR checks | ← CI validation |
| Design Tokens | Style Dictionary | ↔ Token sync |
9. Implementation Roadmap
Phase 1: Core Sync
- Parse markdown/YAML specs
- Connect to design system API
- Basic property validation
- CLI tool
Phase 2: Smart Features
- Auto-generate missing variants
- Visual diff generation
- Change impact analysis
- PR bot integration
Phase 3: Advanced
- Acceptance criteria test generation
- Automated visual regression triggers
- Token usage analytics
- Multi-design-system support
10. Example Use Case
Documentation (button-specs.md):
## Button Component
### States
1. **Default** - Primary action
- Background: `{{token:colors.primary}}`
- AC: [AC-123] Must be clickable
2. **Loading** - Async operation
- Shows spinner
- AC: [AC-456] Must prevent double-submit
Design System (Figma):
- Component:
Button/Primary
- Variants:
Default, Loading, Disabled
- Properties linked via plugin comments
After Sync:
- ✅
Loading state exists in both
- ✅
colors.primary token mapped
- ⚠️ AC-456 not linked to any prototype interaction (warning)
- 🔄
Default state properties match
Benefits
- Single Source of Truth: No more "design doesn't match spec" debates
- Traceability: Every design decision links to documentation
- Automated Validation: CI catches drifts immediately
- Reduced Bus Factor: Knowledge encoded in mappings
- Faster Onboarding: New designers/developers see connections instantly
Potential Challenges & Mitigations
| Challenge | Mitigation |
|---|
| Legacy documentation | Gradual migration with uncategorized bucket |
| Multiple design systems | Adapter pattern per system |
| Non-standard docs | Extensible parser plugins |
| Token naming mismatches | Fuzzy matching + manual override |
| Large repos | Incremental sync with caching |
This layer becomes the central nervous system connecting documentation, design, and implementation, ensuring consistency across the product development lifecycle.