# The Vi guide

The lessons in Studio's **Learn** panel are built from this file, one `##` section per lesson
(`docs/tools/build-learn.mjs`). Every `vi` example here is a whole program and runs with **Try it**;
the few marked `vi fragment` only show one idea. `compiler/tests/learn.test.ts` checks them all.

## Comments and names

A `#` starts a comment that runs to the end of the line. `<# … #>` holds a comment over several
lines. Vi ignores comments; they are notes for people.

```vi
<# A greeting card.
   This comment spans three lines. #>
main greeting_card:
  color: blue[50]          # a light blue background
  arrange: center
  children:
    greeting_text:
      text: "Hello from Vi!"
      text_style: 22
```

Names are lowercase words joined with underscores: `greeting_card`, `add_task`, `high_score`.
A name says what the thing is or does. Vi tells the kinds of names apart by how they are written:

| Written like | It is | Example |
|---|---|---|
| `name = value` | a variable (data) | `score = 0` |
| `name(…):` + statements | a function (work) | `add_point():` |
| `name:` + attributes | a container (something on screen) | `header:` |

## Containers

Everything on the screen is a **container**: a box with attributes, one per line. A container can
hold other containers in `children:`, one per line.

```vi
main main_screen:
  color: gray[100]
  children:
    header:
      size: max, 15
      color: purple[400]
      arrange: center
      children:
        title:
          text: "Containers"
          text_style: 20, white
    body:
      size: max, max
      arrange: center
      children:
        note
    footer

note:
  text: "A container defined on its own, used by name"

footer:
  size: max, 10
  color: purple[100]
```

- A child written inside `children:` (like `header:`) belongs to its parent.
- A child written by name (`note`, `footer`) is a container defined on its own, at the left edge.
  Use that for pieces you show in several places.
- Every container has a name, so you can find it, change it and reach it from code.

Several containers can share one style:

```vi
main row_of_cards:
  arrange: row, spread
  space_inside: 16
  children:
    card_a
    card_b
    card_c

card_a, card_b, card_c:
  size: 30
  color: teal[300]
  shape: rounded
```

## Size and space

**Boxes stretch with the screen; text and gaps stay the same.**

`size: width, height` is out of 100 of the parent: width against the parent's width, height
against the parent's height. One number makes a square from the parent's width.

| Value | Means |
|---|---|
| `size: 50, 20` | half as wide as the parent, a fifth as tall |
| `size: 30` | a square, 30 % of the parent's width on each side |
| `size: max, auto` | fill the width, as tall as the content |
| `max` | fill the room that is left |
| `auto` | fit the content (the default) |

Space is in fixed points, the same on every phone:

| Attribute | The space… |
|---|---|
| `space_inside` | inside the container, around its children (padding) |
| `space_between` | between the children |
| `space_around` | outside the container (margin) |

The difference between `space_inside` and `space_around` is which side of the edge the space is on.
`space_inside` is part of the container: its colour, image and tap area fill it, and it pushes the
children away from the edge. `space_around` is outside: the parent shows through, and it pushes the
container away from its neighbours and its parent's edge.

One number is every side. Name the sides for different ones, in any combination:
`space_inside: 16, top 32` or `space_inside: left right 20, top bottom 8`.

```vi
main page:
  space_inside: 24, top 48
  space_between: 12
  children:
    box_a:
      size: max, 20
      color: amber[300]
    box_b:
      size: 50, 20
      color: amber[500]
      space_around: left 40
    box_c:
      size: 25
      color: amber[700]
```

## Arrange and place

`arrange:` says how a container lays out its children: the **direction**, the **spot** and the
**spread**, in any order, all optional.

- Direction: `column` (top to bottom, the default) or `row` (left to right).
- Spot: `top`, `bottom`, `left`, `right`, `center`, or a pair like `bottom right`.
- Spread: `spread` puts the free space between the children; `even` puts it around them too.
- `scroll` makes the container scroll when its children don't fit.

Vi works out the rest. You never say which axis is "main"; `bottom right` means the bottom right
corner whichever way the children run.

Picture the container as a box and its children as a small stack. The **spot** says where in the box
the stack sits; the first word is up or down, the second is left or right:

```text
 arrange: center         arrange: top center
┌───────────────┐       ┌───────────────┐
│               │       │     [ A ]     │
│     [ A ]     │       │     [ B ]     │
│     [ B ]     │       │     [ C ]     │
│     [ C ]     │       │               │
│               │       │               │
└───────────────┘       └───────────────┘

 arrange: bottom right   arrange: row, center
┌───────────────┐       ┌───────────────┐
│               │       │               │
│               │       │               │
│          [ A ]│       │ [A]  [B]  [C] │
│          [ B ]│       │               │
│          [ C ]│       │               │
└───────────────┘       └───────────────┘
```

