Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Ref operations #36

Merged
merged 1 commit into from
Aug 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions core/src/main/scala/eu/joaocosta/interim/ItemId.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package eu.joaocosta.interim

import scala.annotation.alpha
import scala.annotation.targetName

/** Identifier of an item. Should be unique for each item.
*
Expand All @@ -22,6 +22,6 @@ object ItemId:
/** Operator to add a child to an item id. Useful for composite components.
*/
extension (parentId: ItemId)
@alpha("addChild")
@targetName("addChild")
def |>(childId: ItemId): ItemId =
parentId.toIdList ++ childId.toIdList
37 changes: 18 additions & 19 deletions core/src/main/scala/eu/joaocosta/interim/api/Components.scala
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ trait Components:
def applyRef(value: Ref[Boolean]): Component[Boolean] =
val checkboxArea = skin.checkboxArea(area)
val itemStatus = UiState.registerItem(id, checkboxArea)
skin.renderCheckbox(area, Ref.get[Boolean](value), itemStatus)
skin.renderCheckbox(area, value.get, itemStatus)
if (itemStatus.hot && itemStatus.active && summon[InputState].mouseDown == false)
Ref.modify[Boolean](value, v => !v)
else Ref.get(value)
value.modify(!_).get
else value.get

/** Radio button component. Returns value currently selected.
*
Expand All @@ -65,13 +65,11 @@ trait Components:
def applyRef(value: Ref[T]): Component[T] =
val buttonArea = skin.buttonArea(area)
val itemStatus = UiState.registerItem(id, buttonArea)
val newValue =
if (itemStatus.hot && itemStatus.active && summon[InputState].mouseDown == false)
Ref.set[T](value, buttonValue)
else Ref.get[T](value)
if (newValue == buttonValue) skin.renderButton(area, label, itemStatus.copy(hot = true, active = true))
if (itemStatus.hot && itemStatus.active && summon[InputState].mouseDown == false)
value := buttonValue
if (value.get == buttonValue) skin.renderButton(area, label, itemStatus.copy(hot = true, active = true))
else (skin.renderButton(area, label, itemStatus))
newValue
value.get

/** Slider component. Returns the current position of the slider, between min and max.
*
Expand All @@ -91,18 +89,18 @@ trait Components:
val sliderSize = skin.sliderSize(area, min, max)
val range = max - min
val itemStatus = UiState.registerItem(id, sliderArea)
val clampedValue = math.max(min, math.min(Ref.get[Int](value), max))
val clampedValue = math.max(min, math.min(value.get, max))
skin.renderSlider(area, min, clampedValue, max, itemStatus)
if (itemStatus.active)
if (area.w > area.h)
val mousePos = summon[InputState].mouseX - sliderArea.x - sliderSize / 2
val maxPos = sliderArea.w - sliderSize
Ref.set(value, math.max(min, math.min(min + (mousePos * range) / maxPos, max)))
value := math.max(min, math.min(min + (mousePos * range) / maxPos, max))
else
val mousePos = summon[InputState].mouseY - sliderArea.y - sliderSize / 2
val maxPos = sliderArea.h - sliderSize
Ref.set(value, math.max(min, math.min((mousePos * range) / maxPos, max)))
else Ref.get(value)
value := math.max(min, math.min((mousePos * range) / maxPos, max))
value.get

/** Text input component. Returns the current string inputed.
*/
Expand All @@ -115,9 +113,10 @@ trait Components:
def applyRef(value: Ref[String]): Component[String] =
val textInputArea = skin.textInputArea(area)
val itemStatus = UiState.registerItem(id, textInputArea)
skin.renderTextInput(area, Ref.get(value), itemStatus)
if (itemStatus.keyboardFocus) Ref.modify(value, summon[InputState].appendKeyboardInput)
else Ref.get(value)
skin.renderTextInput(area, value.get, itemStatus)
if (itemStatus.keyboardFocus)
value.modify(summon[InputState].appendKeyboardInput)
value.get

