Keystone UI is a reusable UI component system for Rails applications built on the
view_component gem. It provides stable, authoritative UI primitives that avoid ERB noise,
prevent UI drift, and enable safe mass updates.
- All UI lives in ViewComponents (no partials).
- Components are Ruby objects with explicit keyword arguments.
- Helpers are thin render wrappers with no logic or conditionals.
- Styling uses Tailwind CSS utility classes applied directly in components.
- Rails 7+
- tailwindcss-rails v4+
- Add the gem to your Gemfile:
gem "keystone_ui"-
Run
bundle install. -
Run the install generator:
rails generate keystone:installThe generator handles setup automatically:
- If
app/assets/tailwind/application.cssdoes not exist, the generator creates it with the Tailwind import and Keystone source import. No need to runtailwindcss:installfirst. - If it already exists, the generator injects the Keystone source import after the existing Tailwind import line.
- It wires the Stimulus controllers by appending
registerControllers(application)toapp/javascript/controllers/index.js, so interactive components (accordion, modal, stat card info, …) work out of the box. If that file isn't present, the generator prints the one line to add manually.
At boot time, the engine initializer writes keystone_source.css with @source directives pointing to the gem's component files so Tailwind scans them automatically. The engine also adds the gem's controllers to your importmap automatically.
- The generator commits only an
@import "./keystone_source.css"line — no machine-specific paths in git. - On every app boot (dev server,
assets:precompile, CI), the engine writeskeystone_source.csswith@sourceand@importdirectives, including the stylesheet of keystone_ui-styles, which keystone_ui depends on. - Tailwind's JIT scanner finds all component classes automatically.
- When keystone updates with new components, they're picked up on the next build with no action required.
keystone_source.cssis the only stylesheet a host imports for keystone_ui and the gems built on it. No keystone gem ships a Tailwind file that tailwindcss-rails turns into a generated stylesheet inapp/assets/builds/tailwind.
A gem built on keystone_ui adds its own CSS and the files Tailwind should scan in
an initializer, and keystone_source.css includes them:
initializer "my_gem.tailwind" do
KeystoneUi.configuration.tailwind_imports << root.join("app/assets/tailwind/my_gem.css").to_s
KeystoneUi.configuration.tailwind_sources << root.join("app/views/**/*.erb").to_s
endRe-run the generator. It removes legacy @import and @source inline(...) lines
automatically:
rails generate keystone:installkeystone_ui decides light and dark mode for the whole app, including the dark:
classes in your own views. The html element's data-theme attribute decides it:
<html data-theme="dark"> <!-- always dark -->
<html data-theme="light"> <!-- always light -->
<html> <!-- follows the operating system -->Do not declare your own @custom-variant dark in application.css. keystone_ui's
rule applies to your classes as well as keystone_ui's components.
Place the toggle anywhere in a view:
<%= ui_theme_toggle %>It is one button showing a sun in light mode and a moon in dark mode. Pressing it
switches to the other mode at once and keeps that mode in a keystone_theme
cookie, and the server marks the html tag from that cookie so later pages open
in it. A visitor who has never pressed it sees the mode their device is set to,
and the button shows the sun or the moon to match. The install
generator adds the helper that does this to app/views/layouts/application.html.erb:
<html <%= keystone_theme_attributes %> lang="en">Add it by hand if your layout lives elsewhere.
Strongest first:
- The toggle's choice in this browser.
- A mode supplied by another gem, such as a signed-in user's saved mode.
- Light.
A gem supplies a mode by registering a callable that receives the view and returns
"light", "dark", "system", "custom" or nil. A custom mode marks the page
data-theme="custom":
KeystoneUi.configure do |config|
config.theme_mode_supplier = ->(view) { view.current_user&.theme_mode }
endKeystone UI components use two semantic color scales — accent and surface — defined as CSS custom properties. Components reference these via Tailwind classes like bg-accent-500, text-accent-600, bg-surface-100, etc. This means your entire UI updates when you change the color values — no need to touch component code.
keystone_ui-styles, which keystone_ui installs and imports for you, sets the default values:
| Scale | Default palette | Used for |
|---|---|---|
accent |
Blue (#3b82f6 at 500) |
Buttons, links, focus rings, active states, badges |
surface |
Zinc (#71717a at 500) |
Backgrounds, borders, text on dark mode surfaces |
Each scale provides shades 50-950, matching Tailwind's standard shade range.
Override the CSS custom properties in your app's application.css (after the Tailwind import):
@import "tailwindcss";
@import "./keystone_source.css";
@theme {
/* Override accent to indigo */
--color-accent-50: #eef2ff;
--color-accent-100: #e0e7ff;
--color-accent-200: #c7d2fe;
--color-accent-300: #a5b4fc;
--color-accent-400: #818cf8;
--color-accent-500: #6366f1;
--color-accent-600: #4f46e5;
--color-accent-700: #4338ca;
--color-accent-800: #3730a3;
--color-accent-900: #312e81;
--color-accent-950: #1e1b4e;
}You only need to override the shades you use. All Keystone components will pick up the new colors automatically.
If you're building a gem or engine that uses keystone_ui, do not set theme colors in your gem. The host app owns the theme. Your gem just uses the accent/surface Tailwind classes and they'll inherit whatever the host app has configured.
In your gem's test/dummy app, set up colors the same way a host app would:
- Add
keystone_uito your gemspec as a dependency - Run
rails generate keystone:installintest/dummy - The default blue/zinc theme applies automatically — no extra config needed
- To test with a custom theme, override the variables in
test/dummy/app/assets/tailwind/application.css:
@import "tailwindcss";
@import "./keystone_source.css";
@theme {
--color-accent-500: #6366f1;
/* ... */
}Key principle: gems use bg-accent-500, text-surface-700, etc. in their views. The host app decides what those colors actually are — either statically in CSS, or dynamically with keystone_colors for per-user theming.
For dynamic, per-user color customization (e.g. letting users pick their own accent color), see the keystone_colors gem, which generates the CSS custom properties from user preferences at runtime.
A look is one CSS file that changes how components look without editing the
gem. It sets the --ks- variables that keystone_ui-styles defines, and a
component reads them through the ks- classes it renders. Buttons, panels,
cards, alerts, badges, form fields, the modal, the mobile action menu, the column
picker, multi select, search select, copy button, theme toggle, checkbox row, radio card, option
card, file upload and colour picker read them today. So do the stat card, chart
card, card link, call to action banner, feature grid, hero, data table, code,
accordion, disclosure, tab switcher, progress, funnel, bucket, pipeline and swipe
deck, and the navbar title, nav items, nav dropdown, bottom nav, mobile header
and settings link.
This look changes the corner radius, font, label weight, border, padding and colours of every button:
/* app/assets/tailwind/look.css */
:root {
--ks-radius-control: 9999px;
--ks-font-body: "Roboto", sans-serif;
--ks-font-weight-strong: 500;
--ks-border-width-control: 1px;
--ks-spacing: 0.3rem;
--ks-color-accent: #6200ee;
--ks-color-accent-hover: #7c4dff;
--ks-color-neutral: #616161;
--ks-color-neutral-hover: #757575;
--ks-color-danger: #b00020;
--ks-color-danger-hover: #c51162;
--ks-color-on-fill: #ffffff;
--ks-color-accent-dark: #bb86fc;
--ks-color-accent-hover-dark: #d1b3ff;
--ks-color-neutral-dark: #9e9e9e;
--ks-color-neutral-hover-dark: #bdbdbd;
--ks-color-danger-dark: #cf6679;
--ks-color-danger-hover-dark: #e0879a;
--ks-color-on-fill-dark: #000000;
}Each colour variable has a -dark partner that a button reads on a dark page. A
look that sets only the light variable leaves dark pages with the default
colour. The keystone_ui-styles README lists every variable and its default.
A host imports its look file after keystone_source.css:
@import "tailwindcss";
@import "./keystone_source.css";
@import "./look.css";keystone_ui-styles puts its defaults in Tailwind's base layer, and a :root
rule outside any layer overrides them. The look's :root rule must not sit
inside an @layer block.
A gem that ships a look registers its file in an initializer, and
keystone_source.css imports it after keystone_ui-styles:
initializer "my_look.tailwind" do
KeystoneUi.configuration.tailwind_imports << root.join("app/assets/tailwind/my_look.css").to_s
endA host can offer several looks and let the page pick one. Each look file scopes its variables to the look's name:
/* app/assets/tailwind/looks/material.css */
:root[data-look="material"] {
--ks-radius-control: 9999px;
--ks-color-accent: #6200ee;
--ks-color-accent-dark: #bb86fc;
}Register each look by name with its file, and name the default:
# config/initializers/keystone_ui.rb
KeystoneUi.configure do |config|
config.register_look :plain, Rails.root.join("app/assets/tailwind/looks/plain.css")
config.register_look :material, Rails.root.join("app/assets/tailwind/looks/material.css")
config.default_look = :plain
endkeystone_source.css imports every registered look, and keystone_theme_attributes
marks the html tag with data-look="plain". A gem can choose the look per
request by setting config.look_supplier to a lambda that receives the view and
returns a look's name. A name that is not registered leaves the page on the
default. A host that registers no looks gets no data-look attribute.
A Turbo visit carries the next page's look onto the page, as it does the theme.
Boot stops with KeystoneUi::LookCheck::Error when a registered look's file does
not exist, when the file sets no --ks- variables under
:root[data-look="<name>"], or when default_look names a look that is not
registered, so a mistake shows up the moment the app starts.
Use the helpers in ERB. Consuming apps should not instantiate components directly.
<%= ui_card(
title: "Revenue",
summary: "$42,300 this month",
link: reports_path
) %>
<%= ui_button(
label: "Create invoice",
href: new_invoice_path,
variant: :primary
) %>
<%= ui_data_table(
items: @products,
columns: [
{ name: "Name" },
{ quantity: "Quantity" },
{ price: "Price" }
],
empty_message: "No products found."
) do |table| %>
<% table.link(:name) { |item| product_path(item) } %>
<% end %>Renders a card layout with a title, summary, and a single call-to-action link.
Required props
title:(String)summary:(String)link:(String or URL)
Optional props
cta:(String, default"Read more")edge_to_edge:(Boolean, defaultfalse) — whentrue, removes horizontal border-radius and side borders on mobile, restoring them at thesmbreakpoint. Useful for cards that span the full viewport width on small screens.class:(String) — extra classes added to the component's outer element for this one use
Renders a deterministic button or link. If href is present, an <a> tag is rendered.
Otherwise, a <button> tag is rendered with type="button".
Required props
label:(String)
Optional props
href:(String or URL)method:(:get | :post | :patch | :put | :delete, default:get) — withhref:, any method other than:getrenders the button inside its own small form that sends that request when tappedvariant:(:primary | :secondary | :danger, default:primary)size:(:sm | :md | :lg, default:md)full_width:(Boolean, defaultfalse) — makes the button, and the form of a button sending a request, as wide as its row
<%= ui_button(label: "Start game", href: game_start_path(@game), method: :post, full_width: true) %>Renders a responsive data table. Accepts a collection of items (ActiveRecord objects, Structs, or hashes) and column definitions that map lookup keys to header labels.
Required props
items:(Array) — collection of AR objects, Structs, or hashescolumns:(Array of Hashes orColumnobjects) — each hash maps a lookup key to a header label, e.g.{ name: "Name" }. UseKeystone::Ui::Columnfor per-column options.
Optional props
empty_message:(String) — message displayed whenitemsis emptysort:(Symbol/String) — current sort column keysort_direction:(Symbol) —:ascor:descsort_url:(Lambda) —(col, dir) → urlfor generating sort linkshidden_columns:(Array) — column keys to hide (only affectshideablecolumns)key:(Symbol/String) — names the table so its saved layout can be found throughconfig.preference_suppliergroup_by:(Symbol/String) — lists the rows under heading rows named by this key's value, one heading for each run of rows that share itgroup_totals:(Hash) — subtotals for each group, keyed by the group's name, each a hash of column key to value shown under that column in the group's heading rowtotal:(Hash) — column key to value for a total row at the end of the tablecurrent_row:(item) — the item whose row is the viewer's own, given theks-table-row-currentclass andaria-current="true"; only the first row equal to it is marked
Column options
Keystone::Ui::Column.new(key, header_text, mobile_hidden: false, sortable: false, hideable: false, locked: false, align: nil)
| Option | Default | Description |
|---|---|---|
mobile_hidden: |
false |
hide on small screens (hidden sm:table-cell) |
sortable: |
false |
render header as clickable sort link |
hideable: |
false |
allow hiding via hidden_columns: / column picker |
locked: |
false |
on the first column, keep it in view while the rest of the table scrolls sideways; a locked column cannot be hidden or moved |
align: |
nil |
:start aligns the heading and cells left, :end aligns them right; nil keeps the table's own alignment, which puts the last column right |
Mobile-hidden columns
Use Keystone::Ui::Column objects to hide columns on mobile. Columns with mobile_hidden: true receive hidden sm:table-cell classes, hiding them on small screens and showing them from the sm breakpoint up. Columns are visible on mobile by default.
<%= ui_data_table(
items: @products,
columns: [
Keystone::Ui::Column.new(:name, "Name"),
Keystone::Ui::Column.new(:quantity, "Quantity", mobile_hidden: true),
Keystone::Ui::Column.new(:price, "Price")
]
) %>Sortable columns
Mark columns as sortable: true and pass sort:, sort_direction:, and sort_url: to render clickable header links with sort arrows. Sort links use data-turbo-action="replace" for clean Turbo navigation. Toggle logic: active asc → desc, active desc → asc, inactive → asc.
<%
columns = [
Keystone::Ui::Column.new(:name, "Name", sortable: true),
Keystone::Ui::Column.new(:quantity, "Quantity", mobile_hidden: true),
Keystone::Ui::Column.new(:price, "Price", sortable: true)
]
%>
<%= ui_data_table(
items: @products,
columns: columns,
sort: params[:sort],
sort_direction: params[:direction],
sort_url: ->(col, dir) { products_path(sort: col, direction: dir) }
) %>Hidden columns
Mark columns as hideable: true and pass hidden_columns: to filter them out server-side. Non-hideable columns are always shown even if listed in hidden_columns:.
<%= ui_data_table(
items: @products,
columns: columns,
hidden_columns: current_user.hidden_columns_for(:products)
) %>Saved layouts
Give a table a key: and it looks up its saved layout itself. The columns the call hides with hidden_columns: are the table's default layout, used whenever nothing is saved for the key.
<%= ui_data_table(
items: @products,
columns: columns,
key: :products,
hidden_columns: [ :sku ]
) %>Set config.preference_supplier to a lambda that receives the view and the key and returns { value:, save_url: }, or nil when the person can neither see nor save a layout. A gem that stores layouts, such as keystone_ui-preferences, sets it for the app. The table hides the hideable columns listed under "hidden_columns" in value, and keeps the columns its own call hides when value is nil or lists no "hidden_columns". When nothing is saved yet, return { value: nil, save_url: } so the person can save a first layout. When save_url is present, the table shows a "Columns" menu in a row above itself, aligned right, that saves to it. A table given no key:, or rendered with no supplier set, renders from its own call.
A saved value may also hold "column_order", a list of hideable column keys. The table renders its hideable columns in that order, then any hideable columns the list leaves out in the order they were declared. Columns that are not hideable keep their declared place, and the Columns menu lists its columns in the order the table shows them.
KeystoneUi.configure do |config|
config.preference_supplier = ->(view, key) { TablePreferences.for(view.current_user, key) }
endLinkable cells
Register links via table.link(:column_key) in the block. The block receives the current item and must return a URL string. The cell's value is wrapped in an <a> tag.
<%= ui_data_table(
items: @products,
columns: [
{ name: "Name" },
{ quantity: "Quantity" },
{ price: "Price" }
]
) do |table| %>
<% table.link(:name) { |item| product_path(item) } %>
<% end %>Actions column
Pass a block to add a trailing "Actions" column. The block receives the component instance; call actions on it with a sub-block that receives each item.
<%= ui_data_table(
items: @products,
columns: [
{ name: "Name" },
{ status: "Status" }
]
) do |table| %>
<% table.link(:name) { |item| product_path(item) } %>
<% table.actions do |item| %>
<%= ui_action_menu_item(label: "Edit", href: edit_product_path(item)) %>
<%= ui_action_menu_item(label: "Delete", href: product_path(item), method: :delete) %>
<% end %>
<% end %>Current row
Pass current_row: the item whose row belongs to the viewer, such as their own entry on a scoreboard. That row gets the ks-table-row-current class, which keystone_ui-styles colours, and aria-current="true", so a screen reader announces it as the current row. The item is compared with ==, and only the first equal row is marked.
<%= ui_data_table(
items: @scores,
columns: [ { team: "Team" }, { points: "Points" } ],
current_row: @my_score
) %>Each row's actions show in an action menu, opened by an ellipsis button, so a table never shows buttons. When an actions column is present, position-based styling classes shift automatically — the last data column receives middle styling and the actions column receives last styling.
Renders a "Columns" dropdown button with checkboxes for showing/hiding hideable columns. Pair with ui_data_table's hidden_columns: param.
Required props
columns:(Array ofColumnobjects) — same array passed toui_data_table
Optional props
hidden_columns:(Array) — currently hidden column keyssave_url:(String) — PATCH endpoint to persist preferences; omit for no persistence
Each column in the menu has an up and a down button that move it one place; the first column's up button and the last column's down button are disabled. Ticking, unticking and moving change only the open menu, and an unticked column's name turns grey straight away. When the menu closes, by a click outside it or on its Columns button, the Stimulus column-picker controller PATCHes { "hidden_columns": [...], "column_order": [...] } as JSON to save_url once, then reloads via Turbo.visit. Closing it with nothing changed sends nothing. When the save is refused or cannot reach the server, the menu says "Your column changes were not saved.", puts its boxes and order back to what the table shows, and does not reload the page.
<%= ui_column_picker(
columns: columns,
hidden_columns: @hidden_columns,
save_url: table_preferences_path("products")
) %>Wraps page content with consistent max-width and horizontal padding. When the page also uses ui_form_page or ui_show_page, it shows their desktop back link or breadcrumbs, and the form page title, at its top.
Optional props
max_width:(:sm | :md | :lg | :xl | :full, default:full) — constrains content width. Values map tomax-w-2xl,max-w-4xl,max-w-6xl,max-w-7xl, or no constraint.padding:(:standard | :none, default:standard) — adds responsive horizontal padding (px-4 sm:px-6 lg:px-8).class:(String) — extra classes added to the component's outer element for this one use
<%= ui_page(max_width: :lg) do %>
<!-- page content -->
<% end %>Groups related content with an optional header (title, subtitle, action) and vertical spacing.
Optional props
title:(String) — section headingsubtitle:(String) — secondary text below the titleaction:— slot for a trailing action (e.g. a button)menu:— a list of{ label:, href:, method: }items shown in an action menu in the header, such as Edit and Deletespacing:(:sm | :md | :lg, default:md) — top margin between sectionsclass:(String) — extra classes added to the component's outer element for this one use
<%= ui_section(title: "Products", subtitle: "All active items", spacing: :lg) do %>
<!-- section content -->
<% end %>Renders a CSS grid with responsive column counts and configurable gap sizes.
Optional props
cols:(Hash, default{ default: 1 }) — maps breakpoints to column counts (1-12). Keys::default,:sm,:md,:lg.gap:(:sm | :md | :lg | :xl, default:md) — uniform gap sizegap_x:(Symbol) — horizontal gap (overridesgap:)gap_y:(Symbol) — vertical gap (overridesgap:)
<%= ui_grid(cols: { default: 1, sm: 2, lg: 4 }, gap: :lg) do %>
<!-- grid items -->
<% end %>Renders a bordered, rounded container with padding and optional shadow.
Optional props
padding:(:sm | :md | :lg, default:md)radius:(:md | :lg | :xl, default:lg)shadow:(Boolean, defaulttrue)
<%= ui_panel(padding: :lg) do %>
<!-- panel content -->
<% end %>Renders a clickable card that wraps its content in an <a> tag with hover styling.
Required props
href:(String or URL)
Optional props
padding:(:sm | :md | :lg, default:md)shadow:(Boolean, defaulttrue)
<%= ui_card_link(href: product_path(@product)) do %>
<h3>Product name</h3>
<p>Product description</p>
<% end %>Wraps content in a <form> tag with proper method handling. For non-GET/POST methods (patch, put, delete), it renders a hidden _method input following Rails conventions. Supports multipart for file uploads.
Required props
action:(String) — form action URL
Optional props
method:(:get | :post | :patch | :put | :delete, default:post) — HTTP method. Non-native methods use a hidden_methodfield.multipart:(Boolean, defaultfalse) — setsenctype="multipart/form-data"for file uploadsdata:(Hash) — data attributes for the form element
<%= ui_form(action: items_path, method: :post) do %>
<%= ui_form_field(attribute: :name, required: true) %>
<%= ui_button(label: "Save", type: :submit) %>
<% end %>
<%= ui_form(action: item_path(@item), method: :patch, multipart: true) do %>
<%= ui_form_field(attribute: :name) %>
<%= ui_file_upload(name: "item[photo]", accept: "image/*", hint: "Max 5MB") %>
<%= ui_button(label: "Save", type: :submit) %>
<% end %>Renders a styled file upload with a clickable drop zone. Clicking anywhere on the zone opens the native file picker. Supports drag-and-drop — the zone highlights with accent colors on drag-over. Displays the selected file name(s) after pick or drop. Uses the file-upload Stimulus controller.
Required props
name:(String) — input name attribute
Optional props
label:(String, default"Choose file") — label text above the drop zoneaccept:(String) — accepted file types (e.g."image/*",".pdf,.doc")multiple:(Boolean, defaultfalse) — allow multiple file selectionhint:(String) — help text below the drop zone (e.g. file size limits)
<%= ui_file_upload(name: "avatar", accept: "image/*", hint: "PNG or JPG, max 5MB") %>
<%= ui_file_upload(name: "documents[]", multiple: true, label: "Upload documents", hint: "PDF, DOC up to 10MB each") %>A form field that searches the host app as a person types and submits the id of the record they pick. It is one field of an ordinary form, not a separate form. Uses the search-select Stimulus controller.
As the person types, the field asks url for matches with GET url?q=<typed text> and an Accept: application/json header. The host answers with a JSON array of {"id": ..., "label": ...} objects, and the field lists their labels in the order given, as text. Picking one sets a hidden input named by name: to its id and shows its label in the field. The down and up arrow keys move the highlight, Enter picks the highlighted choice, and Escape closes the list.
Required props
name:(String) — the name of the hidden input that submits the chosen idlabel:(String) — label text above the fieldurl:(String) — where matches are fetched from
Optional props
selected_id:/selected_label:— open the field with a record already chosen, so the form submits its id unchanged when nothing new is pickednew_label:(String) — adds a last choice, such as "Enter a new address", that clears the chosen id and shows the block passed to the helper. The block is drawn hidden inside the field and holds the host's fields for the new record.
<%= ui_search_select(name: "space[address_id]", label: "Address", url: matches_addresses_path,
selected_id: @space.address_id, selected_label: @space.address&.address, new_label: "Enter a new address") do %>
<%= ui_form_field(attribute: "address[line1]", label: "Street") %>
<% end %>A list whose rows can be dragged into a new order with a mouse or a finger. It is one field of an ordinary form and makes no request of its own, so nothing is saved until the form is submitted. Uses the sortable-list Stimulus controller, written with pointer events and no JavaScript dependency.
Each row holds a hidden field named by name: with the row's id, and dragging moves the field with the row, so the form submits the ids in the order shown. Give each list its own name: when a page has several, and each list orders only its own rows.
Dragging starts from the handle on the left of a row, so on a phone a finger on the rest of the row still scrolls the page. Each row also has Move up and Move down buttons, reachable by keyboard and named for screen readers, such as "Move Ann up". A status region announces the row's new position, such as "Ann is number 2 of 3.". A list longer than the screen does not scroll by itself during a drag.
Without JavaScript running, the rows show with no handle and no buttons, and the form submits the starting order.
Not tested in iPhone Safari or a Hotwire Native web view, only in Chrome with a mouse and emulated touch.
Required props
name:(String) — the name of each hidden field, such as"order[]"label:(String) — the list's name for screen readersrows:(Array) —{ id:, label: }hashes in their starting order
<%= ui_form(action: tie_order_path, method: :patch) do %>
<%= ui_sortable_list(name: "order[#{group.id}][]", label: "Tied for #{group.place}",
rows: group.players.map { |player| { id: player.id, label: player.name } }) %>
<%= ui_button(label: "Save") %>
<% end %>Wraps a label, input, hint, and error message in a consistent layout. Infers label text from the attribute name when not explicitly provided.
Required props
attribute:(Symbol) — the form attribute name
Optional props
label:(String) — explicit label text (inferred fromattribute:if omitted)type:(:text | :number | :email | :password | :date | :datetime | :textarea, default:text) —:datetimerenders adatetime-localinput, and aTimeorDateTimegiven asvalue:is written asYYYY-MM-DDTHH:MMrequired:(Boolean, defaultfalse) — shows a red asterisk after the label, and on an input sets therequiredattribute so the form will not send while it is emptyhint:(String) — help text below the inputplaceholder:(String)min:/max:(for number inputs)disabled:(Boolean, defaultfalse) — shows the value in an input that cannot be typed into and is not submittedautofocus:(Boolean, defaultfalse) — puts the cursor in the input when the page opensautocomplete:/autocapitalize:/inputmode:(String) — written onto the input as given, such as"email","none"and"numeric"
The label is tied to its input, textarea, select or checkbox through an id built from attribute:, so "player[email]" gets the id player-email.
<%= ui_form_field(
attribute: :name,
label: "List Name",
required: true,
hint: "Enter a descriptive name"
) %>Renders a standalone <input> element with consistent styling.
Required props
name:(String)
Optional props
type:(:text | :number | :email | :password | :date | :datetime, default:text) —:datetimerenders adatetime-localinput, and aTimeorDateTimegiven asvalue:is written asYYYY-MM-DDTHH:MMvalue:(String/Number)placeholder:(String)disabled:(Boolean, defaultfalse)min:/max:/step:(for number type)autofocus:/required:(Boolean, defaultfalse)autocomplete:/autocapitalize:/inputmode:(String) — written onto the input as given
<%= ui_input(name: "search", placeholder: "Search...") %>
<%= ui_input(name: "quantity", type: :number, value: 1, min: 1) %>Renders a multi-line <textarea> element with consistent styling.
Required props
name:(String)
Optional props
value:(String)rows:(Integer, default3)placeholder:(String)disabled:(Boolean, defaultfalse)
<%= ui_textarea(name: "notes", rows: 5, placeholder: "Add notes...") %>Renders a page title area with an optional subtitle and action slot. On small screens the title stacks above actions; on wider screens they sit side-by-side.
Required props
title:(String) — the page heading
Optional props
subtitle:(String) — secondary text below the titleaction_url:(String) — the address of the screen's main action. It is drawn as a button when noheader.actionblock is given, and published forui_mobile_actioneither wayaction_label:(String, default"Add new") — the name of the main actionclass:(String) — extra classes added to the component's outer element for this one use
<%= ui_page_header(title: "Products", action_url: new_product_path, action_label: "New Product") %>Block API — register an action slot via header.action, which is drawn alone when action_url: is also given:
<%= ui_page_header(title: "Products", subtitle: "Manage your catalog") do |header| %>
<% header.action do %>
<%= ui_button(label: "New Product", href: new_product_path) %>
<% end %>
<% end %>Renders a styled alert/flash message with type variants, optional title, and dismissible button.
Required props
message:(String) — the alert message
Optional props
type:(:info | :success | :warning | :error, default:info) — determines background/text colortitle:(String) — bold title above the messagedismissible:(Boolean, defaultfalse) — shows a dismiss button whentrueclass:(String) — extra classes added to the component's outer element for this one use
<%= ui_alert(message: "Changes saved successfully.", type: :success) %>
<%= ui_alert(message: "Could not save record.", type: :error, title: "Error", dismissible: true) %>Renders a styled <select> dropdown.
Required props
name:(String)
Optional props
options:(Array of[label, value]pairs, default[])selected:(String) — pre-selected valueinclude_blank:(String) — blank option labeldisabled:(Boolean, defaultfalse)
<%= ui_select(
name: "status",
options: [["Active", "active"], ["Inactive", "inactive"]],
selected: "active",
include_blank: "Select status..."
) %>Renders an inline status badge.
Required props
label:(String)
Optional props
variant:(:neutral | :success | :danger | :warning | :info, default:neutral)class:(String) — extra classes added to the component's outer element for this one use
<%= ui_badge(label: "Active", variant: :success) %>
<%= ui_badge(label: "Expired", variant: :danger) %>Shows a figure, such as an amount, in plain text or in the success or danger colour.
Required props
text:(String)
Optional props
tone:(:neutral | :success | :danger, default:neutral)
<%= ui_figure(text: "$4,700.00", tone: :success) %>
<%= ui_figure(text: "-$300.00", tone: :danger) %>Shows an image, centred and never taller than half the visible screen, so what follows it stays in view on a phone.
Required props
src:(String) — the address of the image to showalt:(String) — the text read out in place of the image
Optional props
full_size_url:(String) — when given, tapping the picture opens this address in a new tab
<%= ui_picture(src: url_for(question.picture.variant(:display)), alt: question.text, full_size_url: url_for(question.picture)) %>Shows a heading at one of three sizes, with an optional short note at the right end of its row.
Required props
text:(String)
Optional props
size:(:sm | :md | :lg, default:md)note:(String) — a short note in muted text at the right end of the heading's row
<%= ui_heading(text: "Work", note: "12.5 billable hours") %>
<%= ui_heading(text: "Monthly report", size: :lg) %>Shows small, uppercase, muted text for placing above a title or a figure.
Required props
text:(String)
<%= ui_caption(text: "Work report") %>Shows a paragraph of running text.
Required props
text:(String)
<%= ui_paragraph(text: "Work from 1 to 30 September.") %>Shows rows of a label and its value, such as a ledger, a byline beside a title, or a list of terms and what they mean.
Required props
rows:(Array of Hashes) — each row is{ label:, value: }, with optionalnote:(a short note under the label),total: true(draws the row with more weight) andfallback:(shown when the value isnilor empty)
Optional props
align:(:start | :end, default:start) —:startplaces each value beside its label,:endpushes it to the right end of its row
<%= ui_value_list(align: :end, rows: [
{ label: "Rate", value: "$150.00", note: "per hour" },
{ label: "Billable hours", value: "12.5" },
{ label: "Reviews", value: nil, fallback: "N/A" },
{ label: "Total billed", value: "$1,875.00", total: true }
]) %>Draws a bar chart on the server as an SVG, so it shows with no JavaScript and prints as it shows on screen. The value axis is labelled in round steps reaching just past the largest value, with a grid line at each step. The bars stretch to fill the chart's width, the chart grows no taller than it is in an 800px-wide column, and its labels stay at the page's small text size at any width.
Required props
bars:(Array of Hashes) — each bar is{ label:, value: }, with optionalshaded: trueto draw it faded, such as a weekend day
Optional props
show_values:(Boolean, defaultfalse) — write each bar's value on it
<%= ui_bar_chart(show_values: true, bars: [
{ label: "Fri", value: "2.5" },
{ label: "Sat", value: "0.5", shaded: true }
]) %>Renders a metric card for dashboards.
Required props
label:(String)value:(String/Number)
Optional props
variant:(:neutral | :success | :danger | :warning | :info, default:neutral)suffix:(String) — unit label after the valuedefinition:(String) — what the metric capturescalculation:(String) — how the metric is computedchange:(Number) — percent change against the previous period, shown as ▲/▼href:(String) — turns the value into a link to that URL; the card itself stays unlinkednote:(String) — a short note shown under the valueplain:(Boolean, defaultfalse) — draws a plain figure with no card border or background, for a row of figuresfallback:(String) — shown in a muted colour when the value is missing, such as"N/A"
When definition: or calculation: is given, an info button appears. Hovering or focusing it shows the details in a panel floating below the card, and tapping it toggles the panel on touch screens. The card never changes size.
<%= ui_stat_card(label: "Revenue", value: "$42,300", variant: :success, suffix: "/mo") %>
<%= ui_stat_card(label: "Merged", value: 12, href: "/pull_requests?state=merged", definition: "Pull requests merged in the range.") %>Shows the working behind a figure, closed by default under a quiet "How this is worked out" row, so a reader can check how a number was reached without it taking over the page. Put it under the figure it explains, such as a ui_stat_card.
Required props
groups:(Array of Hashes) — each withlines:and an optionaltitle:. Each line is a Hash withlabel:,working:andresult:.
Optional props
summary:(String, default"How this is worked out") — the text on the row that opens it
Each line is laid out as its label, its working and its result in three columns, in the same quiet text as a form hint.
<%= ui_stat_card(label: "Perfect value", value: "$107,695.00") %>
<%= ui_calculation(groups: [
{ title: "Store runs", lines: [
{ label: "Money a year", working: "$34.00 × 1,825", result: "$62,050.00" },
{ label: "Time a year", working: "1 hour × 1,825 × $25.00 an hour", result: "$45,625.00" }
] },
{ title: "How it adds up", lines: [
{ label: "Perfect value", working: "$107,675.00 in costs + $20.00 missed out", result: "$107,695.00" }
] }
]) %>Renders a card wrapper for chart content with a title and configurable height.
Required props
title:(String)
Optional props
height:(:sm | :md | :lg, default:md) — maps toh-48,h-64,h-96
<%= ui_chart_card(title: "Monthly Revenue", height: :lg) do %>
<!-- chart content -->
<% end %>Renders a button that copies text to the clipboard.
Required props
text:(String) — the text to copy
Optional props
label:(String, default"Copy")success_message:(String, default"Copied!")error_message:(String, default"Failed!")
<%= ui_copy_button(text: "https://example.com/invite/abc123") %>Renders a modal dialog with title, close button, and backdrop.
Required props
title:(String)
Optional props
size:(:sm | :md | :lg | :xl, default:md)
<%= ui_modal(title: "Confirm Delete", size: :sm) do %>
<p>This action cannot be undone.</p>
<% end %>Renders collapsible question/answer items.
Optional props
items:(Array of Hashes) — each with:questionand:answerkeys
<%= ui_accordion(items: [
{ question: "What is Keystone?", answer: "A UI component library for Rails." },
{ question: "How do I install it?", answer: "Add the gem and run the generator." }
]) %>Renders a tab bar with active state indicator. Uses Stimulus tab-switcher controller.
Required props
tabs:(Array of Strings) — tab labels
<%= ui_tab_switcher(tabs: ["Overview", "Details", "History"]) do %>
<!-- tab panel content -->
<% end %>Renders a toggleable card option (radio-like selection).
Required props
name:(String) — input namevalue:(String) — input value
Optional props
selected:(Boolean, defaultfalse)input_data:(Hash) — data attributes for the hidden inputlabel_data:(Hash) — data attributes for the label
<%= ui_option_card(name: "theme", value: "dark", selected: true) do %>
Dark Mode
<% end %>Renders a large hero section for landing pages.
Required props
title:(String)
Optional props
subtitle:(String)badge:(String) — small badge text above the titlelayout:(:split | :centered, default:split)height:(:screen | :content, default:screen) —:screenkeeps the hero at least the full screen height, and:contentdraws it only as tall as its content and its padding
<%= ui_hero(title: "Build faster with Keystone", subtitle: "UI components for Rails", badge: "New") do |hero| %>
<% hero.with_aside do %>
<!-- image or illustration -->
<% end %>
<% end %>Renders a grid of feature cards with icons.
Required props
title:(String)features:(Array of Hashes) — each with:icon,:title,:description
Optional props
subtitle:(String)
<%= ui_feature_grid(
title: "Why Keystone?",
subtitle: "Built for Rails developers",
features: [
{ icon: "🚀", title: "Fast", description: "No build step required." },
{ icon: "🎨", title: "Themeable", description: "CSS custom properties." }
]
) %>Renders a call-to-action banner with title, subtitle, and action buttons.
Required props
title:(String)
Optional props
subtitle:(String)
<%= ui_cta_banner(title: "Ready to get started?", subtitle: "Try Keystone today.") do %>
<%= ui_button(label: "Get Started", href: signup_path) %>
<% end %>Renders an HSV color picker with swatch preview and a text field holding its value. Uses Stimulus color-picker controller.
A colour typed in the text field as hex, rgb(), hsl() or oklch() is drawn in the swatch and submitted exactly as typed. A typed value the browser cannot read as a colour is not drawn or submitted. A colour chosen in the hue panel is submitted as six-digit hex.
Required props
name:(String) — form input name
Optional props
value:(String, default"#000000") — initial colour, as hex,rgb(),hsl()oroklch()label:(String)
<%= ui_color_picker(name: "accent_color", value: "#3b82f6", label: "Accent") %>Renders the top-level navigation bar with slots for desktop and mobile sections. Sticky by default.
Optional props
sticky:(Boolean, defaulttrue)hide_logo_on_mobile:(Boolean, defaultfalse). Hides thelogoslot belowlgand keeps it fromlgup, for a page that shows its own title in the phone header.
Slots: logo, desktop_links, desktop_right, mobile_left, mobile_center, mobile_right
<%= ui_navbar do |nav| %>
<% nav.with_logo do %>
<%= link_to "MyApp", root_path %>
<% end %>
<% nav.with_desktop_links do %>
<%= ui_nav_item(label: "Dashboard", href: root_path, active: true) %>
<% end %>
<% end %>Draws the app's declared tabs as a top bar on lg screens and wider, or as a sidebar when the person's saved placement is left or right as described below, then the page content the layout passes as a block. Each declared group is a menu in the top bar holding its tabs, and each tab declared outside any group is a plain link, in declared order unless the person saved an order as described below. A tab whose permission check fails for the view is left out, and so is a group whose tabs are all left out. Below lg it draws only the page content, so the phone's bottom tab bar and mobile header stay as they are. With no tabs declared, or none the person may see, it draws only the page content, unless the layout hands it a logo or menus as shown below. Whenever it draws a top bar or a sidebar, it hands the layout one element holding both the navigation and the page content, so a layout that arranges the body's children, such as a grid of header, stretching row and footer, sees the same single element in every placement.
<%= ui_navigation do %>
<%= yield %>
<% end %>To put the app's logo and its menus, such as the account menu and the user menu, in the same top bar, set them inside the block. The logo is drawn at the left end of the bar and the menus at its right end, after the tabs. A layout that sets neither gets a bar holding only the tabs. When the person may see no tab, a layout that sets either still gets the bar, holding just the logo and menus.
<%= ui_navigation do |navigation| %>
<% navigation.with_logo do %>
<%= link_to "MyApp", root_path %>
<% end %>
<% navigation.with_menus do %>
<%= ui_nav_dropdown(title: "Account", area: "account") do %>
<%= link_to "Settings", settings_path %>
<% end %>
<% end %>
<%= yield %>
<% end %>The navigation asks config.preference_supplier for the key :navigation and reads the placement under "placement" in the returned value. With "left" or "right" it draws a sidebar on that side of the page content on lg screens and wider, showing each group as its label alone, which opens to list the group's tabs when clicked and closes when clicked again, with the group holding the current page's tab open when the page loads, the logo at the top and the menus at the bottom. An open group's tabs sit inside one element with the class ks-sidebar-group-tabs, so a stylesheet can draw a border around them and lines between them, and a tab declared outside any group is never inside one. A menu in the sidebar opens in place: the panel marked data-dropdown-target="menu" inside an element with data-controller="dropdown" is drawn on its own line below its button, inside the sidebar, instead of as a dropdown laid over it, even when the app's own stylesheet positions that panel absolutely, as long as that stylesheet is in a CSS layer below Tailwind's utilities, such as components. A closed menu's panel, marked by the hidden class both the gem's dropdown controller and tailwindcss-stimulus-components toggle, stays out of sight, out of the keyboard's tab order and away from screen readers, but still counts toward the sidebar's width, so the sidebar is always as wide as its widest item and opening or closing a menu never changes it. The sidebar scrolls when its content is taller than the screen. Menus in the top bar still open as dropdowns. Below lg the sidebar is not drawn and the page content takes the full width. With "top", no supplier, no saved value or any other placement it draws the top bar. A gem that stores preferences, such as keystone_ui-preferences, sets the supplier for the app.
For the :navigation key the supplier returns the saved value in this shape:
{ value: { "placement" => "left" } }The same value may hold the person's order of groups and tabs under "order", a list with one entry per group. Each entry names a group by its declared label under "group", and may list that group's tab keys as strings under "tabs". Both placements draw the groups, and each group's tabs, in that order. Groups and tabs the order does not name come after the named ones, in declared order. A group label or tab key in the order that is no longer declared is ignored.
{ value: { "placement" => "left", "order" => [ { "group" => "Admin" }, { "group" => "Sales", "tabs" => [ "orders", "quotes" ] } ] } }Declare the groups and tabs in the app's Keystone UI initializer. A tab's href: is an address or a lambda that receives the view and returns one, and permitted: is a lambda that receives the view and returns whether the current person may see the tab.
KeystoneUi.configure do |config|
config.navigation_group "Sales" do |group|
group.tab :quotes, label: "Quotes", href: ->(view) { view.quotes_path }, permitted: ->(view) { view.policy(Quote).index? }
group.tab :orders, label: "Orders", href: "/orders", permitted: ->(_view) { true }
end
endTo show a tab on its own, outside any group, declare it with config.navigation_tab, which takes the same key, label:, href: and permitted: as a group's tab. The top bar draws it as a plain link among the menus, and the sidebar draws it as a plain tab with no group label, which does not open or close, in the place it was declared among the groups. A saved order names it under "group" by its label, the same as a group.
KeystoneUi.configure do |config|
config.navigation_tab :console, label: "Console", href: "/console", permitted: ->(_view) { true }
config.navigation_group "Sales" do |group|
group.tab :quotes, label: "Quotes", href: "/quotes", permitted: ->(_view) { true }
end
endBoot stops with KeystoneUi::NavigationCheck::Error when a declared tab has no label or no href:, naming the tab's key, when two declared tabs share a key, naming the key, or when a declared group has no tabs, naming the group, so a mistake shows up the moment the app starts. It does not check that a tab's link leads to a page that exists.
To mark where the person is, set config.current_tab_supplier to a lambda that receives the view and returns the key of the declared tab the current page belongs to. The top bar shows that tab and the menu holding it as active, and the sidebar gives that tab and its group's label the active class. A tab declared outside any group is marked the same way, with no menu or group label to mark. Returning nil or a key no declared tab has marks nothing, and so does setting no supplier. In this example each controller names its tab, and a controller that names none marks nothing:
KeystoneUi.configure do |config|
config.current_tab_supplier = ->(view) { view.controller.try(:navigation_tab) }
endclass QuotesController < ApplicationController
def navigation_tab = :quotes
endRenders a single nav link within the navbar.
Required props
label:(String)href:(String)
Optional props
active:(Boolean, defaultfalse)
<%= ui_nav_item(label: "Dashboard", href: "/", active: current_page?(root_path)) %>Renders a dropdown menu within the navbar. Uses Stimulus dropdown controller.
Required props
title:(String)area:(Symbol/String)
Optional props
active:(Boolean, defaultfalse)
<%= ui_nav_dropdown(title: "Settings", area: :settings, active: false) do %>
<%= link_to "Profile", profile_path %>
<%= link_to "Billing", billing_path %>
<% end %>Renders a mobile bottom tab bar. Hidden on desktop (lg:hidden).
No props. Wrap ui_bottom_nav_item calls inside.
<%= ui_bottom_nav do %>
<%= ui_bottom_nav_item(label: "Home", href: "/", icon: "<svg>…</svg>", active: true) %>
<%= ui_bottom_nav_item(label: "Search", href: "/search", icon: "<svg>…</svg>") %>
<% end %>Renders a single bottom nav tab.
Required props
label:(String)href:(String)icon:(String) — raw SVG string
Optional props
active:(Boolean, defaultfalse)
<%= ui_bottom_nav_item(label: "Home", href: "/", icon: "<svg>…</svg>", active: true) %>Renders a mobile header with back link, title, and optional subtitle. Hidden on lg: screens. With a nil back_url: it shows no back link, as on a nav tab's own page.
The title and subtitle sit between the back link and the bar's right-side controls and start at the left of that space, and text too long for it ends in an ellipsis. In ui_navbar's mobile_left slot, controls that leave less than 6rem for the title move to a second row under it. In a hand-written top bar, make the header a direct child of the bar's flex row, and add max-lg:has-[.ks-mobile-header-title]:flex-wrap to the bar if its controls can fill its width.
Required props
title:(String)back_url:(String)
Optional props
subtitle:(String)
<%= ui_mobile_header(title: "Edit Product", back_url: products_path) %>Renders an ellipsis (⋯) button that opens a dropdown of actions, at every screen size. Uses the Stimulus action-menu controller. The menu opens under its button, or above it when there is no room below, and at the top of the screen when it fits neither way. An open menu moves with its button while the page scrolls, and closes when a tap or click is released outside it or the screen resizes. Fill it with ui_action_menu_item.
<%= ui_action_menu do %>
<%= ui_action_menu_item(label: "Edit", href: edit_product_path(@product)) %>
<%= ui_action_menu_item(label: "Delete", href: product_path(@product), method: :delete) %>
<% end %>One entry in an action menu. A link when method: is :get, and a form button that sends the method otherwise. An item that deletes asks for confirmation first.
| Param | Required | Default |
|---|---|---|
label: |
yes | — |
href: |
yes | — |
method: |
no | :get |
confirm: |
no | nil |
Renders an ellipsis dropdown for mobile action menus. Hidden on lg: screens. Uses the Stimulus action-menu controller, so it opens, moves and closes as ui_action_menu does.
No props. Pass action links as block content.
<%= ui_mobile_actions do %>
<%= link_to "Edit", edit_product_path(@product) %>
<%= link_to "Delete", product_path(@product), data: { turbo_method: :delete } %>
<% end %>Draws the action a screen gives ui_page_header through action_url: as a plus icon link in the phone top bar, named with action_label:. It draws nothing on a screen with no action. It is hidden from sm screens up, where the page header shows the action, so the action shows once at every width. It is also hidden when the page is printed and inside a Hotwire Native web view, where the layout writes the hotwire-native class on <html> and declares that Tailwind variant, so give native users another way to reach the action, such as ui_mobile_actions.
No props. Call it from the layout's top bar, which is rendered after the screen.
<%= ui_navbar do |nav| %>
<% nav.with_mobile_right do %>
<%= ui_mobile_action %>
<% end %>
<% end %>Wraps a form page with title and back navigation. Sets content_for signals so the navbar can render mobile header context. On lg screens and wider, where the mobile header is hidden, it shows a link back to back_url at the top of the page's ui_page, so call ui_page on the same page.
Required props
title:(String)
Optional props
back_url:(String) — defaults to the last link of the trail; with noback_url:and no trail, rendering raisesKeystoneUi::MissingBackLinknaming the page, while an empty trail needs noback_url:subtitle:(String)trail:(Array of[label, href]pairs) — the pages above this one; onlgscreens and wider, the back link sits above breadcrumbs ending withtitle. An empty trail marks a nav tab's own page, which shows no back link and no breadcrumbs. When the page passes none, it uses the trail the app supplies throughconfig.trail_supplier
<%= ui_form_page(title: "New Product", back_url: products_path) %>
<%= ui_form_page(title: "New Product", back_url: products_path, trail: [["Catalog", catalog_path], ["Products", products_path]]) %>Wraps a show/detail page with title and back navigation. Sets content_for signals so the navbar can render mobile header context. On lg screens and wider, where the mobile header is hidden, it shows a link back to back_url at the top of the page's ui_page, so call ui_page on the same page.
Required props
title:(String)
Optional props
back_url:(String) — defaults to the last link of the trail; with noback_url:and no trail, rendering raisesKeystoneUi::MissingBackLinknaming the page, while an empty trail needs noback_url:subtitle:(String)trail:(Array of[label, href]pairs) — the pages above this one; onlgscreens and wider, the back link sits above breadcrumbs ending withtitle. An empty trail marks a nav tab's own page, which shows no back link and no breadcrumbs. When the page passes none, it uses the trail the app supplies throughconfig.trail_supplier
<%= ui_show_page(title: @product.name, back_url: products_path, subtitle: "Details") %>
<%= ui_show_page(title: @product.name, back_url: products_path, trail: [["Catalog", catalog_path], ["Products", products_path]]) %>Set config.trail_supplier to a lambda that receives the view and returns that page's trail. ui_form_page and ui_show_page call it when the page passes no trail:, and a page that passes no back_url: goes back to the trail's last link. Returning nil leaves the page with its own back_url and no breadcrumbs. Returning [] marks the page as a nav tab's own page, which shows no back link and no breadcrumbs.
KeystoneUi.configure do |config|
config.trail_supplier = ->(view) { Breadcrumbs.trail_for(view) }
endShows the pages above the current one as links separated by ›, ending with the current page, which is not linked. Shown on lg screens and wider only, where the mobile header is hidden. Use it on a page that uses neither ui_form_page nor ui_show_page; those two take the same trail through trail:.
Required props
trail:(Array of[label, href]pairs)
Optional props
current:(String) — the current page, shown last
<%= ui_breadcrumbs(trail: [["Catalog", catalog_path]], current: "Products") %>Renders a settings row link with label and chevron icon.
Required props
label:(String)href:(String)
<%= ui_settings_link(label: "Account", href: account_settings_path) %>Cutting a new version to RubyGems.org is documented in RELEASING.md.