The **spread** shares out the free space instead of grouping the children at one spot: `spread`
puts it only between them, `even` puts it around them too.

```text
 arrange: spread         arrange: even
┌───────────────┐       ┌───────────────┐
│     [ A ]     │       │               │
│               │       │     [ A ]     │
│               │       │               │
│     [ B ]     │       │     [ B ]     │
│               │       │               │
│               │       │     [ C ]     │
│     [ C ]     │       │               │
└───────────────┘       └───────────────┘
```

Try every combination here:

```vi
main home:
  arrange: row, bottom right
  space_inside: 20
  space_between: 8
  color: indigo[50]
  children:
    a:
      size: 20
      color: indigo[300]
    b:
      size: 20
      color: indigo[500]
    c:
      size: 20
      color: indigo[700]
```

`place:` is for one container that should **float** above the others, pinned to a spot of its
parent: `place: bottom right` for a round "+" button, or `place: x, y` to put its middle at a
point out of 100 (`place: 50, 10` is centred, near the top). Games move things this way.

```vi
main home:
  color: white
  children:
    message:
      text: "A list would go here"
      space_inside: 24
    add_button:
      place: bottom right
      space_around: 24
      size: 16
      shape: circle
      color: blue[600]
      button: "+"
      text_style: 28, white
```

## Text

`text:` shows text. `{name}` puts a value inside it; `{{` writes a real brace.
`text_style:` holds the size, the weight, the colour and the font, in any order:

```vi
first_name = "Ada"

main home:
  arrange: center
  space_between: 8
  children:
    hello:
      text: "Hello, {first_name}!"
      text_style: 32, bold, purple[700]
    quiet:
      text: "Weights: thin, light, bold, heavy; also italic and underline."
      text_style: 14, italic, gray[600]
    serif:
      text: "A font by name, in quotes"
      text_style: 18, "Georgia"
```

- A number is the size, in points.
- `bold`, `italic`, `light`, `thin`, `heavy`, `underline`, `strikethrough` are the weights and lines.
- A colour name is the colour. A quoted name is the font.
- Children take on their parent's `text_style`, so set it once on a card.
- Text lines up with `arrange` (there is no separate text alignment).

## Colour, shape and images

`color:` is the background. Colours have names (`red`, `teal`, `gray`…), shades from 50 (light)
to 900 (dark) like `blue[600]`, or `rgb(r, g, b)` with an optional fourth number from 0
(see-through) to 1 (solid). A hex colour goes in quotes: `"#FF6B6B"`.

```vi
main swatches:
  arrange: row, center
  space_between: 10
  children:
    named:
      size: 20
      color: coral
      shape: circle
    shade:
      size: 20
      color: teal[700]
      shape: rounded
    mixed:
      size: 20
      color: rgb(255, 120, 0, 0.6)
      shadow: true
    faded:
      size: 20
      color: "#6B4EFF"
      see_through: 50
      outline: 2, purple[900]
```

| Attribute | Does |
|---|---|
| `shape:` | `square` (default), `rounded` or `circle` |
| `shadow: true` | a soft drop shadow |
| `see_through: 50` | 50 % see-through (0 is solid, 100 invisible) |
| `outline: 2, red` | a 2-point line round the edge; name sides for some: `outline: bottom 1, gray` |
| `visible: false` | hides it (and the space it took) |
| `image: @photo.jpg` | a picture behind the children; add `fill` to cover the box, `blurred` to blur it |

`@name` means a file in the project's `assets` folder: `@cat.png`, `@backgrounds/sky.jpg`.
Typing `@` lists the files. Web pictures go in quotes: `image: "https://…/photo.jpg"`.

```vi
main card:
  size: max, 40
  image: @hero.png, fill
  arrange: bottom left
  space_inside: 16
  children:
    caption:
      text: "Pictures come from the assets folder"
      text_style: 16, bold, white
```

## Buttons, inputs and other kinds

The attribute that names a kind of container also holds its main value:

| Write | You get |
|---|---|
| `button: "Save"` | a button with that label |
| `input: "Your name"` | a text field; the words show while it is empty. Read what was typed as `name.text` |
| `search: "Search songs"` | a search field |
| `icon: heart` | an icon; its size and colour come from `text_style` |
| `link: "https://…"` | opens the page when tapped |
| `arrange: column, scroll` | a list that scrolls |

```vi
greeting = "Type your name and press Enter"

main form:
  space_inside: 24
  space_between: 12
  children:
    name_box:
      input: "Your name"
      on_change: greeting = "Hello, {name_box.text}…"
      on_submit: greeting = "Hello, {name_box.text}!"
    message:
      text: greeting
      text_style: 18
    row:
      arrange: row, center
      space_between: 8
      children:
        star:
          icon: star
          text_style: 28, amber[500]
        more:
          link: "https://example.com"
          text: "Read more"
```

