zui docs v0.0.5
GitHub ↗
Zui guide · 02

State and bindings

Model reactive application state and update only the native properties that changed.

Updated for Zui 0.0.5·2 minutes read

State belongs to Ruby

Declare state inside the application definition. Read it from binding blocks; changing a value schedules the smallest valid native patch.

require "zui"

Zui.app do
  state :status, "Ready"
  state :progress, 0

  app :main, title: "Build monitor", width: 640, height: 420 do
    column spacing: 16 do
      label { state.status }

      progress_bar = progress state.progress, minimum: 0, maximum: 100
      bind(progress_bar, :value) { state.progress }

      button "Start" do
        transaction do
          state.status = "Working"
          state.progress = 12
        end
      end
    end
  end
end

Bind any registered property

Convenience helpers bind their primary value, while bind connects any registered property to a Ruby reader.

require "zui"

Zui.app do
  state :panel_visible, true

  app :main, title: "Animated binding", width: 640, height: 420 do
    column spacing: 16 do
      panel = card padding: 24 do
        label "Bound panel"
      end

      bind panel, :opacity, animation: animation(duration: 240) do
        state.panel_visible ? 1.0 : 0.0
      end

      button "Toggle panel" do
        state.panel_visible = !state.panel_visible
      end
    end
  end
end

Render collections with ordinary Ruby

Container blocks accept normal Ruby iteration when building a collection. Keep item identity in ordinary Ruby data and use state for values that change after rendering.

require "zui"

devices = [
  { id: "display", name: "Studio Display" },
  { id: "headphones", name: "USB Headphones" }
]

Zui.app do
  state :selected_id, devices.first.fetch(:id)

  app :main, title: "Devices", width: 640, height: 420 do
    column spacing: 8 do
      devices.each do |device|
        button device.fetch(:name) do
          state.selected_id = device.fetch(:id)
        end
      end

      text { "Selected: #{state.selected_id}" }
    end
  end
end