HextaUI

Token input (UI SDK): Custom codec

A codec turns tokens into text and back, here as <@id>. With copy="label", copying writes what people read, and pasting back still restores the tokens.

Ping ​@hollis mention​ and ​@ines mention​ about the launch

Ping <@hollis> and <@ines> about the launch

"use client"

import * as React from "react"

import {
  fromText,
  TokenInput,
  TokenInputEditor,
  toText,
  type TokenCodec,
} from "@/components/ui/ui-sdk-token-input"

const chat: TokenCodec = {
  format: (token) => "<@" + token.value + ">",
  parse: (text) =>
    text.split(/(<@[\w.-]+>)/).map((part) => {
      const id = /^<@([\w.-]+)>$/.exec(part)?.[1]
      return id ? { type: "mention", value: id, label: "@" + id } : part
    }),
}

const source = "Ping <@hollis> and <@ines> about the launch"

function UiSdkTokenInputCodec() {
  const [text, setText] = React.useState(source)

  return (
    <div className="flex w-full max-w-md flex-col gap-2">
      <TokenInput
        codec={chat}
        copy="label"
        defaultValue={fromText(source, chat)}
        onValueChange={(value) => setText(toText(value, chat))}
      >
        <TokenInputEditor aria-label="Message" />
      </TokenInput>
      <p className="font-mono text-xs wrap-anywhere text-muted-foreground">
        {text}
      </p>
    </div>
  )
}

export { UiSdkTokenInputCodec }

This adds the example as components/examples/ui-sdk-token-input/codec.tsx, together with the Token input component and the HextaUI theme tokens it needs.

pnpm dlx shadcn@latest add https://hextaui.com/r/ui-sdk-token-input-codec.json

To add only the component, follow the Token input installation.

Props in this example

The Token input props this example sets, from the API reference.

PropTypeDefault
defaultValue
TokenInputValue–
onValueChangeRuns on typing, pastes, menus, undo and controller calls. details lists the reason and any removed tokens.
(value, details) => void–
copy
"codec" | "label""codec"
codec
TokenCodec–

Every prop is in the Token input API reference.

See them all, with keyboard support and accessibility notes, on the Token input page.