## Events

An event runs an action when something happens to a container. A short action fits on the line;
several actions go one per line underneath.

| Event | Runs when |
|---|---|
| `on_tap` | it is tapped |
| `on_hold` | it is pressed and held |
| `on_touch` | a finger lands on it (at once, with no tap highlight: for games) |
| `on_swipe` | a swipe: `left:`, `right:`, `up:`, `down:` underneath |
| `on_change` | the text of an input changes |
| `on_submit` | Enter / Done is pressed in an input |
| `on_hit` | two containers start to overlap: `a, b: action` underneath (games) |

```vi
taps = 0
last = "nothing yet"

main pad:
  arrange: center
  space_between: 12
  color: green[50]
  on_swipe:
    left: last = "swiped left"
    right: last = "swiped right"
  children:
    target:
      size: 40
      shape: circle
      color: green[700]
      arrange: center
      text: "{taps}"
      text_style: 36, bold, white
      on_tap: taps = taps + 1
      on_hold:
        taps = 0
        last = "held: back to zero"
    log:
      text: "Last: {last}"
```

## Data: lists and objects

A variable holds a value: a number, text in quotes, `true` / `false`, a list `[…]` or an object
`{ … }`.

```vi
score = 0
player = "Ada"
playing = true
scores = [12, 40, 7]
user = { name: "Sam", age: 31 }

main show_data():
  scores.add(25)
  print(player, "has", scores.count, "scores")
  print("first", scores.first, "last", scores.last)
  print("has 40?", scores.has(40))
  user.age = user.age + 1
  print(user.name, "is now", user.age)
  scores.remove(7)
  print(scores)
  scores.clear()
  print("left:", scores.count)
```

| On a list | Does |
|---|---|
| `items.add(x)` | adds `x` at the end |
| `items.remove(x)` | removes `x` |
| `items.clear()` | removes everything |
| `items.count` | how many there are |
| `items.first`, `items.last` | the first and the last |
| `items.has(x)` | `true` when `x` is in the list |
| `items.index(x)` | where `x` is (from 0) |
| `items[0]` | the item at a place, from 0 |

Objects group named values: `user.name` reads one, `user.age = 32` changes it. A list of objects is
the usual way to hold records: `tasks = [{ name: "Milk", done: false }]`.

## Functions

A function has brackets after its name and holds statements. It can take values and give one
back with `return`.

```vi
add(a, b):
  return a + b

describe(n):
  if (n > 10):
    return "big"
  return "small"

main try_functions():
  total = add(3, 4)
  print("3 + 4 =", total, "which is", describe(total))
  helper(x):
    return x * 2
  print("doubled:", helper(total))
```

Built-in functions:

| Function | Does |
|---|---|
| `print(a, b, …)` | writes a line to the Output panel (or the console screen) |
| `wait(seconds)` | pauses this function, then carries on |
| `random(1, 7)` | a whole number from 1 up to 6 |
| `go_to(screen)`, `go_back()` | changes screen (lesson **Screens**) |
| `every(seconds, action)`, `stop(timer)` | repeats an action (lesson **Timers and games**) |
| `play(@sound.mp3)`, `stop(sounds)` | plays sounds (lesson **Sound and video**) |
| `visit("https://…")` | opens a web page |

## Conditions and loops

`if` runs a block when its condition is true; `else if` and `else` cover the other cases. Combine
conditions with `and`, `or` and `not`. The short form `a if (condition) else b` picks a value.

```vi
main grades():
  for score in [95, 82, 64]:
    if (score >= 90):
      print(score, "is an A")
    else if (score >= 80):
      print(score, "is a B")
    else:
      print(score, "needs work")
  n = 0
  while (n < 3):
    n = n + 1
  print("counted to", n)
  late = false
  print("on time" if (not late) else "late")
```

The short form works in attributes too: `color: green if (done) else gray`.

## Programs without a screen

Mark a **function** `main` instead of a container, and Vi runs it once as a console program: no
screen, just what it prints. Studio shows a **Console** screen with the output and a **Run again**
button.

```vi
main times_table():
  for n in [1, 2, 3, 4, 5]:
    print(n, "× 7 =", n * 7)
```

A file can have both a `main` container and a `main` function: the app shows the screen and runs
the function once when it starts.

## Screens

The `main` container is the first screen. Every other screen is a container you open with
`go_to(name)`; `go_back()` returns. Screens fill the phone and stay clear of the notch and the
keyboard by themselves.

