Skip to content

Focus Zones

Manage keyboard navigation across multiple UI zones with useFocusZone. Requires KeyboardProvider.

Manage keyboard navigation across multiple UI zones (e.g., sidebar + content + preview). Handles zone transitions via arrow keys and Tab cycling. Requires KeyboardProvider — not available in copy mode.

Info:

For the complete API reference, see the @diffgazer/keys documentation.


useFocusZone

tsx
import { useFocusZone, useKey } from "@diffgazer/keys"

function Layout() {
  const { isZone, getKeyOptions, getZoneProps } = useFocusZone({
    initial: "sidebar",
    zones: ["sidebar", "content", "preview"] as const,
    tabCycle: ["sidebar", "content", "preview"] as const,
    transitions: ({ zone, key }) => {
      if (zone === "sidebar" && key === "ArrowRight") return "content"
      if (zone === "content" && key === "ArrowLeft") return "sidebar"
      if (zone === "content" && key === "ArrowRight") return "preview"
      return null
    },
  })

  // Zone-specific bindings
  useKey("Enter", () => openItem(), getKeyOptions("sidebar"))
  useKey("Enter", () => editContent(), getKeyOptions("content"))

  return (
    <div>
      <aside
        {...getZoneProps("sidebar")}
        className={isZone("sidebar") ? "ring-1 ring-white" : ""}
      >
        Sidebar
      </aside>
      <main
        {...getZoneProps("content")}
        className={isZone("content") ? "ring-1 ring-white" : ""}
      >
        Content
      </main>
      <section
        {...getZoneProps("preview")}
        className={isZone("preview") ? "ring-1 ring-white" : ""}
      >
        Preview
      </section>
    </div>
  )
}

Return value

PropertyTypeDescription
zoneTCurrent active zone
setZone(zone: T) => voidSet zone programmatically
isZone(...zones: T[]) => booleanCheck if current zone matches
getKeyOptions(zone: T, extra?) => UseKeyOptionsCreate zone-scoped options for useKey
getZoneProps(zone: T) => { "data-focused": true | undefined }Add the active-zone data attribute to a zone container

With @diffgazer/ui components

See Patterns for integration examples with Menu, Dialog, CommandPalette, and Tabs, including a multi-zone layout.