Skip to content

Commit

Permalink
Merge pull request #29 from JD557/radio-buttons
Browse files Browse the repository at this point in the history
Add radio buttons
  • Loading branch information
JD557 committed Jul 23, 2023
2 parents bf4a173 + 3d8f78f commit b7aa576
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ To know more about the library and how to get started check the [examples](https
- Text
- Buttons
- Checkboxes
- Radio Buttons
- Sliders
- Text Input
- Movable components (including windows)
Expand Down
21 changes: 21 additions & 0 deletions core/src/main/scala/eu/joaocosta/interim/api/Components.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,27 @@ trait Components:
if (itemStatus.hot && itemStatus.active && summon[InputState].mouseDown == false) Ref.modify(value, v => !v)
else Ref.get(value)

/** Radio button component. Returns value currently selected.
*
* @param buttonIndex the index of this button (value that this button returns when selected)
* @param label text label to show on this button
*/
final def radioButton(
id: ItemId,
area: Rect,
buttonIndex: Int,
label: String,
skin: ButtonSkin = ButtonSkin.default()
)(value: Int | Ref[Int]): Component[Int] =
val buttonArea = skin.buttonArea(area)
val itemStatus = UiState.registerItem(id, buttonArea)
val newValue =
if (itemStatus.hot && itemStatus.active && summon[InputState].mouseDown == false) Ref.set[Int](value, buttonIndex)
else Ref.get[Int](value)
if (newValue == buttonIndex) skin.renderButton(area, label, itemStatus.copy(hot = true, active = true))
else (skin.renderButton(area, label, itemStatus))
newValue

/** Slider component. Returns the current position of the slider, between min and max.
*
* @param min minimum value for this slider
Expand Down
18 changes: 17 additions & 1 deletion core/src/main/scala/eu/joaocosta/interim/api/Ref.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,24 @@ object Ref {
* The new value is returned. Refs will be mutated while immutable values will not.
*/
inline def modify[T](x: T | Ref[T], f: T => T): T = x match
case value: T => f(value)
case value: T =>
f(value)
case ref: Ref[T] =>
ref.value = f(ref.value)
ref.value

/** Creates a Ref that can be used inside a block and returns that value.
*
* Useful to set temporary mutable variables.
*/
def withRef[T](initialValue: T)(block: Ref[T] => Unit): T =
val ref = Ref(initialValue)
block(ref)
ref.value

/** Wraps this value into a Ref and passes it to a block, returning the final value of the ref.
*
* Useful to set temporary mutable variables.
*/
extension [T](x: T) def asRef(block: Ref[T] => Unit): T = withRef(x)(block)
}

0 comments on commit b7aa576

Please sign in to comment.