Collapsible
An interactive component which expands/collapses a panel.
Usage
Example
CollapsibleTrigger is the button itself. Pass Button options (variant:, size:, icon:) to style it as a Button.
@joeldrapper starred 3 repositories
Collapsible(class: "flex w-[350px] flex-col gap-2") do
div(class: "flex items-center justify-between gap-4 px-4") do
h4(class: "text-sm font-semibold") { "@joeldrapper starred 3 repositories" }
CollapsibleTrigger(variant: :ghost, icon: true, class: "size-8") do
chevrons_icon
span(class: "sr-only") { "Toggle" }
end
end
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex" }
CollapsibleContent(class: "flex flex-col gap-2") do
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex-rails" }
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "ruby-ui/ruby_ui" }
end
end
Open
open: sets the initial state. The server renders it, so the panel shows the right state before any JavaScript runs.
@joeldrapper starred 3 repositories
Collapsible(open: true, class: "flex w-[350px] flex-col gap-2") do
div(class: "flex items-center justify-between gap-4 px-4") do
h4(class: "text-sm font-semibold") { "@joeldrapper starred 3 repositories" }
CollapsibleTrigger(variant: :ghost, icon: true, class: "size-8") do
chevrons_icon
span(class: "sr-only") { "Toggle" }
end
end
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex" }
CollapsibleContent(class: "flex flex-col gap-2") do
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex-rails" }
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "ruby-ui/ruby_ui" }
end
end
Rotating icon
The trigger gets data-panel-open while open, and the root and content get data-open / data-closed, so you can style by state.
Collapsible(class: "w-[350px]") do
CollapsibleTrigger(variant: :ghost, class: "group w-full justify-start") do
chevron_right_icon
plain "Order details"
end
CollapsibleContent(class: "px-2 pt-2 text-sm text-muted-foreground") do
"Shipped on November 2 via express delivery."
end
end
Disabled
Collapsible(disabled: true, class: "w-[350px]") do
CollapsibleTrigger(variant: :outline) { "Show details" }
CollapsibleContent(class: "pt-2 text-sm") { "You can't see this." }
end
Animated
The panel exposes --collapsible-panel-height and gets data-starting-style while opening and data-ending-style while closing; it is hidden once its animation ends.
Collapsible(class: "w-[350px]") do
CollapsibleTrigger(variant: :outline) { "Show recovery keys" }
CollapsibleContent(class: "h-(--collapsible-panel-height) overflow-hidden transition-[height] duration-200 ease-out data-starting-style:h-0 data-ending-style:h-0") do
div(class: "flex flex-col gap-2 pt-2 font-mono text-sm") do
div(class: "rounded-md border px-4 py-2") { "alien-bean-pasta" }
div(class: "rounded-md border px-4 py-2") { "wild-tiger-moon" }
end
end
end
Find in page
With hidden_until_found: true the browser's find in page can reach the hidden text and opens the panel. Try searching for “rubyists”.
A community of rubyists who love Phlex.
Collapsible(class: "w-[350px]") do
CollapsibleTrigger(variant: :outline) { "Who maintains RubyUI?" }
CollapsibleContent(hidden_until_found: true) do
p(class: "pt-2 text-sm") { "A community of rubyists who love Phlex." }
end
end
Events
Each toggle dispatches ruby-ui--collapsible:change with detail: {open} before the state changes. Call preventDefault() to keep the current state. To open or close from your own code, set the data-ruby-ui--collapsible-open-value attribute on the root.
Installation
Using RubyUI CLI
Run the install command
rails g ruby_ui:component Collapsible
Manual installation
1
Add RubyUI::Collapsible to app/components/ruby_ui/collapsible/collapsible.rb
# frozen_string_literal: true
require "securerandom"
module RubyUI
# A panel that expands and collapses, after shadcn's Collapsible (Base UI).
#
# open: is the initial state (shadcn's defaultOpen). The server renders the
# matching state, so a closed panel is hidden before any JS runs. From the
# outside, change the ruby-ui--collapsible open value to open or close it.
#
# Every toggle dispatches a cancelable ruby-ui--collapsible:change event
# (detail: {open}) before the state changes, like onOpenChange; call
# preventDefault() on it to keep the current state.
#
# disabled: true blocks toggling and disables the trigger.
class Collapsible < Base
def initialize(open: false, disabled: false, **attrs)
@open = open
@disabled = disabled
@content_id = "collapsible-content-#{SecureRandom.hex(4)}"
super(**attrs)
end
def view_template(&)
previous = context[:ruby_ui_collapsible]
context[:ruby_ui_collapsible] = {open: @open, disabled: @disabled, content_id: @content_id}
div(**attrs, &)
ensure
context[:ruby_ui_collapsible] = previous
end
private
def default_attrs
{
data: {
slot: "collapsible",
controller: "ruby-ui--collapsible",
ruby_ui__collapsible_open_value: @open ? "true" : "false",
ruby_ui__collapsible_disabled_value: @disabled ? "true" : "false",
open: @open || nil,
closed: !@open || nil,
disabled: @disabled || nil
}
}
end
end
end
2
Add RubyUI::CollapsibleContent to app/components/ruby_ui/collapsible/collapsible_content.rb
# frozen_string_literal: true
module RubyUI
# The panel of a Collapsible, after shadcn's CollapsibleContent. It stays in
# the DOM when closed (hidden attribute), so form fields inside it keep their
# values and still submit. A custom id: is picked up by the trigger's
# aria-controls once the controller connects; the server HTML points to the
# generated id.
#
# hidden_until_found: true renders hidden="until-found": the browser's
# find-in-page (and #:~:text= links) can reach the text and open the panel.
# A hidden="until-found" panel keeps its padding and border, so put those on
# an inner element.
#
# Animation hooks, as in Base UI: --collapsible-panel-height and
# --collapsible-panel-width hold the panel size, data-starting-style is set
# while opening starts and data-ending-style while closing; the panel is
# hidden once its animations finish. For example:
# class: "h-(--collapsible-panel-height) overflow-hidden transition-[height] duration-200
# data-starting-style:h-0 data-ending-style:h-0"
class CollapsibleContent < Base
def initialize(hidden_until_found: false, **attrs)
@hidden_until_found = hidden_until_found
super(**attrs)
end
def view_template(&)
state = context[:ruby_ui_collapsible] || {}
content_attrs = attrs.dup
content_attrs[:id] ||= state[:content_id]
content_attrs[:data] = content_attrs[:data].merge(open: state[:open] || nil, closed: !state[:open] || nil)
content_attrs[:hidden] = (@hidden_until_found ? "until-found" : true) unless state[:open]
div(**content_attrs, &)
end
private
def default_attrs
{
data: {
slot: "collapsible-content",
ruby_ui__collapsible_target: "content",
hidden_until_found: @hidden_until_found || nil
}
}
end
end
end
3
Add RubyUI::CollapsibleDocs to app/components/ruby_ui/collapsible/collapsible_docs.rb
# frozen_string_literal: true
class Views::Docs::Collapsible < Views::Base
def view_template
component = "Collapsible"
div(class: "max-w-2xl mx-auto w-full py-10 space-y-10") do
render Docs::Header.new(title: "Collapsible", description: "An interactive component which expands/collapses a panel.")
Heading(level: 2) { "Usage" }
render Docs::VisualCodeExample.new(title: "Example", description: "CollapsibleTrigger is the button itself. Pass Button options (variant:, size:, icon:) to style it as a Button.", context: self) do
<<~RUBY
Collapsible(class: "flex w-[350px] flex-col gap-2") do
div(class: "flex items-center justify-between gap-4 px-4") do
h4(class: "text-sm font-semibold") { "@joeldrapper starred 3 repositories" }
CollapsibleTrigger(variant: :ghost, icon: true, class: "size-8") do
chevrons_icon
span(class: "sr-only") { "Toggle" }
end
end
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex" }
CollapsibleContent(class: "flex flex-col gap-2") do
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex-rails" }
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "ruby-ui/ruby_ui" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Open", description: "open: sets the initial state. The server renders it, so the panel shows the right state before any JavaScript runs.", context: self) do
<<~RUBY
Collapsible(open: true, class: "flex w-[350px] flex-col gap-2") do
div(class: "flex items-center justify-between gap-4 px-4") do
h4(class: "text-sm font-semibold") { "@joeldrapper starred 3 repositories" }
CollapsibleTrigger(variant: :ghost, icon: true, class: "size-8") do
chevrons_icon
span(class: "sr-only") { "Toggle" }
end
end
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex" }
CollapsibleContent(class: "flex flex-col gap-2") do
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "phlex-ruby/phlex-rails" }
div(class: "rounded-md border px-4 py-2 font-mono text-sm") { "ruby-ui/ruby_ui" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Rotating icon", description: "The trigger gets data-panel-open while open, and the root and content get data-open / data-closed, so you can style by state.", context: self) do
<<~RUBY
Collapsible(class: "w-[350px]") do
CollapsibleTrigger(variant: :ghost, class: "group w-full justify-start") do
chevron_right_icon
plain "Order details"
end
CollapsibleContent(class: "px-2 pt-2 text-sm text-muted-foreground") do
"Shipped on November 2 via express delivery."
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Disabled", context: self) do
<<~RUBY
Collapsible(disabled: true, class: "w-[350px]") do
CollapsibleTrigger(variant: :outline) { "Show details" }
CollapsibleContent(class: "pt-2 text-sm") { "You can't see this." }
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Animated", description: "The panel exposes --collapsible-panel-height and gets data-starting-style while opening and data-ending-style while closing; it is hidden once its animation ends.", context: self) do
<<~RUBY
Collapsible(class: "w-[350px]") do
CollapsibleTrigger(variant: :outline) { "Show recovery keys" }
CollapsibleContent(class: "h-(--collapsible-panel-height) overflow-hidden transition-[height] duration-200 ease-out data-starting-style:h-0 data-ending-style:h-0") do
div(class: "flex flex-col gap-2 pt-2 font-mono text-sm") do
div(class: "rounded-md border px-4 py-2") { "alien-bean-pasta" }
div(class: "rounded-md border px-4 py-2") { "wild-tiger-moon" }
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Find in page", description: "With hidden_until_found: true the browser's find in page can reach the hidden text and opens the panel. Try searching for “rubyists”.", context: self) do
<<~RUBY
Collapsible(class: "w-[350px]") do
CollapsibleTrigger(variant: :outline) { "Who maintains RubyUI?" }
CollapsibleContent(hidden_until_found: true) do
p(class: "pt-2 text-sm") { "A community of rubyists who love Phlex." }
end
end
RUBY
end
Heading(level: 2) { "Events" }
Text do
plain "Each toggle dispatches "
InlineCode { "ruby-ui--collapsible:change" }
plain " with "
InlineCode { "detail: {open}" }
plain " before the state changes. Call "
InlineCode { "preventDefault()" }
plain " to keep the current state. To open or close from your own code, set the "
InlineCode { "data-ruby-ui--collapsible-open-value" }
plain " attribute on the root."
end
render Components::ComponentSetup::Tabs.new(component_name: component)
render Docs::ComponentsTable.new(component_files(component))
end
end
private
def chevrons_icon
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round"
) do |s|
s.path(d: "m7 15 5 5 5-5")
s.path(d: "m7 9 5-5 5 5")
end
end
def chevron_right_icon
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round",
class: "transition-transform group-data-panel-open:rotate-90"
) do |s|
s.path(d: "m9 18 6-6-6-6")
end
end
end
4
Add RubyUI::CollapsibleTrigger to app/components/ruby_ui/collapsible/collapsible_trigger.rb
# frozen_string_literal: true
module RubyUI
# The button that toggles its Collapsible. It is the <button> itself, with
# aria-expanded and aria-controls, like shadcn's CollapsibleTrigger.
#
# Unstyled by default. Pass any Button option (variant:, size:, icon:) to
# render it as a RubyUI Button (ghost unless variant: says otherwise), the
# counterpart of shadcn's render={<Button variant="ghost" />}.
class CollapsibleTrigger < Base
def initialize(variant: nil, size: nil, icon: false, **attrs)
@variant = variant
@size = size
@icon = icon
super(**attrs)
end
def view_template(&)
state = context[:ruby_ui_collapsible] || {}
trigger_attrs = mix(attrs, state_attrs(state))
# Always take disabled out of the attrs, so it can't override the
# collapsible's own disabled state. The marker tells the controller this
# trigger is disabled on its own, not because of the collapsible.
own_disabled = trigger_attrs.delete(:disabled) ? true : false
disabled = state[:disabled] || own_disabled
trigger_attrs[:data][:ruby_ui__collapsible_own_disabled] = true if own_disabled
if @variant || @size || @icon
# The trigger is always a <button>: no Button links.
trigger_attrs.delete(:href)
button = RubyUI::Button.new(variant: @variant || :ghost, size: @size || :md, icon: @icon,
disabled: disabled, **trigger_attrs)
# Button sets its own data-slot; mix would join the two.
button.attrs[:data][:slot] = "collapsible-trigger"
render(button, &)
else
trigger_attrs[:disabled] = true if disabled
button(**trigger_attrs, &)
end
end
private
def state_attrs(state)
{
aria: {expanded: (state[:open] || false).to_s, controls: state[:content_id]},
data: {panel_open: state[:open] || nil, disabled: state[:disabled] || nil}
}
end
def default_attrs
{
type: :button,
data: {
slot: "collapsible-trigger",
ruby_ui__collapsible_target: "trigger",
action: "click->ruby-ui--collapsible#toggle"
}
}
end
end
end
5
Add collapsible_controller.js to app/javascript/controllers/ruby_ui/collapsible_controller.js
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="ruby-ui--collapsible"
//
// The server renders the initial state (hidden, aria-expanded, data-open /
// data-closed), so connect() only syncs it. Each toggle dispatches a cancelable
// ruby-ui--collapsible:change event before the state changes. Changing the
// open value from outside opens or closes without the event.
export default class extends Controller {
static targets = ["trigger", "content"]
static values = {
open: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
}
initialize() {
this.ownDisabled = new WeakMap()
this.focusableWhenDisabled = new WeakMap()
}
connect() {
this.sync()
this.ready = true
}
disconnect() {
this.ready = false
this.transition = null
}
// Target callbacks run before connect() and again whenever Turbo or other
// code swaps a trigger or the content inside a connected collapsible.
triggerTargetConnected(trigger) {
// A trigger rendered with its own disabled: keeps it. The server marks it,
// since a disabled collapsible disables every trigger too.
const own = trigger.hasAttribute("data-ruby-ui--collapsible-own-disabled") || (trigger.disabled && !this.disabledValue)
this.ownDisabled.set(trigger, own)
// Button's focusable_when_disabled: disabled through aria-disabled.
this.focusableWhenDisabled.set(trigger, trigger.hasAttribute("aria-disabled"))
if (this.ready) this.syncAttributes()
}
contentTargetConnected(content) {
content.addEventListener("beforematch", this.handleBeforeMatch)
if (this.ready) this.sync()
}
contentTargetDisconnected(content) {
content.removeEventListener("beforematch", this.handleBeforeMatch)
if (this.ready) this.syncAttributes()
}
toggle() {
if (this.disabledValue) return
this.requestOpen(!this.openValue)
}
// Find-in-page reached the text inside a hidden="until-found" panel. The
// browser removes hidden right after this event, so a canceled open puts it
// back on the next frame.
handleBeforeMatch = (event) => {
if (this.openValue) return
if (this.requestOpen(true)) return
const content = event.currentTarget
requestAnimationFrame(() => {
if (!this.openValue) this.hideContent(content)
})
}
requestOpen(open) {
const event = this.dispatch("change", { detail: { open }, cancelable: true })
if (event.defaultPrevented) return false
this.openValue = open
return true
}
openValueChanged() {
if (!this.ready) return
this.openValue ? this.animateOpen() : this.animateClose()
}
disabledValueChanged() {
if (!this.ready) return
this.syncAttributes()
}
// Current state with no animation; also drops a transition a reconnect cut
// short.
sync() {
this.transition = null
this.syncAttributes()
this.contentTargets.forEach((content) => {
content.removeAttribute("data-starting-style")
content.removeAttribute("data-ending-style")
if (this.openValue) {
content.hidden = false
this.setSize(content, "auto")
} else {
this.hideContent(content)
}
})
}
syncAttributes() {
const open = this.openValue
this.toggleAttribute(this.element, "data-open", open)
this.toggleAttribute(this.element, "data-closed", !open)
this.toggleAttribute(this.element, "data-disabled", this.disabledValue)
const controls = this.contentTargets.map((content) => content.id).filter(Boolean).join(" ")
this.triggerTargets.forEach((trigger) => {
trigger.setAttribute("aria-expanded", String(open))
if (controls) trigger.setAttribute("aria-controls", controls)
else trigger.removeAttribute("aria-controls")
this.toggleAttribute(trigger, "data-panel-open", open)
this.toggleAttribute(trigger, "data-disabled", this.disabledValue)
const disabled = this.disabledValue || this.ownDisabled.get(trigger) === true
if (this.focusableWhenDisabled.get(trigger)) trigger.setAttribute("aria-disabled", String(disabled))
else if (trigger.tagName === "BUTTON") trigger.disabled = disabled
})
this.contentTargets.forEach((content) => {
this.toggleAttribute(content, "data-open", open)
this.toggleAttribute(content, "data-closed", !open)
})
}
animateOpen() {
const transition = (this.transition = {})
this.syncAttributes()
this.contentTargets.forEach((content) => {
content.removeAttribute("data-ending-style")
content.hidden = false
this.setSize(content, `${content.scrollHeight}px`, `${content.scrollWidth}px`)
content.setAttribute("data-starting-style", "")
requestAnimationFrame(() => {
if (this.transition !== transition) return
content.removeAttribute("data-starting-style")
this.afterAnimations(content, () => {
if (this.transition === transition) this.setSize(content, "auto")
})
})
})
}
animateClose() {
const transition = (this.transition = {})
this.syncAttributes()
this.contentTargets.forEach((content) => {
content.removeAttribute("data-starting-style")
this.setSize(content, `${content.scrollHeight}px`, `${content.scrollWidth}px`)
requestAnimationFrame(() => {
if (this.transition !== transition) return
content.setAttribute("data-ending-style", "")
this.afterAnimations(content, () => {
if (this.transition !== transition) return
content.removeAttribute("data-ending-style")
this.hideContent(content)
})
})
})
}
// Runs callback once the finite animations and transitions the current
// styles started have finished (at once when there are none). Infinite ones,
// like animate-pulse, never finish, so they don't hold the panel open.
afterAnimations(element, callback) {
requestAnimationFrame(() => {
const animations = typeof element.getAnimations === "function" ? element.getAnimations() : []
const finite = animations.filter((animation) => animation.effect?.getComputedTiming().endTime !== Infinity)
Promise.allSettled(finite.map((animation) => animation.finished)).then(callback)
})
}
hideContent(content) {
if (content.hasAttribute("data-hidden-until-found")) content.setAttribute("hidden", "until-found")
else content.hidden = true
this.setSize(content, "0px")
}
setSize(content, height, width = height) {
content.style.setProperty("--collapsible-panel-height", height)
content.style.setProperty("--collapsible-panel-width", width)
}
toggleAttribute(element, name, on) {
if (on) element.setAttribute(name, "")
else element.removeAttribute(name)
}
}
6
Update the Stimulus controllers manifest file
rake stimulus:manifest:update7
Install required components
Component Collapsible relies on the following RubyUI components. Refer to their individual installation guides for setup instructions:
Components
| Component | Built using | Source |
|---|---|---|
Collapsible | Phlex | |
CollapsibleContent | Phlex | |
CollapsibleDocs | Phlex | |
CollapsibleTrigger | Phlex | |
CollapsibleController | Stimulus JS |