# SettingSwitch, SettingChoice, SettingNumber — settings edited in place, each saying where its value comes from

> A card of settings, one row each: the setting's name, what it does and where its value comes from on the left — the Default chip, "Set for Alpha" with who and when and a Reset link, or Locked by an organisation's policy with why — and its control on the right. A switch or a choice saves as it changes and says "Saved · Undo"; a typed number shows Cancel and Save and checks its range on Save. Someone who may not change it reads the value as words. Every colour, line, height and padding is a theme token, so a look sets its values and forks nothing.

<!-- id: ui-setting-controls · area: ui · stability: preview · html: https://osysharp.com/reference/ui/setting-controls/ -->

## Summary        {#summary}
A product's settings are read far more often than they are changed, so each row says, at a glance, what the setting
does and where its value comes from — and lets the person who may change it do so where it stands, without a form
and a Save at the foot of the page.

```osy syntax
SettingsCard("Designer tools", description: "What the design agent may look up.") {
  SettingSwitch("Other products", value: p.SearchOthers, help: "Search the plans of other products you can see.",
                setFor: p.SearchOthers ? "" : p.Name, onReset: ResetOthers);
  SettingNumber("Session size", value: p.SessionSize, unit: "tokens", min: 10000, max: 1000000,
                setFor: p.SessionSize == 200000 ? "" : p.Name, resetTo: "200,000", onReset: ResetSize);
  SettingSwitch("Earlier sessions", value: p.SearchSessions, lockedBy: "Northwind Health's policy · version 5",
                lockedWhy: "Session history is kept for audit.");
}
```

## Signature      {#signature}
```osy syntax
SettingsCard(string title, string description = "") { …rows… }

SettingSwitch(string label, Binding<bool> value, string onWord = "On", string offWord = "Off", …where it comes from…)
SettingChoice<T>(string label, Binding<T> value, T[] options = T.Members, …where it comes from…,
                 Func<T, string>? detail = null, Func<T, string>? words = null)   // the kit's SelectField, in a setting's face; detail: opens its list
SettingNumber(string label, Binding<int> value, string unit = "", int min, int max, string outOfRange = "", …where it comes from…)
SettingAlways(string name, string help = "", string word = "Always on", string note = "")
SettingRow(name: "…", …where it comes from…) { YourControl(…); }

// where it comes from, and how it saves — the same on every row:
//   string help, string setFor, string setBy, string setWhen, string resetTo, Action? onReset,
//   string lockedBy, string lockedWhy, bool readOnly,
//   SettingSaves saves = SettingSaves.Immediate, Func<string>? saveWith, Action? onSaved
public enum SettingSaves { Immediate, Explicit }
```

## Description    {#description}

### One row, four ways to say where its value comes from   {#provenance}
Under the name and the help line, every row says where its value comes from, in exactly one of four ways. The words
are the app's; the row only draws them.

| The app passes | The row says |
|---|---|
| nothing | the **Default** chip |
| `setFor: "Alpha"` (+ `setBy`, `setWhen`, `onReset`, `resetTo`) | **Set for Alpha** · "by you · just now" · *Reset to default* (or *Reset to 200,000*). A switch says **Turned on for Alpha** / **Turned off for Alpha** |
| `lockedBy: "Northwind Health's policy · version 5"` (+ `lockedWhy`) | **🔒 Locked** · "by Northwind Health's policy · version 5", the reason under it, and the control disabled |
| `SettingAlways(…, note: "…")` | the note, and "✓ Always on" where a control would be — a fact nobody changes |

`readOnly: true` is the form for someone who may not change the setting: the value as plain words on the right
("Ask each time", "150,000 tokens", "On"), the provenance as before, no Reset and no control. Pass it from the same
rule the row's `security { }` uses (`readOnly: !IsOwner`) — the row is refused by its own rules either way.

### It saves where it stands   {#saves}
With `saves: SettingSaves.Immediate` (the default) the row saves itself:

- **A switch or a choice saves as it changes**, and says "✓ Saved · Undo". Undo saves the value before.
- **A typed number stays in its box until Save.** Cancel and Save appear under it once the person types; Save checks
  `min`/`max` and says `outOfRange` (or "Enter a number from 10,000 to 1,000,000.") under the box, storing nothing.
- **It saves by committing the page's unit of work** — or, with `saveWith`, through a function of the page's that
  answers `""` when it saved and the reason when it did not, exactly as `SaveBar`'s `saveWith` ([[ui-settings#save]]).
  A save that is refused is put back, and the reason is said under the control. `onSaved` runs once a save lands —
  to re-read who changed it and when.

`saves: SettingSaves.Explicit` fits the row into a page that saves with `SaveBar`: the control edits the page's unit
of work and saves nothing itself — no "Saved", no row Save. Keep one page to one of the two.