```vi
tasks = [{ name: "Buy milk", note: "Two litres" }, { name: "Call Sam", note: "About Friday" }]

main home:
  space_inside: 24
  space_between: 12
  children:
    first:
      button: tasks[0].name
      on_tap: go_to(details(tasks[0]))
    second:
      button: tasks[1].name
      on_tap: go_to(details(tasks[1]), fade)
    settings_button:
      button: "Settings"
      on_tap: go_to(settings, slide)

details(task):
  space_inside: 24
  space_between: 12
  children:
    title:
      text: task.name
      text_style: 28, bold
    note:
      text: task.note
    back:
      button: "Back"
      on_tap: go_back()

settings:
  arrange: center
  children:
    label:
      text: "Settings"
    back:
      button: "Back"
      on_tap: go_back()
```

- `go_to(details(task))` opens a screen that **takes a value** (lesson **Containers that take values**).
- The second value picks the change: `slide`, `fade` or `none`. The default is the phone's own slide.
- `phone`, `tablet` and `desktop` are `true` on that size of screen:
  `arrange: row if (tablet) else column`.

## Containers that take values

A container can take values, like a function: write the names in brackets after its name, then
use them in its attributes. Show it with values: `task_card(tasks[0])`.

```vi
tasks = [{ name: "Buy milk", done: true }, { name: "Call Sam", done: false }]

main home:
  space_inside: 20
  space_between: 10
  children:
    task_card(tasks[0])
    task_card(tasks[1])

task_card(task):
  size: max, auto
  space_inside: 14
  shape: rounded
  color: green[100] if (task.done) else white
  shadow: true
  text: task.name
  text_style: strikethrough if (task.done) else normal
  on_tap: task.done = not task.done
```

Containers written inside it see the values too, however deep:

```vi
main home:
  children:
    tab("🧳", "Trips")
    tab("🗺️", "Map")

tab(emoji, label):
  arrange: row
  space_between: 6
  children:
    tab_icon:
      text: emoji
    tab_name:
      text: label
      text_style: 12, bold
```

## Repeating things

`repeat:` makes copies of a container.

- `repeat: task in tasks` makes one copy per item. `task` is that copy's item, and the copies
  follow the list: add an item and a copy appears.
- `repeat: 5` makes five copies; `repeat: 3, 3` makes a grid of 3 columns and 3 rows.
- In a copy, `index` is its place (from 0). In a grid, `x` and `y` are its column and row.
- Containers written inside a copy see that copy's item, `index`, `x` and `y` too.
- The copies belong to the parent, like children written out one by one. `repeat: 3` is the same
  as listing the container three times: the parent's `arrange` lines them up and its
  `space_between` is the gap. A grid is one block in the parent; the parent's `space_between` is
  the gap between its cells, and with `spread` or `even` the grid fills the parent and spreads them.

```vi
main home:
  children:
    tiles

tiles:
  size: max, 30
  arrange: row, spread
  space_inside: 10
  children:
    tile

tile:
  repeat: 3
  size: 20
  color: yellow
  shape: rounded
```

```vi
tasks = ["Buy milk", "Call Sam", "Water the plants"]

main home:
  space_inside: 20
  space_between: 8
  children:
    task_row
    add:
      button: "Add a task"
      on_tap: tasks.add("Task {tasks.count + 1}")

task_row:
  repeat: task in tasks
  size: max, auto
  space_inside: 12
  color: gray[100]
  shape: rounded
  text: "{index + 1}. {task}"
  on_hold: tasks.remove(task)
```

```vi
main board:
  arrange: center
  children:
    grid:
      size: max, auto
      arrange: row, center
      children:
        cell

cell:
  repeat: 3, 3
  size: 30
  space_around: 2
  shape: rounded
  color: blue[200] if (x == y) else blue[400]
  arrange: center
  text: "{x}, {y}"
  on_tap: cell.at(x, y).color = orange[400]
```

Reach one copy with `.at()`: `cell.at(1, 1)` in a grid, `task_row.at(4)` in a list.

## Reaching other containers

Code reaches a container by its name: `title.text`, `score_label.color`.

- **Top-level containers** (at the left edge of a file) can be reached by name from anywhere in
  the project.
- **A container written inside another** belongs to it. Its parent and its siblings use the plain
  name; everyone else goes through the parent: `form.name_box.text`. So two cards can each have
  their own `title` without a clash.
- A repeated container's copies: `cell.at(1, 2)`, `task_row.at(0)`.

```vi
main home:
  space_inside: 24
  space_between: 12
  children:
    form
    preview

form:
  space_between: 8
  children:
    name_box:
      input: "Type a name"
    save:
      button: "Show it"
      on_tap: preview.text = "Saved: {name_box.text}"

preview:
  text: "Nothing saved yet"
  text_style: 18, gray[700]
  on_tap: preview.text = "Still typing: {form.name_box.text}"
```

Inside `form`, `save` reaches its sibling as `name_box`. `preview` is outside `form`, so it writes
`form.name_box`.