/** Draggable handle. Returns the moved area.
*
Expand All @@ -131,13 +130,13 @@ trait Components:
def applyRef(value: Ref[Rect]): Component[Rect] =
val handleArea = skin.handleArea(area)
val itemStatus = UiState.registerItem(id, handleArea)
skin.renderHandle(area, Ref.get(value), itemStatus)
skin.renderHandle(area, value.get, itemStatus)
if (itemStatus.active)
val handleCenterX = handleArea.x + handleArea.w / 2
val handleCenterY = handleArea.y + handleArea.h / 2
val mouseX = summon[InputState].mouseX
val mouseY = summon[InputState].mouseY
val deltaX = mouseX - handleCenterX
val deltaY = mouseY - handleCenterY
Ref.modify(value, _.move(deltaX, deltaY))
else Ref.get(value)
value.modify(_.move(deltaX, deltaY))
value.get
28 changes: 15 additions & 13 deletions core/src/main/scala/eu/joaocosta/interim/api/Panels.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ trait Panels:
* @param title of this window
* @param movable if true, the window will include a move handle in the title bar
*/
final inline def window[T](
final def window[T](
id: ItemId,
area: Rect | Ref[Rect],
title: String,
Expand All @@ -38,15 +38,17 @@ trait Panels:
)(
body: Rect => T
): Components.Component[(T, Rect)] =
val oldArea: Rect = Ref.get(area)
skin.renderWindow(oldArea, title)
val nextArea: Rect =
if (movable)
Components
.moveHandle(
id |> "internal_move_handle",
skin.titleTextArea(oldArea),
handleSkin
)(area)
else oldArea
(body(skin.panelArea(oldArea)), nextArea)
val areaRef = area match {
case ref: Ref[Rect] => ref
case v: Rect => Ref(v)
}
skin.renderWindow(areaRef.get, title)
val res = body(skin.panelArea(areaRef.get))
if (movable)
Components
.moveHandle(
id |> "internal_move_handle",
skin.titleTextArea(areaRef.get),
handleSkin
)(areaRef)
(res, areaRef.get)
36 changes: 12 additions & 24 deletions core/src/main/scala/eu/joaocosta/interim/api/Ref.scala
Original file line number Diff line number Diff line change
@@ -1,44 +1,32 @@
package eu.joaocosta.interim.api

import scala.annotation.targetName
import scala.deriving.Mirror

/** A mutable reference to a variable.
*
* When a function receives a Ref as an argument, it will probably mutate it.
*/
final case class Ref[T](var value: T):
final case class Ref[T](private var value: T):
/** Returns the value of this Ref.
*/
def get: T = value

/** Assigns a value to this Ref.
* Shorthand for `ref.value = x`
*/
@targetName("set")
def :=(newValue: T): this.type =
value = newValue
this

object Ref:

/** Gets a value from a Ref or from a plain value.
*/
inline def get[T](x: T | Ref[T]): T = inline x match
case value: T => value
case ref: Ref[T] => ref.value

/** Sets a value from a Ref or from a plain value.
*
* The new value is returned. Refs will be mutated while immutable values will not.
/** Modifies the value pf this Ref.
* Shorthand for `ref := f(ref.value)`
*/
inline def set[T](x: T | Ref[T], v: T): T = modify(x, _ => v)
def modify(f: T => T): this.type =
value = f(value)
this

/** Modifies a value from a Ref or from a plain value.
*
* 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 = inline x match
case value: T =>
f(value)
case ref: Ref[T] =>
ref.value = f(ref.value)
ref.value
object Ref:

/** Creates a Ref that can be used inside a block and returns that value.
*
Expand Down
35 changes: 8 additions & 27 deletions core/src/test/scala/eu/joaocosta/interim/api/RefSpec.scala
Original file line number Diff line number Diff line change
@@ -1,40 +1,21 @@
package eu.joaocosta.interim.api

class RefSpec extends munit.FunSuite:
test("A Ref value can be correctly set and retrieved with := and value"):
test("A Ref value can be correctly set and retrieved with := and get"):
val x = Ref(1)
assertEquals(x.value, 1)
assertEquals(x.get, 1)
x := 2
assertEquals(x.value, 2)
x.value = 3
assertEquals(x.value, 3)
assertEquals(x.get, 2)

test("Ref values and raw values can be fetched with Ref.get"):
test("Ref values can be modified with modify"):
val x = Ref(1)
val y = 1
assertEquals(Ref.get[Int](x), Ref.get[Int](y))

test("Ref values and raw values can be set with Ref.set"):
val x = Ref(1)
val y = 1

assertEquals(Ref.set[Int](x, 2), 2)
assertEquals(Ref.set[Int](y, 2), 2)
assertEquals(x.value, 2)
assertEquals(y, 1)

test("Ref values and raw values can be modified with Ref.modify"):
val x = Ref(1)
val y = 1

assertEquals(Ref.modify[Int](x, _ + 1), 2)
assertEquals(Ref.modify[Int](y, _ + 1), 2)
assertEquals(x.value, 2)
assertEquals(y, 1)
assertEquals(x.modify(_ + 1).get, 2)
assertEquals(x.get, 2)

test("withRef allows to use a temporary Ref value"):
val result = Ref.withRef(0) { ref =>
Ref.modify[Int](ref, _ + 2)
ref.modify(_ + 2)
}
assertEquals(result, 2)

Expand All @@ -51,7 +32,7 @@ class RefSpec extends munit.FunSuite:
test("asRef allows to use a temporary Ref value"):
import Ref.asRef
val result = 0.asRef { ref =>
Ref.modify[Int](ref, _ + 2)
ref.modify(_ + 2)
}
assertEquals(result, 2)

Expand Down
6 changes: 3 additions & 3 deletions examples/snapshot/4-refs.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,17 @@ def applicationRef(inputState: InputState, appState: AppState) =
window(id = "window", area = windowArea, title = "My Counter", movable = true) { area =>
columns(area = area.shrink(5), numColumns = 3, padding = 10) { column =>
if (button(id = "minus", area = column(0), label = "-"))
counter := counter.value - 1 // Counter is a Ref, so we need to use :=
counter := counter.get - 1 // Counter is a Ref, so we need to use :=
text(
area = column(1),
color = Color(0, 0, 0),
text = counter.value.toString, // Counter is a Ref, so we need to use .value
text = counter.get.toString, // Counter is a Ref, so we need to use .get
fontSize = 8,
horizontalAlignment = centerHorizontally,
verticalAlignment = centerVertically
)
if (button(id = "plus", area = column(2), label = "+"))
counter := counter.value + 1 // Counter is a Ref, so we need to use :=
counter := counter.get + 1 // Counter is a Ref, so we need to use :=
}
}
}
Expand Down
18 changes: 9 additions & 9 deletions examples/snapshot/5-colorpicker.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,22 +79,22 @@ def application(inputState: InputState, appState: AppState) =
window(id = "color picker", area = colorPickerArea, title = "Color Picker", movable = true) {
area =>
rows(area = area.shrink(5), numRows = 5, padding = 10) { row =>
rectangle(row(0), color.value)
text(row(1), textColor, color.value.toString, 8, verticalAlignment = centerVertically)
val r = slider("red slider", row(2), min = 0, max = 255)(color.value.r)
val g = slider("green slider", row(3), min = 0, max = 255)(color.value.g)
val b = slider("blue slider", row(4), min = 0, max = 255)(color.value.b)
rectangle(row(0), color.get)
text(row(1), textColor, color.get.toString, 8, verticalAlignment = centerVertically)
val r = slider("red slider", row(2), min = 0, max = 255)(color.get.r)
val g = slider("green slider", row(3), min = 0, max = 255)(color.get.g)
val b = slider("blue slider", row(4), min = 0, max = 255)(color.get.b)
color := Color(r, g, b)
}
}

window(id = "color search", area = colorSearchArea, title = "Color Search", movable = true) {
area =>
dynamicRows(area = area.shrink(5), padding = 10) { newRow =>
val oldQuery = query.value
val oldQuery = query.get
textInput("query", newRow(16))(query)
if (query.value != oldQuery) resultDelta := 0
val results = htmlColors.filter(_._1.toLowerCase.startsWith(query.value.toLowerCase))
if (query.get != oldQuery) resultDelta := 0
val results = htmlColors.filter(_._1.toLowerCase.startsWith(query.get.toLowerCase))
val resultsArea = newRow(maxSize)
val buttonSize = 32
dynamicColumns(area = resultsArea, padding = 10) { newColumn =>
Expand All @@ -103,7 +103,7 @@ def application(inputState: InputState, appState: AppState) =
slider("result scroller", newColumn(-16), min = 0, max = resultsHeight - resultsArea.h)(resultDelta)
val clipArea = newColumn(maxSize)
clip(area = clipArea) {
rows(area = clipArea.copy(y = clipArea.y - resultDelta.value, h = resultsHeight), numRows = results.size, padding = 10) { rows =>
rows(area = clipArea.copy(y = clipArea.y - resultDelta.get, h = resultsHeight), numRows = results.size, padding = 10) { rows =>
results.zip(rows).foreach { case ((colorName, colorValue), row) =>
if (button(s"$colorName button", row, colorName))
color := colorValue
Expand Down
Loading