# VirtualKeyboard

Tells where the software keyboard leaves the page visible, so content fixed to the bottom of the screen can sit above it.

- Page: https://www.effectcn.com/components/virtual-keyboard
- Kind: Module
- File: `src/ui/virtual-keyboard.ts`
- Built on: `VirtualKeyboard` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/virtual-keyboard.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/virtual-keyboard.ts`

```ts
import { Component, Mount } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import { VirtualKeyboard } from "@effect/ui-kit"
import { cn } from "#lib/cn"

type Options<Msg> = {
  readonly class?: string | undefined
  /** A message for each band the keyboard leaves visible, `null` while none is up. Leave it out when only the CSS is needed. */
  readonly onBand?: ((band: VirtualKeyboard.Band | null) => Msg) | undefined
}

const track = <Msg>(options: Options<Msg>) =>
  VirtualKeyboard.TrackKeyboard().pipe(
    Mount.map((band) => (options.onBand === undefined ? Component.noop : options.onBand(band)))
  )

/**
 * A bar fixed to the bottom of the screen that rides up with the software
 * keyboard: a chat composer, a toolbar, a "Save" strip. The kit's mount
 * writes `--keyboard-inset` on it while a keyboard covers the bottom of the
 * layout viewport, and `bottom` reads it.
 */
export const KeyboardBar = <Msg>(h: Html.H<Msg>, options: Options<Msg> = {}) =>
  h.div
    .class(cn(
      "fixed inset-x-0 bottom-[var(--keyboard-inset,0px)] z-40 flex items-center gap-2 border-t bg-background px-3 py-2.5",
      "pb-[max(0.625rem,env(safe-area-inset-bottom))] shadow-float transition-[bottom] duration-150",
      options.class
    ))
    .onMount(track(options))

/**
 * A container that pads its bottom by the height the keyboard covers, so
 * its last content can scroll into view above the keyboard. Use it around
 * a page or a full-height panel.
 */
export const KeyboardInset = <Msg>(h: Html.H<Msg>, options: Options<Msg> = {}) =>
  h.div
    .class(cn("pb-[var(--keyboard-inset,0px)] transition-[padding] duration-150", options.class))
    .onMount(track(options))