## Changing the screen

There are two ways to change a container from code:

- **A dot for one change:** `score_label.color = red`.
- **A block for several:** the container's name, then the new attributes underneath.

```vi
main home:
  arrange: center
  space_between: 16
  children:
    light
    switch

light:
  size: 40
  shape: circle
  color: gray[300]
  animate: 0.4 seconds

switch:
  button: "Turn on for 2 seconds"
  on_tap: blink()

blink():
  light:
    color: amber[400]
    shadow: true
  switch.text = "On…"
  wait(2 seconds)
  light:
    color: gray[300]
    shadow: false
  switch.text = "Turn on for 2 seconds"
```

- `light` and `switch` are top-level containers, so `blink()` reaches them by name (lesson
  **Reaching other containers**).
- `wait(2 seconds)` pauses the function; the rest of the app keeps running.
- `animate: 0.4` makes changes to size, place, colour, `see_through`, `flip` and `tilt` glide over
  0.4 seconds instead of jumping.
- Changing a variable that a container uses redraws it too: often that is all you need.

## Timers and games

`every(seconds, action)` runs an action again and again and gives back a timer; `stop(timer)` ends
it. A game is a step function that `every` runs about 30 times a second.

```vi
ball_y = 10
speed = 0
loop = 0

step():
  speed = speed + 0.3
  ball_y = ball_y + speed
  if (ball_y > 90):
    ball_y = 90
    speed = 0 - speed * 0.7

drop():
  stop(loop)
  ball_y = 10
  speed = 0
  loop = every(0.03 seconds, step())

main court:
  color: slate[900]
  on_touch: drop()
  children:
    ball:
      place: 50, ball_y
      size: 10
      shape: circle
      color: orange[400]
    hint:
      place: 50, 96
      text: "Tap to drop the ball"
      text_style: 14, white
```

- `place: x, y` puts a container's middle at x across and y down, out of 100. Change x and y in
  the step function and it moves.
- `on_touch` reacts the moment a finger lands: better than `on_tap` for "tap to jump".
- `on_hit` notices when two containers start to overlap:

```vi fragment
main field:
  on_hit:
    ball, wall: bounce()
    ball, goal:
      score()
      play(@cheer.mp3)
```

- `flip: 180` turns a container over (a card flip) and `tilt: 20` leans it back, in degrees.
- Edit the code while a game runs and the old timers stop by themselves.

The **Comet Glide** template is a whole game built this way.

## Sound and video

```vi
main player:
  arrange: center
  space_between: 12
  children:
    jingle:
      button: "Play a sound"
      on_tap: play(@ding.mp3)
    music:
      button: "Music on (loops)"
      on_tap: play(@music.mp3, loop)
    quiet:
      button: "Stop all sounds"
      on_tap: stop(sounds)
    clip:
      size: max, auto
      video: @intro.mp4
      loop: true
      volume: 80
    controls:
      arrange: row
      space_between: 8
      children:
        go:
          button: "Play"
          on_tap: play(clip)
        hold:
          button: "Pause"
          on_tap: pause(clip)
        back:
          button: "Stop"
          on_tap: stop(clip)
```

- `play(@x.mp3)` plays a sound once; add `loop` to repeat it. `stop(sounds)` stops them all.
- Vi draws no player. `video:` shows only the frames and `audio:` shows nothing; you make the
  buttons and call `play(box)`, `pause(box)` and `stop(box)` (stop goes back to the start).
- `loop: true` starts it again when it ends; `volume:` goes from 0 (silent) to 100 (full).
- Put the files in the `assets` folder and write them with `@`. Web addresses go in quotes.

## Keeping data

```vi
saved best = 0
saved names = []
secret token = ""

main game:
  children:
    score:
      text: "Best: {best}"
    again:
      button: "Clear"
      on_tap: reset(best)
```

- `saved` keeps a variable on the phone: it is still there the next time the app opens.
- `secret` keeps it in the phone's locked storage (passwords, tokens).
- `cloud tasks = []` keeps a list in your online database (see below).
- `reset(best)` puts any top-level variable back to the value it started with.
- Without one of these words, a variable starts again every time the app opens.

## The internet and the cloud

```vi
weather = empty

get_weather():
  weather = load("https://api.example.com/weather.json", 10 seconds)

main home:
  on_open: get_weather()
  children:
    sky:
      text: "{weather.sky}" if weather != empty else "No answer yet"
```

- `load(url)` gives back the data as objects and lists, or `empty` when it fails. `send(url, data)`
  sends data. Both wait for the answer by themselves, like `wait()`.
- An optional time stops waiting (`10 seconds`); keys an API needs go in an object:
  `load(url, 10 seconds, { key: "abc" })`. `last_error()` says what went wrong.
- Vi shows no spinner and no error message: the code shows what it wants.

