Statefully Documentation

Traffic Light

A traffic light with normal operation and power outage modes

Try It

Click on states in the diagram or use the buttons in the preview to see how the traffic light transitions between colors.

Traffic Light State Machine

State Diagram

Traffic Light
Normal Operation*
Green*
Yellow
Red
Power Outage+1

Preview

State Specification

This example shows nested states for Normal Operation (Green/Yellow/Red cycle) and a Power Outage mode with Blinking Yellow.

Spec
Traffic Light
	Normal Operation *
		Green *
			timer -> Yellow
		Yellow
			timer -> Red
		Red
			timer -> Green
	Power Outage
		Blinking Yellow *
			power_restored -> Normal Operation
	normal -> Normal Operation
	power_failure -> Power Outage

Prototype Code

Prototype
[Green]
  div.light style="width: 100px; padding: 20px; text-align: center;":
    div.indicator style="width: 60px; height: 60px; border-radius: 50%; background: #22c55e; margin: 0 auto 10px;":
    p style="font-size: 14px; color: #666;": "GO"
    button @click=timer style="margin-top: 10px; padding: 8px 16px;": "Next"

[Yellow]
  div.light style="width: 100px; padding: 20px; text-align: center;":
    div.indicator style="width: 60px; height: 60px; border-radius: 50%; background: #eab308; margin: 0 auto 10px;":
    p style="font-size: 14px; color: #666;": "CAUTION"
    button @click=timer style="margin-top: 10px; padding: 8px 16px;": "Next"

[Red]
  div.light style="width: 100px; padding: 20px; text-align: center;":
    div.indicator style="width: 60px; height: 60px; border-radius: 50%; background: #ef4444; margin: 0 auto 10px;":
    p style="font-size: 14px; color: #666;": "STOP"
    button @click=timer style="margin-top: 10px; padding: 8px 16px;": "Next"

[Blinking Yellow]
  div.light style="width: 100px; padding: 20px; text-align: center;":
    div.indicator style="width: 60px; height: 60px; border-radius: 50%; background: #eab308; margin: 0 auto 10px; animation: blink 1s infinite;":
    p style="font-size: 14px; color: #666;": "POWER OUT"
    button @click=power_restored style="margin-top: 10px; padding: 8px 16px;": "Restore Power"

Key Concepts

  • Nested states - Normal Operation contains the color states
  • Parallel modes - Normal vs Power Outage are separate operation modes
  • State transitions - Timer events move between colors in sequence
  • Cross-hierarchy transitions - power_failure/power_restored switch between modes