```

```ts
import { KeyboardBar, KeyboardInset } from "#ui/virtual-keyboard"
```

## Usage

Viewport sizes as three kinds of browser report them, fed to the pure step function. No device needed.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { VirtualKeyboard } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"

const Behavior = Schema.Literals(["overlays", "resizes", "catching-up"])

type Behavior = typeof Behavior.Type

const VirtualKeyboardSimulatorMessage = UiSchema.TaggedEnum({
  PressedBehavior: { behavior: Behavior },
  PressedToggleFocus: {},
  UpdatedKeyboardHeight: { value: Schema.String }
})

const behaviors: Record<Behavior, { readonly label: string; readonly note: string }> = {
  overlays: {
    label: "Overlays the page",
    note: "iOS Safari: only the visual viewport shrinks, so fixed content needs the inset."
  },
  resizes: {
    label: "Resizes the page",
    note: "Android Chrome: the layout viewport shrinks with the keyboard, so the inset is 0."
  },
  "catching-up": {
    label: "Still resizing",
    note: "The layout viewport follows the keyboard and hasn't caught up yet: resizing is true."
  }
}

const screen = { width: 360, height: 640 }

const closed: VirtualKeyboard.Sample = {
  layoutWidth: screen.width,
  layoutHeight: screen.height,
  visualHeight: screen.height,
  visualTop: 0,
  scale: 1,
  smallViewportHeight: screen.height,
  android: false,
  focused: false
}

// The sizes each kind of browser reports with a keyboard `keyboard` pixels tall.
const sampleOf = (behavior: Behavior, keyboard: number, focused: boolean): VirtualKeyboard.Sample => {
  if (!focused) return closed
  const visualHeight = screen.height - keyboard
  switch (behavior) {
    case "overlays":
      return { ...closed, focused, visualHeight }
    case "resizes":
      return {
        ...closed,
        focused,
        android: true,
        visualHeight,
        layoutHeight: visualHeight,
        smallViewportHeight: visualHeight
      }
    case "catching-up":
      return {
        ...closed,
        focused,
        android: true,
        visualHeight,
        layoutHeight: screen.height - keyboard / 2,
        smallViewportHeight: visualHeight
      }
  }
}

const percent = (pixels: number): string => `${(pixels / screen.height) * 100}%`

export const VirtualKeyboardSimulator = Html.component({
  name: "VirtualKeyboardSimulator",
  model: Schema.Struct({ behavior: Behavior, focused: Schema.Boolean, keyboard: Schema.Number }),
  message: VirtualKeyboardSimulatorMessage
}).make({
  init: () => ({ behavior: "overlays", focused: true, keyboard: 280 }),
  update: {
    PressedBehavior: ($, { behavior }) => $.evolve({ behavior }),
    PressedToggleFocus: ($) => $.evolve({ focused: (focused) => !focused }),
    UpdatedKeyboardHeight: ($, { value }) => $.evolve({ keyboard: Number(value) })
  },
  view: (h, model) => {
    const sample = sampleOf(model.behavior, model.keyboard, model.focused)
    // `step` is pure: the state before the keyboard, and one sample of sizes.
    const { band } = VirtualKeyboard.step(VirtualKeyboard.initialState(closed), sample)
    return h.div.class("flex flex-wrap items-start justify-center gap-8").children(
      h.div
        .class("relative h-96 w-54 shrink-0 overflow-hidden rounded-[1.75rem] border-4 border-foreground/80 bg-background")
        .attr("aria-hidden", "true")
        .children(
          h.div
            .class("absolute inset-x-0 top-0 border-b border-dashed border-input transition-[height] duration-150")
            .style({ height: percent(sample.layoutHeight) })
            .children(
              h.div
                .class("absolute inset-x-2 mb-2 rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-muted-foreground shadow-sm transition-[bottom] duration-150")
                .style({ bottom: percent(band?.inset ?? 0) })
                .children("Message")
            ),
          band !== null &&
            h.div
              .class("absolute inset-x-0 flex items-start justify-center bg-brand-wash/70 pt-3 text-[11px] font-medium text-muted-foreground transition-[top,height] duration-150")
              .style({ top: percent(band.top), height: percent(band.bottom - band.top) })
              .children("visible band"),
          h.div
            .class("absolute inset-x-0 bottom-0 flex items-center justify-center overflow-hidden bg-muted text-[11px] text-muted-foreground transition-[height] duration-150")
            .style({ height: percent(model.focused ? model.keyboard : 0) })
            .children("keyboard")
        ),
      h.div.class("flex w-72 flex-col items-start gap-3").children(
        h.div.class("flex flex-col items-start gap-1").attrs({ role: "group", "aria-label": "Browser" }).children(
          Behavior.literals.map((behavior) =>
            Button(h, {
              variant: behavior === model.behavior ? "secondary" : "ghost",
              size: "sm",
              onPress: VirtualKeyboardSimulatorMessage.PressedBehavior({ behavior })
            }).attr("aria-pressed", String(behavior === model.behavior)).children(behaviors[behavior].label)
          )
        ),
        h.p.class("min-h-10 text-xs text-muted-foreground").children(behaviors[model.behavior].note),
        h.label.class("grid w-full gap-1.5 text-xs text-muted-foreground tabular-nums").children(
          `Keyboard height ${model.keyboard}px`,
          h.input
            .class("accent-brand")
            .attrs({ type: "range", min: "80", max: "400", step: "10" })
            .value(String(model.keyboard))
            .on("input", ({ value }) => VirtualKeyboardSimulatorMessage.UpdatedKeyboardHeight({ value }))
        ),
        Button(h, { variant: "outline", size: "sm", onPress: VirtualKeyboardSimulatorMessage.PressedToggleFocus() })
          .children(model.focused ? "Blur the text field" : "Focus the text field"),
        h.pre.class("w-full rounded-md bg-muted px-3 py-2 font-mono text-xs leading-relaxed").children(
          band === null
            ? "band: null"
            : `band: {\n  top: ${band.top},\n  bottom: ${band.bottom},\n  inset: ${band.inset},\n  resizing: ${band.resizing}\n}`
        )
      )
    )
  }
})
```

## Examples

### A bar above the keyboard

KeyboardBar is fixed to the bottom and reads --keyboard-inset, which the TrackKeyboard mount writes on it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { KeyboardBar } from "#ui/virtual-keyboard"

const VirtualKeyboardComposerMessage = UiSchema.TaggedEnum({
  PressedOpen: {},
  PressedClose: {},
  UpdatedDraft: { value: Schema.String },
  SubmittedDraft: {}
})