**The cloud** (Supabase). Put the project's address and its public key in `config:`; then
`cloud tasks = []` is the `tasks` table, kept live both ways (`cloud tasks from todo_items = []` for
another table name). `sign_in(email, password)`, `sign_up(…)`, `sign_out()` and `current_user()` handle
accounts; `upload(photo)` stores a file and gives back its web address. Only the public key belongs in
an app: Vi refuses a secret key.

## The phone

```vi
photo = empty

snap():
  photo = take_photo()
  vibrate()

main home:
  arrange: center
  space_between: 12
  children:
    picture:
      size: 60, 60
      image: photo, fill
    take:
      button: "Take a photo"
      on_tap: snap()
    tell:
      button: "Share"
      on_tap: share(photo)
```

- Photos, videos and sounds: `take_photo()`, `choose_photo()`, `take_video()`, `choose_video()`,
  `record_sound()` (until `stop(box)`), `choose_sound()`. Each gives back the file, or `empty`.
- `camera: back | front | scan` puts a live camera in a container; `take_photo(box)` uses it, and
  `camera: scan` reads QR codes and barcodes into its `text` and runs `on_scan`.
- `my_location()`, `battery()`, `vibrate()`, `notify("Drink water", 10 minutes)`, `on_shake`.
- Bluetooth: `lamp = connect("Lamp")`, then `send(lamp, "on")`; what it sends back runs `on_receive`.
- Other apps: `share(x)`, `copy(text)`, `paste()`, `call(number)`, `write_email(to, subject, text)`,
  `write_sms(number, text)`, `open_map(place)`, `visit(url)`. They only open the app: the person
  presses send.
- Links that open your app: `link: "myshop"` in `config:`; `on_link` runs when one opens the app and
  `opened_link()` gives the part after `myshop://`. `link: "myshop", "myshop.com"` makes website
  links (`https://myshop.com/…`) open it too: a store build writes the two files your website needs
  and says where to put them.
- Vi asks the phone for permission the first time; it shows nothing else.

## Games

```vi
main game:
  size: max, max
  on_key:
    space: jump(player)
    p: pause()
  children:
    player:
      size: 10, 10
      color: orange
      move: arrows
      gravity: normal
      stay_inside: parent
    ground:
      size: max, 5
      place: bottom
      color: green
      solid: true
```

- `move:` is how something moves: `arrows`, `tilt`, `finger` (the player steers), `left`, `right`,
  `up`, `down` (by itself), `towards x`, `away from x`. `speed: slow | normal | fast | number`.
  `stop(enemy)` stops it; setting `enemy.move` starts it again.
- `gravity: light | normal | strong` makes it fall until it lands on something `solid: true`.
  `jump(player)` (or `jump(player, high)`); `bounces: true` bounces instead of stopping.
- `stay_inside: parent` keeps it in; `on_leave` runs when it leaves; `starts_at: player` places each
  new copy of a repeated container where that container is.
- `after(2 seconds, action)` runs once, later. `pause()` pauses everything (timers, movement, sounds)
  and `play()` carries on.
- `frames: @run1.png, @run2.png` with `frame_time: 0.1 seconds` animates pictures.
- `shake(screen, 0.3 seconds)` and `flash(player, red)` for effects.

## Popups and menus

```vi
main inbox:
  on_back: sure.visible = false
  children:
    ask:
      button: "Delete"
      on_tap: sure.visible = true
    sure:
      visible: false
      layer: top
      size: max, max
      color: black
      see_through: 50
      appear: fade
      on_tap: sure.visible = false
      children:
        card:
          size: 80, auto
          color: white
          shape: rounded
          space_inside: 20
          text: "Delete this message?"
```

- A popup is a container shown and hidden with `visible`. `layer: top` draws it above the whole
  screen. Vi adds no dimming, no closing on a tap outside: the code writes them.
- `appear: fade | slide_up | slide_down | slide_left | slide_right | grow | none` is how it comes in
  and goes out. A bottom sheet is `place: bottom` with `appear: slide_up`.
- `place: below x` (or `above x`, `left of x`, `right of x`) puts a dropdown next to what opened it.
- `on_back` runs on the Android back button; the code decides what back does.

## Pages and tabs

```vi
main home:
  children:
    pages:
      arrange: pages
      size: max, max
      children:
        news
        settings
    tabs:
      arrange: row, spread
      children:
        to_news:
          icon: home
          spoken: "News"
          color: blue if (pages.page == news) else gray
          on_tap: go_to(news)
        to_settings:
          icon: settings
          spoken: "Settings"
          color: blue if (pages.page == settings) else gray
          on_tap: go_to(settings, fade)

news:
  text: "News"

settings:
  text: "Settings"
```

