Single-source component examples.
Author each example ONCE as a ~H block. The example/3 macro captures the
block's exact source (for the "View Code" panel) AND compiles it to a render
function, so the code shown can never drift from the live preview - the whole
point of the registry. Both the dev playground and petal.build render the same
examples/0, so they stay equivalent by construction.
defmodule PetalComponents.Showcase.Button do
use PetalComponents.Showcase, component: PetalComponents.Button, title: "Button"
example :basic, "Basic", description: "The default button." do
~H"""
<.button label="Save" />
"""
end
end
PetalComponents.Showcase.Button.examples()
#=> [%PetalComponents.Showcase.Example{id: :basic, title: "Basic",
# code: ~s|<.button label="Save" />|, render: #Function<...>, ...}]Rules for examples
- The body must be a single
~Hblock with no#{}interpolation - examples render deterministically withassigns = %{}(no outer state, no routes). iddoubles as the marketing section anchor; keep it stable.- Author copy in Matt's voice (no em-dashes, no banned marketing phrases).
Summary
Functions
Defines one example: a stable id, a human title, optional description:,
and a do block that must be a single ~H sigil.
Functions
Defines one example: a stable id, a human title, optional description:,
and a do block that must be a single ~H sigil.
example :basic, "Basic" do
~H"<.button label=\"Save\" />"
end
example :danger, "Danger", description: "For destructive actions." do
~H"<.button label=\"Delete\" color=\"danger\" />"
end