export const VirtualKeyboardComposer = Html.component({
  name: "VirtualKeyboardComposer",
  model: Schema.Struct({ open: Schema.Boolean, draft: Schema.String, sent: Schema.Array(Schema.String) }),
  message: VirtualKeyboardComposerMessage
}).make({
  init: () => ({ open: false, draft: "", sent: [] }),
  update: {
    PressedOpen: ($) => $.evolve({ open: true }),
    PressedClose: ($) => $.evolve({ open: false }),
    UpdatedDraft: ($, { value }) => $.evolve({ draft: value }),
    SubmittedDraft: ($) =>
      $.model.draft.trim() === ""
        ? $.model
        : $.evolve({ sent: (sent) => [...sent, $.model.draft.trim()], draft: "" })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3").children(
      Button(h, { variant: "outline", onPress: VirtualKeyboardComposerMessage.PressedOpen() }).children(
        "Open the composer"
      ),
      h.p.class("text-xs text-muted-foreground").children(
        model.sent.length === 0
          ? "On a phone, the bar stays above the keyboard while you type."
          : `Sent: ${model.sent.join(", ")}`
      ),
      // The bar's mount writes --keyboard-inset while a keyboard is up, and
      // its `bottom` reads it.
      model.open &&
        KeyboardBar(h).children(
          h.form
            .class("mx-auto flex w-full max-w-xl items-center gap-2")
            .on("submit", VirtualKeyboardComposerMessage.SubmittedDraft())
            .children(
              h.input
                .class("h-8 min-w-0 flex-1 rounded-md border border-input bg-background px-3 text-[13px]")
                .attrs({ placeholder: "Write a message", "aria-label": "Message", enterkeyhint: "send" })
                .value(model.draft)
                .on("input", ({ value }) => VirtualKeyboardComposerMessage.UpdatedDraft({ value })),
              Button(h, { size: "sm", props: { type: "submit" } }).children("Send"),
              Button(h, { variant: "ghost", size: "sm", onPress: VirtualKeyboardComposerMessage.PressedClose() })
                .children("Close")
            )
        )
    )
})
```

### Live readout

A mount of your own over the watch Stream reports each band to the Model. On a desktop it stays closed.

```ts
import { Mount, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { VirtualKeyboard } from "@effect/ui-kit"
import { Schema } from "effect"

const VirtualKeyboardWatchMessage = UiSchema.TaggedEnum({
  ChangedBand: { band: Schema.NullOr(VirtualKeyboard.Band) }
})

// `watch` writes nothing, so a mount of your own decides what a band does.
const WatchKeyboard = Mount.makeStream(
  "WatchKeyboard",
  { args: {} },
  (node: HTMLElement) => VirtualKeyboard.watch(node)
)

export const VirtualKeyboardWatch = Html.component({
  name: "VirtualKeyboardWatch",
  model: Schema.Struct({ band: Schema.NullOr(VirtualKeyboard.Band), reports: Schema.Number }),
  message: VirtualKeyboardWatchMessage,
  // A band is a measurement: after Back the mount reports it again.
  restore: (model) => ({ ...model, band: null })
}).make({
  init: () => ({ band: null, reports: 0 }),
  update: {
    ChangedBand: ($, { band }) => $.evolve({ band, reports: (reports) => reports + 1 })
  },
  view: (h, model) => {
    const facts = [
      ["Keyboard", model.band === null ? "Closed" : "Up"],
      ["Visible band", model.band === null ? "–" : `${model.band.top}px to ${model.band.bottom}px`],
      ["Inset", model.band === null ? "–" : `${model.band.inset}px`],
      ["Resizing", model.band === null ? "–" : String(model.band.resizing)],
      ["Reports", String(model.reports)]
    ] as const
    return h.div
      .class("flex w-full max-w-xs flex-col gap-3")
      .onMount(WatchKeyboard().pipe(Mount.map((band) => VirtualKeyboardWatchMessage.ChangedBand({ band }))))
      .children(
        h.input
          .class("h-8 rounded-md border border-input bg-background px-3 text-[13px]")
          .attrs({ placeholder: "Focus me on a touch device", "aria-label": "Text field" }),
        h.dl.class("grid grid-cols-[auto_1fr] gap-x-6 gap-y-1.5 rounded-md border px-3.5 py-3 text-[13px]").children(
          facts.flatMap(([name, value]) => [
            h.dt.key(`${name}-name`).class("text-muted-foreground").children(name),
            h.dd.key(`${name}-value`).class("text-right font-mono text-xs tabular-nums").children(value)
          ])
        )
      )
  }
})
```

### Which controls open a keyboard

textFieldOf tells a text field from every other control. Tab through them.

```ts
import { Mount, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { VirtualKeyboard } from "@effect/ui-kit"
import { Schema, Stream } from "effect"
import { Button } from "#ui/button"

const Focused = Schema.Struct({ name: Schema.String, opensKeyboard: Schema.Boolean })

const VirtualKeyboardTextFieldMessage = UiSchema.TaggedEnum({
  FocusedControl: { focused: Focused }
})

// Handlers get plain data, never the element, so "is this a text field?"
// is asked in a mount, which has the node.
const TrackFocusedControl = Mount.makeStream(
  "TrackFocusedControl",
  { args: {} },
  (node: HTMLElement) =>
    Stream.fromEventListener<FocusEvent>(node, "focusin").pipe(
      Stream.map(({ target }) => ({
        name: target instanceof HTMLElement ? target.getAttribute("aria-label") ?? target.tagName.toLowerCase() : "",
        opensKeyboard: VirtualKeyboard.textFieldOf(target) !== null
      }))
    )
)

const field = "h-8 min-w-0 rounded-md border border-input bg-background px-3 text-[13px]"

export const VirtualKeyboardTextField = Html.component({
  name: "VirtualKeyboardTextField",
  model: Schema.Struct({ focused: Schema.NullOr(Focused) }),
  message: VirtualKeyboardTextFieldMessage
}).make({
  init: () => ({ focused: null }),
  update: {
    FocusedControl: ($, { focused }) => $.evolve({ focused })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-md flex-col gap-4").children(
      h.div
        .class("grid grid-cols-2 items-center gap-2.5")
        .onMount(
          TrackFocusedControl().pipe(
            Mount.map((focused) => VirtualKeyboardTextFieldMessage.FocusedControl({ focused }))
          )
        )
        .children(
          h.input.class(field).attrs({ "aria-label": "Text input", placeholder: "Text" }),
          h.input.class(field).attrs({ type: "email", "aria-label": "Email input", placeholder: "Email" }),
          h.textarea.class(`${field} resize-none py-1.5`).attrs({
            "aria-label": "Textarea",
            placeholder: "Textarea",
            rows: "1"
          }),
          h.div
            .class(`${field} flex items-center`)
            .attrs({ contenteditable: "true", role: "textbox", "aria-label": "Editable element" })
            .children("Editable"),
          h.input.class(field).attrs({ type: "date", "aria-label": "Date input" }),
          h.input.class("accent-brand").attrs({ type: "range", "aria-label": "Range input" }),
          h.label.class("flex items-center gap-2 text-[13px]").children(
            h.input.class("accent-brand").attrs({ type: "checkbox", "aria-label": "Checkbox" }),
            "Checkbox"
          ),
          Button(h, { variant: "outline", size: "sm" }).attr("aria-label", "Button").children("Button")
        ),
      h.p.class("rounded-md bg-muted px-3 py-2 text-[13px]").attr("aria-live", "polite").children(
        model.focused === null
          ? "Focus a control."
          : `${model.focused.name}: ${model.focused.opensKeyboard ? "opens the keyboard" : "no keyboard"}`
      )
    )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `step(state, sample)` | Pure: one Sample of the viewport's sizes in, the next State and the visible Band (or null) out. |
| `initialState(layout)` | The State to start from, taken from the layout viewport before any keyboard is up. |
| `watch(node)` | A Stream of the band for the node's document: when it starts, then each time it changes. |
| `TrackKeyboard()` | A stream mount that writes --keyboard-inset on its node and reports each band. |
| `textFieldOf(target)` | The text field a target stands for, or null: the fields whose focus opens the keyboard. |
| `Band` | Schema of { top, bottom, inset, resizing }: the part of the screen left visible. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `band.top / band.bottom` | `number` | The band's edges, in pixels from the top of the layout viewport. |
| `band.inset` | `number` | The height below bottom that the keyboard covers. 0 while the layout viewport follows the keyboard. |
| `band.resizing` | `boolean` | The layout viewport follows the keyboard and hasn't caught up, so the page is still moving. |
| `sample.layoutWidth / layoutHeight` | `number` | The layout viewport: clientWidth and innerHeight. |
| `sample.visualHeight / visualTop / scale` | `number` | visualViewport's height, offsetTop and scale. |
| `sample.smallViewportHeight` | `number` | The height of 100svh. |
| `sample.android` | `boolean` | The browser runs on Android, where the keyboard can resize the page. |
| `sample.focused` | `boolean` | A text field has focus. Without one there is never a band. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `--keyboard-inset` | Written inline by TrackKeyboard on its node while a keyboard is up, and removed otherwise: read it as var(--keyboard-inset, 0px). |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
