iOS Safari: only the visual viewport shrinks, so fixed content needs the inset.

band: {
  top: 0,
  bottom: 360,
  inset: 280,
  resizing: false
}

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/virtual-keyboard.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))
    
  3. Import it

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

Usage

Simulator.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.

On a phone, the bar stays above the keyboard while you type.

Live readout

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

Keyboard
Closed
Visible band
–
Inset
–
Resizing
–
Reports
0

Which controls open a keyboard

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

Editable

Focus a control.

Anatomy

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

PartDescription
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.
BandSchema of { top, bottom, inset, resizing }: the part of the screen left visible.

API reference

Props

PropTypeDescription
band.top / band.bottomnumberThe band's edges, in pixels from the top of the layout viewport.
band.insetnumberThe height below bottom that the keyboard covers. 0 while the layout viewport follows the keyboard.
band.resizingbooleanThe layout viewport follows the keyboard and hasn't caught up, so the page is still moving.
sample.layoutWidth / layoutHeightnumberThe layout viewport: clientWidth and innerHeight.
sample.visualHeight / visualTop / scalenumbervisualViewport's height, offsetTop and scale.
sample.smallViewportHeightnumberThe height of 100svh.
sample.androidbooleanThe browser runs on Android, where the keyboard can resize the page.
sample.focusedbooleanA text field has focus. Without one there is never a band.

Data attributes

AttributeDescription
--keyboard-insetWritten inline by TrackKeyboard on its node while a keyboard is up, and removed otherwise: read it as var(--keyboard-inset, 0px).

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.