- `arrange: pages` shows one child at a time, the first until the code goes elsewhere.
- `go_to(page)` switches that area (with `slide`, `fade` or `none`); `go_back()` returns to the
  previous page or screen. `pages.page` is the page showing. Pages keep their state when hidden.

## Dates and time

```vi
party = date(2026, 12, 25)

main home:
  children:
    clock:
      text: "{now().weekday}, {now().time}"
    left:
      text: "{time_until(party).days} days to go"
```

- `now()`, `date(2026, 12, 25)` or `date("2026-12-25")`.
- Read a date with `.date`, `.time`, `.weekday`, `.ago` ("3 minutes ago"), `.day`, `.month`,
  `.year`, `.hour`, `.minute`.
- `time_until(x)` and `time_since(x)` give `.days`, `.hours`, `.minutes`, `.seconds` and `.text`.
- Add time with a unit: `now() + 3 days`, `party + 1 month` (months follow the calendar).
- `choose_date()` and `choose_time()` open the phone's picker (`empty` when cancelled).

## Text and number helpers

```vi
main sums():
  name = "  ada lovelace "
  print(name.tidy.upper)
  print("a,b,c".split(","))
  print(["x", "y"].join(" and "))
  print(3.14159.round(2))
  print(1250000.commas)
  print([4, 8, 6].average)
  print(number("42") + 1)
```

- Text: `.upper`, `.lower`, `.tidy` (no spaces at the ends), `.count`, `.has("@")`,
  `.starts_with("A")`, `.ends_with(".com")`, `.split(",")`, `.replace("cat", "dog")`.
- Checks: `.is_email`, `.is_number`, `.is_phone`. `number("42")` is 42, or `empty`.
- Numbers: `.round`, `.round(2)`, `.commas`, `.money("NGN")`.
- Lists of numbers: `.total`, `.average`, `.biggest`, `.smallest`; `list.join(", ")` makes text.

## Forms

```vi
main signup:
  space_between: 12
  space_inside: 20
  children:
    email_box:
      input: "Email"
      expects: email
      on_submit: focus(password_box)
    password_box:
      input: "Password"
      expects: password
    bio:
      input: "About you"
      expects: long_text
      limit: 200
    loud:
      slider: 0 to 100
      on_change: print(loud.value)
```

- `expects: email | number | phone | password | long_text` picks the keyboard, hides letters or
  lets the text grow. `limit: 200` is the most letters.
- `focus(box)` puts the cursor in a field; `close_keyboard()` hides the keyboard.
- `slider: 0 to 100` is a slider; its number is `.value` and `on_change` runs as it moves.
- Vi never shows an error by itself: check with `.is_email` and show what you want.

## Maps

```vi
main where:
  children:
    town:
      map: "Lagos"
      zoom: city
      size: max, 60
      children:
        shop:
          place: location(6.60, 3.35)
          icon: location
```

- `map: place` makes a container a map centred on a place name or a location.
- `zoom: country | city | street | building`.
- Inside a map, a child with `place: location(…)` is a pin; it looks like whatever you make it.
- `town.tapped` is where the person tapped (with `.address`), `town.center` where they dragged to.
- `a.distance_to(b)` gives `.km`, `.miles` and `.text`. A published Android app needs
  `maps_key:` in `config:`.

## Purchases and ads

- List the store's products in `config:` (`products: remove_ads, coins_100`). `buy(product)` opens
  the payment sheet and gives back `true` when paid; `owns(product)`, `price_of(product)` and
  `restore_purchases()` do the rest.
- `ads: "ca-app-pub-…~…"` in `config:` is your AdMob app id. `ad: banner` is a container kind;
  `show_ad()` shows a full-screen ad and `watch_ad()` gives back `true` when a rewarded ad was
  watched to the end. `ask_ad_consent()` asks Google's privacy question.
- Both need a phone build. In the preview, purchases act as if they succeeded and ads are Google's
  test ads.

## Themes and dark mode

```vi
themes:
  light:
    paper: white
    ink: gray[900]
  dark:
    paper: gray[900]
    ink: white

main home:
  color: paper
  on_open: use_theme(dark if dark_mode() else light)
  on_dark_mode: use_theme(dark if dark_mode() else light)
  children:
    hello:
      text: "Hello"
      text_style: ink
```

- `themes:` names colours once for each theme; use the names like any colour. They can't be
  built-in colour names.
- `use_theme(name)` switches the whole app. The app does not follow the phone by itself:
  `dark_mode()` and `on_dark_mode` let the code decide.

## Accessibility

- `spoken: "Delete task"` is what a screen reader says for a container (icons and pictures mostly);
  `spoken: empty` hides decoration from it. `announce(text)` speaks a message.
- `screen_reader()`, `reduce_motion()` and `text_scale()` read the phone's settings.
- Text follows the phone's larger-text setting only with `text_size: follow_phone` in `config:`
  (new projects have it).