### Asking why: `reason:`   {#reason}
`reason: why` (a string of the page's) draws a **Why** box under the control — a number's while it is typed, beside its
Cancel and Save; a switch's and a choice's always, so it is filled before the press. What is typed lands in `why`, and
the row's `saveWith` reads it, so an app whose server function refuses a change without a reason is answered:

```osy syntax
string why = "";
string SaveWithReason() { return why.Trim() == "" ? "say why this is changed." : Save(why); }   // "" when it saved
SettingNumber("Session size", value: p.SessionSize, unit: "tokens", reason: why, saveWith: SaveWithReason);
```
The row says the app's refusal as "Not saved — say why this is changed." and the value is put back. `reasonRequired: true`
holds the save in the kit instead, saying "Say why first." while the box is empty. Without `reason` nothing is drawn.
In a test: `Ui.Fill("Why", "Cheaper sessions", within: "Session size")`.

### A line under the row: `note:`   {#note}
`note: "Latest reason: cheaper sessions"` on `SettingSwitch`, `SettingChoice` and `SettingNumber` puts the app's own words
on the row's provenance line (`SettingAlways` and `SettingRow(name:)` already took it). Nothing is drawn without it.

### A read-only number in the app's own words: `words:`   {#words}
A read-only `SettingNumber` says "150,000 tokens" by default. `words: n => n + " dollars"` says the app's own words for the
value instead — a budget reads "8 dollars", not "8" or "$8.00". It is a display formatter, so no currency or unit is the
kit's, exactly as `SettingChoice`'s `words:` is for its options. A row that can be edited keeps its number and `unit`.

### An app that cannot say where a value came from: `chipless:`   {#chipless}
With no `setFor` and no lock a row says **Default**. An app whose readers cannot see the change history must not say
that when it is not known: `chipless: true` — on `SettingSwitch`, `SettingChoice`, `SettingNumber` and
`SettingRow(name: …)` — leaves the Default chip out. A row that is set for something, or locked, still says so.

### A control of your own in the same row   {#row}
`SettingRow(name: "Colour", hint: "…", setFor: …) { ColourPicker("Colour", value: p.Colour); }` lays out any control
the kit does not draw in place in the same row, with the same provenance line. Without `name:` a `SettingRow` is what
it always was — a control with its hint under it ([[ui-settings#row]]).

### On a phone, a choice and a number go full-width   {#phone}
Below the `Tablet` breakpoint (the row's own room, `Layout.AtLeast`, [Viewport.AtLeast and Layout.AtLeast — the window, or the room this component has](https://osysharp.com/reference/ui/viewport/)) a switch stays beside the name at
44 × 26; a choice and a number go full-width under the help line, 44 high; the provenance line comes last.

### Every measure is a token   {#tokens}
Each defaults to a token the kit already had, so on the floor the rows take the app's theme as it is; a look that
draws them to a design sets only the ones its design states differently.

| Token | Default | What it draws |
|---|---|---|
| `Colors.SettingsCardBg` · `SettingsCardLine` | `Surface` · `CardLine` | a settings card's ground and edge |
| `Radius.SettingsCard` | `Radius.Lg` | its corners |
| `Space.SettingsCardHeadTop` · `SettingsCardHeadBottom` | 3.5 · 3 steps | the room above and under its title |
| `FontSize.SettingsCardTitle` | `Body` | its title |
| `Colors.RowLine` | `Border` | the rule between rows |
| `Length.SettingRowCols` | `minmax(0, 1fr) 300px` | a row's two columns: the words, the control |
| `Space.SettingRowX` · `SettingRowY` · `SettingRowGap` | 5 · 4 · 6 steps | a row's padding, and the room between its columns |
| `Space.SettingRowXTouch` · `SettingRowYTouch` | 4 · 3.5 steps | a row's padding on a phone |
| `Colors.SettingNameInk` · `FontSize.SettingName` · `SettingNameTouch` | `OnSurface` · `Label` · `Body` | the name (and a read-only value) |
| `Colors.SettingHelpInk` | `MetaText` | the help line, a switch's word, a lock's reason |
| `Colors.ProvenanceInk` | `MetaText` | "by you · just now", a number's unit |
| `Colors.SettingDefaultTint` · `SettingDefaultInk` | `DefaultTint` · `DefaultInk` | the Default chip |
| `Colors.SettingSetTint` · `SettingSetInk` | `PrimaryTint` · `PrimaryInk` | the Set for … chip |
| `Colors.SettingLockedTint` · `SettingLockedInk` | `WarningTint` · `WarningInk` | the Locked chip |
| `Length.SettingChipH` · `Space.SettingChipX` · `Radius.SettingChip` · `FontSize.SettingChipFont` | `18px` · 1.5 steps · `Radius.Sm` · `Overline` | the chip's height, sides, corners and words |
| `Colors.SettingSwitchOn` · `SettingSwitchOff` · `SettingSwitchKnob` | `Primary` · `ControlBorder` · white | the switch's track, on and off, and its knob |
| `Colors.SettingSwitchLockedOn` · `SettingSwitchLockedOff` | the on track mixed 40 % into `Surface` · `Muted` | a switch a policy holds |
| `Length.SettingSwitchW` · `SettingSwitchH` · `SettingKnobSize` | `34px` · `20px` · `14px` | the switch |
| `Length.SettingSwitchWTouch` · `SettingSwitchHTouch` · `SettingKnobSizeTouch` | `44px` · `26px` · `20px` | the switch on a phone |
| `Space.SettingSwitchInset` · `Shadow.SettingKnobLift` | `3px` · a 1px drop | the knob's inset and its shadow |
| `Colors.ControlBorder` · `Radius.SettingControl` | `Border` · `Radius.Md` | a choice's and a number's box |
| `Length.SettingControlH` · `SettingControlHTouch` · `SettingFieldW` | `ControlSm` · `Touch` · `220px` | its height (on a phone) and width |
| `FontSize.SettingControlFont` · `SettingControlFontTouch` | `Label` · `Body` | the words in it, a switch's word |
| `Colors.SelectChevronInk` · `Length.SelectChevronRoom` | `MetaText` · `30px` | a choice's chevron and the room its box keeps clear for it — the kit's one dropdown chevron, shared with every `SelectField` (a choice IS a `SelectField` in the setting's face) |
| `Colors.SettingLockedRowBg` · `SettingLockedBg` | `Muted` mixed 35 % into `Surface` · `LockedValueBg` | a locked row's ground, a locked box's |
| `Colors.SettingSavedInk` · `SettingAlwaysTick` | `SuccessInk` · `Success` | "Saved · Undo", the tick beside "Always on" |

In a test: press a switch by its name (`Ui.Click("Other products")`), read a row as the group of that name
(`Assert.Visible("Saved", within: "Other products")`), fill a number and save it in its row
(`Ui.Fill("Session size", "150000")`, `Ui.Click("Save", within: "Session size")`), and `Assert.Disabled` a locked one.

## Examples       {#examples}

### A product's planning settings, changed where they stand   {#example-product}
```osy title="a card of settings: a choice, a number with its unit, a switch, a fixed fact and a locked one" test app=ui-setting-controls
public enum Unfinished { [Label("Ask each time")] Ask, [Label("Move to the next release")] NextRelease }

entity ProductSettings {
  [Required, MaxLength(80)] string Product = "Alpha";
  Unfinished Unfinished = Unfinished.Ask;
  int SessionSize = 200000;
  bool SearchOtherProducts = true;
  bool SearchSessions = true;
  security { allow read, create, update when IsAuthenticated; }
}

[Route("/settings")] [Title("Settings")]
component ProductSettingsPage() {
  live var s = ProductSettings.FirstOrDefault();

  action ResetUnfinished() { s.Unfinished = Unfinished.Ask; UnitOfWork.Commit(); }
  action ResetSize() { s.SessionSize = 200000; UnitOfWork.Commit(); }
  action ResetOthers() { s.SearchOtherProducts = true; UnitOfWork.Commit(); }

  render {
    if (s != null) {
      Stack(gap: 4, p: 6) {
        SettingsCard("Planning and releases", description: "How " + s.Product + " plans its work.") {
          SettingChoice("Unfinished items at release", value: s.Unfinished,
                        help: "What happens to items that aren't done when a release is marked as released.",
                        setFor: s.Unfinished == Unfinished.Ask ? "" : s.Product, onReset: ResetUnfinished);
          SettingNumber("Session size", value: s.SessionSize, unit: "tokens", min: 10000, max: 1000000,
                        help: "The largest estimate a slice can have and still fit in one agent session.",
                        setFor: s.SessionSize == 200000 ? "" : s.Product, resetTo: "200,000", onReset: ResetSize);
        }
        SettingsCard("Designer tools", description: "What the design agent may look up.") {
          SettingAlways("Work on the outline", help: "Read and edit the outline.",
                        note: "Always available: this is the designer's core job.");
          SettingSwitch("Other products", value: s.SearchOtherProducts,
                        help: "Search the plans of other products you can see.",
                        setFor: s.SearchOtherProducts ? "" : s.Product, onReset: ResetOthers);
          SettingSwitch("Earlier sessions", value: s.SearchSessions, help: "Search this design's previous sessions.",
                        lockedBy: "Northwind Health's policy · version 5",
                        lockedWhy: "Session history is kept for audit. Ask an organization admin to change it.");
        }
      }
    }
  }
}
```

The kit's own test app draws the same page at `/setting-controls` (with the change trail's "by … · just now" and a
read-only form for someone who may not change it), and its tests press, undo, refuse and lock it.

## See also       {#see-also}
- [SettingsArea — an app's settings: sections, explicit save and discard, undo, who changed what](https://osysharp.com/reference/ui/settings/) — the settings area, its pages and sections, and `SaveBar`'s explicit save
- [[Settings] and [Setting]: a settings section declared on its row, each field drawn by its type](https://osysharp.com/reference/ui/settings-declared/) — a row of settings declared with `[Settings]` and drawn with no page code
- [Save, discard, undo — three ways to show a page's unit of work](https://osysharp.com/reference/ui/saving/) — `SaveBar`, `SaveActions` and `AutoSave`, the page-wide ways to save
- [theme tokens](https://osysharp.com/reference/ui/theming/) — how a theme sets the tokens above
- [Viewport.AtLeast and Layout.AtLeast — the window, or the room this component has](https://osysharp.com/reference/ui/viewport/) — `Layout.AtLeast`, which decides the phone layout
