Skip to content
Open
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
7 changes: 6 additions & 1 deletion base/numberinput.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,12 @@ func (c *numberCtl) fit(v float64) float64 {
if lo != nil {
from = *lo
}
scale := math.Pow(10, float64(decimals(step)))
digits := decimals(step)
if c.n.Precision != 0 {
// An explicit grid can have an origin finer than its spacing.
digits = max(digits, decimals(from))
}
scale := math.Pow(10, float64(digits))
v = math.Round((from+math.Round((v-from)/step)*step)*scale) / scale
}
return clampTo(v, lo, hi)
Expand Down
3 changes: 3 additions & 0 deletions changelog.d/numberinput-typed-precision.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Let `ui.NumberInput` accept and display typed values independently of the increment size (#2263 by @J4ck1e2000).
14 changes: 9 additions & 5 deletions docs/public/en/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,19 @@ ui.Select[string]{
}
```

`ui.NumberInput` and `base.NumberInput` accept `LabelFunc` for a changing accessible name. A custom `Format` follows the signals it reads while the field is not being edited; a language switch preserves the active draft until editing ends. `ui.NumberInput` steps and scrubs a number with bounds, `ui.DatePicker` and `ui.TimeField` edit dates and times, `ui.ColorPicker` edits a color, and `ui.TagInput` edits a list of tags.

`ui.OtpInput` takes a one-time code in cells. It and `base.OtpInput` accept `LabelFunc` without replacing the focused field or its code. `Size` sets the default height and width, 36 points on desktops and TVs and 44 on touch devices. `CellWidth` and `CellHeight` override either dimension independently. `TextStyle` overrides the cell typography, `CornerRadius` changes its corners, and `CaretHeight` overrides the height derived from the line height.
`ui.NumberInput` uses `Step` for buttons, arrow keys and scrubbing. When a typed value is committed, it rounds to `Precision` from `Min`; zero `Precision` uses `Step`. Set `NoSnap: true` to clamp typed values to `Min` and `Max` without rounding. The default `Format` shows the rounding grid's decimal places, or the shortest round-trip decimal with `NoSnap`.

```go
quantity := core.NewSignal(cx, 1.0)
ui.NumberInput{Value: quantity.Get, OnChange: quantity.Set, Min: 1, Max: 99, Step: 1, Label: "Quantity"}
gravity := core.NewSignal(cx, 9.81)
ui.NumberInput{Value: gravity.Get, OnChange: gravity.Set, Min: 0, Max: 100, Step: 0.1, Precision: 0.01, Label: "Gravity"}
```

`ui.NumberInput` and `base.NumberInput` accept `LabelFunc` for a changing accessible name. A custom `Format` follows the signals it reads while the field is not being edited; a language switch preserves the active draft until editing ends.

`ui.DatePicker` and `ui.TimeField` edit dates and times, `ui.ColorPicker` edits a color, and `ui.TagInput` edits a list of tags.

`ui.OtpInput` takes a one-time code in cells. It and `base.OtpInput` accept `LabelFunc` without replacing the focused field or its code. `Size` sets the default height and width, 36 points on desktops and TVs and 44 on touch devices. `CellWidth` and `CellHeight` override either dimension independently. `TextStyle` overrides the cell typography, `CornerRadius` changes its corners, and `CaretHeight` overrides the height derived from the line height.

## Grouped rows

`ui.FormSection` puts its rows on a card, with the title above and footer below. Set `CardStyle` for the card’s background, border or corners. `CardStyleFunc` merges over it and follows the signals it reads. `DividerInset` receives each child row, including rows made by `core.Each`: return an inset and `true` to override its divider, or `false` to keep automatic title alignment (12 points for other nodes). An inset of zero makes a full-width divider.
Expand Down
14 changes: 8 additions & 6 deletions docs/public/zh/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,18 @@ ui.Select[string]{
}
```

`ui.NumberInput` 带边界地步进和拖动数字,`ui.DatePicker` 和 `ui.TimeField` 编辑日期和时间,`ui.ColorPicker` 编辑颜色,`ui.TagInput` 编辑一组标签。
`ui.NumberInput` 的按钮、方向键和拖动操作使用 `Step` 步进。输入值提交时,以 `Min` 为起点按 `Precision` 取整;`Precision` 为零时使用 `Step`。设置 `NoSnap: true` 可将输入值限制在 `Min` 和 `Max` 之间而不取整。默认的 `Format` 按取整网格的小数位数显示;启用 `NoSnap` 时,使用能无损读回数值的最短十进制写法。

```go
gravity := core.NewSignal(cx, 9.81)
ui.NumberInput{Value: gravity.Get, OnChange: gravity.Set, Min: 0, Max: 100, Step: 0.1, Precision: 0.01, Label: "重力"}
```

`ui.NumberInput` 和 `base.NumberInput` 的 `LabelFunc` 可更新辅助功能名称。自定义 `Format` 会在字段未编辑时跟随其读取的信号更新;切换语言会保留正在编辑的草稿,直到编辑结束。

`ui.OtpInput` 在格子中输入一次性验证码。它和 `base.OtpInput` 的 `LabelFunc` 可更新名称,同时保留输入焦点和验证码。`Size` 设置格子的默认宽度和高度,在桌面和电视上为 36 点,在触屏设备上为 44 点。`CellWidth` 和 `CellHeight` 可分别覆盖宽度和高度。`TextStyle` 设置格子的文字样式,`CornerRadius` 设置圆角,`CaretHeight` 可覆盖根据行高计算的光标高度。
`ui.DatePicker` 和 `ui.TimeField` 编辑日期和时间,`ui.ColorPicker` 编辑颜色,`ui.TagInput` 编辑一组标签。

```go
quantity := core.NewSignal(cx, 1.0)
ui.NumberInput{Value: quantity.Get, OnChange: quantity.Set, Min: 1, Max: 99, Step: 1, Label: "数量"}
```
`ui.OtpInput` 在格子中输入一次性验证码。它和 `base.OtpInput` 的 `LabelFunc` 可更新名称,同时保留输入焦点和验证码。`Size` 设置格子的默认宽度和高度,在桌面和电视上为 36 点,在触屏设备上为 44 点。`CellWidth` 和 `CellHeight` 可分别覆盖宽度和高度。`TextStyle` 设置格子的文字样式,`CornerRadius` 设置圆角,`CaretHeight` 可覆盖根据行高计算的光标高度。

## 分组行

Expand Down
2 changes: 1 addition & 1 deletion skills/nsgo/references/components.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Use `ui`'s component whenever one exists: it is `base`'s control with NSGo's loo
| --- | --- |
| Box, text, image, icon | `core.View`, `core.Text` with `core.Span` runs, `core.Image`, `core.Icon` with icons from `icons/lucide`; `ui.Textf` for text from a signal in a size, weight and color |
| Buttons | `ui.Button` (`ButtonPrimary`, `ButtonSecondary`, `ButtonOutline`, `ButtonGhost`), `ui.IconButton` with a `Label` for screen readers that also shows as its tooltip (`Tooltip` overrides it), `ui.ToggleButton`, `ui.ToggleGroup`, `ui.HoldToConfirm`, `ui.Link` (`Style.Color` colors its text and hover underline) |
| Text fields | `ui.Input` (controlled with `Value` and `OnChange`, `Multiline`, `Masked`), `ui.NumberInput`, `ui.OtpInput`, `ui.TagInput`, `ui.FormField` for a label and message |
| Text fields | `ui.Input` (controlled with `Value` and `OnChange`, `Multiline`, `Masked`), `ui.NumberInput` (`Step` for increments, `Precision` to round typed values, `NoSnap` to clamp without rounding), `ui.OtpInput`, `ui.TagInput`, `ui.FormField` for a label and message |
| Choices | `ui.Switch`, `ui.Checkbox`, `ui.Radio` in a `ui.RadioGroup`, `ui.Select[T]` with `ui.Option[T]`, `ui.Combobox`, `ui.Slider`, `ui.Rating` |
| Dates, times, colors and emoji | `ui.DatePicker`, `ui.Calendar`, `ui.TimeField`, `ui.ColorPicker`, `ui.EmojiPicker` (`base.EmojiPicker` for custom styling; multi-language search, categories, skin tones; `base.EmojiPickerRef` focuses, reads or sets the query and jumps categories) |
| Scrolling and long data | `ui.ScrollView` or `core.Scroll`; `ui.List` or `core.List` for rows built only in view; `core.NewCollection` behind them |
Expand Down
30 changes: 24 additions & 6 deletions ui/numberinput.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import (
// NumberInput is base.NumberInput in ui's look, with buttons stacked at
// its end on desktops, a minus and a plus on touch screens. What is typed
// is read as the field is left or Return pressed, and kept to the range
// and the step; text that is no number gives the value back. A drag across
// its Leading handle scrubs it.
// and rounded unless NoSnap is set; text that is no number gives the value
// back. A drag across its Leading handle scrubs it.
type NumberInput struct {
// Ref is the field's; LabelledBy and Invalid are a core.Input's.
Ref *core.Ref
Expand All @@ -25,9 +25,16 @@ type NumberInput struct {
// Min and Max are the range, when Max is above Min.
Min, Max float64
// Step is what the buttons, the keys and the scrub change the value
// by, and what it is rounded to from Min; 1 when 0.
// by; 1 when 0.
Step float64
// Format writes the value, with as many decimals as Step has when nil; Parse reads it back, strconv.ParseFloat's when nil. Changes to signals Format reads refresh the shown value outside editing.
// Precision is what typed values round to from Min; 0 uses Step.
Precision float64
// NoSnap leaves typed values unrounded, but still holds them to the range.
NoSnap bool
// Format writes the value, with the decimals of the rounding grid when
// nil, or the shortest round-trip decimal with NoSnap. Changes to
// signals Format reads refresh the shown value outside editing.
// Parse reads it back, using strconv.ParseFloat when nil.
Format func(value float64) string
Parse func(text string) (float64, bool)
// Leading is the scrub handle's icon, or LeadingText its text, such
Expand Down Expand Up @@ -70,7 +77,17 @@ func decimals(step float64) int {
func (n NumberInput) Render(cx *core.Scope) core.Node {
format := n.Format
if format == nil {
d := decimals(n.step())
d := -1
if !n.NoSnap {
if n.Precision == 0 {
d = decimals(n.step())
} else {
d = decimals(n.Precision)
if n.Max > n.Min {
d = max(d, decimals(n.Min))
}
}
}
format = func(v float64) string { return strconv.FormatFloat(v, 'f', d, 64) }
}
parse := n.Parse
Expand All @@ -81,7 +98,8 @@ func (n NumberInput) Render(cx *core.Scope) core.Node {
}
}
number := func(v float64) func() *float64 { return func() *float64 { return &v } }
in := base.NumberInput{Ref: n.Ref, LabelledBy: n.LabelledBy, Invalid: n.Invalid, Format: format, Parse: parse, OnCommit: true, Snap: true, Step: n.step, Disabled: n.Disabled, Label: n.Label, LabelFunc: n.LabelFunc, TestID: n.TestID,
in := base.NumberInput{Ref: n.Ref, LabelledBy: n.LabelledBy, Invalid: n.Invalid, Format: format, Parse: parse, OnCommit: true,
Snap: !n.NoSnap, Precision: n.Precision, Step: n.step, Disabled: n.Disabled, Label: n.Label, LabelFunc: n.LabelFunc, TestID: n.TestID,
ControlsRight: true, IncrementLabel: n.IncrementLabel, DecrementLabel: n.DecrementLabel,
Value: func() *float64 {
v := 0.0
Expand Down
75 changes: 75 additions & 0 deletions ui/numberinput_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/nsgo-dev/nsgo/core"
"github.com/nsgo-dev/nsgo/icons/lucide"
"github.com/nsgo-dev/nsgo/nsgotest"
)

// TestNumberInput steps the value with its buttons up to the range's
Expand Down Expand Up @@ -59,3 +60,77 @@ func TestNumberInputKeys(t *testing.T) {
t.Fatalf("value = %v, want 4", value.Get())
}
}

func TestNumberInputPrecision(t *testing.T) {
const field = "label:Gravity"
var value *core.Signal[float64]
app, _ := start(t, desktopEnv, func(cx *core.Scope) core.Node {
value = core.NewSignal(cx, 9.81)
return NumberInput{TestID: "gravity", Label: "Gravity", Value: value.Get, OnChange: value.Set,
Min: 0, Max: 100, Step: 0.1, Precision: 0.01, IncrementLabel: "Increase", LeadingText: "g"}
})
checkNumberInputValue(t, app, value, field, 9.81, "9.81")
app.Post(func() { value.Set(9.8) })
app.Settle()
app.Clear(field)
app.Type(field, "9.81")
app.Submit(field)
checkNumberInputValue(t, app, value, field, 9.81, "9.81")

app.Press("label:Increase")
checkNumberInputValue(t, app, value, field, 9.91, "9.91")
app.Focus(field)
app.Key("down")
checkNumberInputValue(t, app, value, field, 9.81, "9.81")
app.Pan("gravity-scrub", core.Point{X: 3}, core.Point{X: 4})
checkNumberInputValue(t, app, value, field, 9.91, "9.91")
}

func TestNumberInputPrecisionFromMin(t *testing.T) {
const field = "label:Offset"
var value *core.Signal[float64]
app, _ := start(t, desktopEnv, func(cx *core.Scope) core.Node {
value = core.NewSignal(cx, 0.005)
return NumberInput{Label: "Offset", Value: value.Get, OnChange: value.Set,
Min: 0.005, Max: 100, Step: 0.1, Precision: 0.01}
})
app.Clear(field)
app.Type(field, "9.811")
app.Submit(field)
checkNumberInputValue(t, app, value, field, 9.815, "9.815")
}

func TestNumberInputNoSnap(t *testing.T) {
const field = "label:Gravity"
var value *core.Signal[float64]
app, _ := start(t, desktopEnv, func(cx *core.Scope) core.Node {
value = core.NewSignal(cx, 9.8)
return NumberInput{Label: "Gravity", Value: value.Get, OnChange: value.Set,
Min: 0, Max: 100, Step: 0.1, NoSnap: true}
})
app.Clear(field)
app.Type(field, "9.8123")
app.Submit(field)
checkNumberInputValue(t, app, value, field, 9.8123, "9.8123")

// Stepping starts from the committed value, not the unsubmitted draft.
app.Clear(field)
app.Type(field, "15")
app.Key("up")
checkNumberInputValue(t, app, value, field, 9.9123, "9.9123")

app.Clear(field)
app.Type(field, "120")
app.Submit(field)
checkNumberInputValue(t, app, value, field, 100, "100")
}

func checkNumberInputValue(t *testing.T, app *nsgotest.App, value *core.Signal[float64], field string, want float64, wantText string) {
t.Helper()
var got float64
app.Post(func() { got = value.Get() })
app.Settle()
if text := app.Find(field).Text; got != want || text != wantText {
t.Fatalf("value = %v, shown %q; want %v, shown %q", got, text, want, wantText)
}
}
Loading