## More than one language

```vi
config:
  languages: english, yoruba

main home:
  on_open: use_language(phone_language())
  children:
    hi:
      text: { english: "Hello", yoruba: "Ẹ n lẹ" }
```

- Write each text as an object with one key per language from `config: languages:`.
- The first language is used until `use_language(name)`; a missing one falls back to the first.
- Right-to-left languages also run rows right to left. Studio warns about missing translations.

## JavaScript, for what Vi doesn't cover

```text
src/js/party.ts
  export function celebrate() { … }
  export function sales_chart({ data }) { return <BarChart data={data} />; }

src/main.vi
  config:
    packages: "react-native-gifted-charts"
  win():
    celebrate()
  report:
    children:
      sales_chart(monthly_sales)
```

- `.js`, `.ts` and `.tsx` files in `src/` join the project like `.vi` files: their exports are seen
  everywhere, with no imports.
- Exported functions are Vi functions (async ones are waited for). Functions that return JSX are
  containers that sit in `children:`; their values fill the props in order.
- `config: packages:` lists npm packages; Studio installs them into the preview. A package with
  native code needs a phone build.

## Files and projects

A small example fits in one file. A real app reads better when each file does one job. Every new
project is laid out like this:

```
my-app/
  README.md
  assets/              icon.png, splash.png, your pictures and sounds
  src/
    main.vi            the main screen: puts the pieces together
    config.vi          app name, icon, splash screen, store id
    theme.vi           colours used everywhere
    tasks.vi           the data, and the functions that change it
    components/
      header.vi        one piece of the screen per file
      task_row.vi
```

- **Every file sees every name** in the project. There are no imports between your own files:
  `src/main.vi` can show `header` from `src/components/header.vi` just by naming it.
- A name may be defined in **one** file only. Two files defining `header` is an error that names
  both files.
- `src/main.vi` holds the `main` container: that is where the app starts.
- Hover a name, or press F12 on it (**Go to Definition**), to see which file it lives in.
- Code from the internet is the one thing you import, by address:
  `from "https://example.com/widgets.vi" import star_rating` (coming soon).

## The config block

The app's settings live in one `config:` block, in `src/config.vi`.

```vi
config:
  name: "Tasks"
  id: com.yourname.tasks
  version: "1.2.0"
  icon: @icon.png
  splash:
    color: white
    logo: @splash.png
    text: "Tasks"
    time: 1 second

main home:
  arrange: center
  children:
    title:
      text: "Welcome to {config.name}"
```

| Key | Means |
|---|---|
| `name` | the app's name under its icon |
| `id` | the store id, like a reversed web address. **Never change it after publishing**, or the stores see a different app |
| `version` | the version people see in the store, like `"1.2.0"`; raise it for each release |
| `icon` | the launcher icon (a square picture, 1024 × 1024 is best) |
| `splash` | the screen while the app starts: `color`, `logo` or `image`, `text`, `seconds` |
| `screens` | changes the sizes where `phone`, `tablet` and `desktop` start (rarely needed) |

`config.name` (and the other keys) can be read anywhere.

## Errors and good habits

Vi checks the code as you type. Problems show as red (errors: the app can't run) or yellow
(warnings: it runs, but something is off) underlines and in the **Problems** tab. Most have a
**Fix** button there, or a light bulb in the editor.

| You see | It means | The fix |
|---|---|---|
| `Unknown container 'heder'` | a misspelt or missing name | pick the suggested name, or **Create container 'heder'** |
| `Unknown function 'ad_task'` | the function doesn't exist | pick the suggested name, or **Create function 'ad_task()'** |
| `Unknown attribute 'colour'` | not an attribute Vi knows | **Change to 'color'** |
| `Nothing to run: mark the screen with 'main'…` | no `main` container | **Add main container**, or **Mark … as the main container** |
| `Your own files need no import…` | an `import` of a file of the project | **Remove this import line** |
| `'header' is also defined in src/a.vi` | the same name in two files | rename one of them |
| `'name_box' is defined inside 'form' and is not visible here` | an inside name used from outside | **Use 'form.name_box'** |

Good habits:

- **One job per file.** `config.vi` for settings, `theme.vi` for colours, a data file for the
  variables and the functions that change them, one file per piece of the screen in `components/`.
- **Colours in one place.** Name them once (`violet = rgb(109, 74, 255)`) and use the names.
- **Write a piece inside the one container that uses it**; give it its own block when several do.
  Right-click a container for **Move out** and **Move in**.
- **Name things for what they are:** `task_row`, `score_card`, `add_task()`.
- **Format Document** (Shift+Alt+F) tidies spacing and puts attributes in the same order
  everywhere: what it is, size, look, text, layout, children, events.
