Building blocks for a chat app
Whole sections, already assembled. A block is an arrangement of components, not new markup: the parts are the ones documented under Components, and restyling one is still a matter of overriding a token. Install a block and you get every component it is built from.
Chat window
A whole channel view: header, scrolling message list and composer, composed from the registry.
"use client"
import * as React from "react"
import { Avatar } from "@/registry/bases/newt/ui/avatar"
import {
ChannelHeader,
ChannelHeaderDivider,
ChannelHeaderIcon,
ChannelHeaderInfo,
ChannelHeaderName,
ChannelHeaderTopic,
} from "@/registry/bases/newt/ui/channel-header"
import { Chat, ChatBody, ChatFooter } from "@/registry/bases/newt/ui/chat"
import { MessageComposer } from "@/registry/bases/newt/ui/message-composer"
import {
MessageGroup,
MessageGroupAuthor,
MessageGroupAvatar,
MessageGroupBody,
MessageGroupContent,
MessageGroupHeader,
MessageGroupTime,
} from "@/registry/bases/newt/ui/message-group"
import { MessageList } from "@/registry/bases/newt/ui/message-list"
/*
* A whole channel view: header, scrolling message list, composer. Everything
* here is composed from registry components — the block is the arrangement,
* not new markup, so restyling it is still a matter of overriding a token.
*
* `messages` is deliberately a plain array. A block does not know your data
* layer; map onto this shape at the edge of it.
*/
export interface ChatMessage {
id: string
author: string
/** The initials the avatar shows. */
initials: string
body: string
sentAt: string
/** Rendered timestamp; the ISO value goes in `sentAt`. */
displayTime: string
}
export interface ChatWindowProps extends React.ComponentProps<"div"> {
channelName: string
topic?: string
messages: readonly ChatMessage[]
onSend?: (message: string) => void
}
export function ChatWindow({
channelName,
topic,
messages,
onSend,
className,
...props
}: ChatWindowProps) {
const [value, setValue] = React.useState("")
return (
<div className={className} {...props}>
<ChannelHeader>
<ChannelHeaderInfo>
<ChannelHeaderIcon />
<ChannelHeaderName>{channelName}</ChannelHeaderName>
{topic && (
<>
<ChannelHeaderDivider />
<ChannelHeaderTopic>{topic}</ChannelHeaderTopic>
</>
)}
</ChannelHeaderInfo>
</ChannelHeader>
<Chat aria-label={`#${channelName} chat`} className="h-96">
<ChatBody focusable viewportLabel={`#${channelName} messages`}>
<MessageList label={`Messages in #${channelName}`}>
{messages.map((message) => (
<MessageGroup key={message.id}>
<MessageGroupAvatar>
<Avatar>{message.initials}</Avatar>
</MessageGroupAvatar>
<MessageGroupBody>
<MessageGroupHeader>
<MessageGroupAuthor>{message.author}</MessageGroupAuthor>
<MessageGroupTime dateTime={message.sentAt}>
{message.displayTime}
</MessageGroupTime>
</MessageGroupHeader>
<MessageGroupContent>{message.body}</MessageGroupContent>
</MessageGroupBody>
</MessageGroup>
))}
</MessageList>
</ChatBody>
<ChatFooter>
<MessageComposer
channelName={channelName}
value={value}
onValueChange={setValue}
onSubmit={(message) => {
onSend?.(message)
setValue("")
}}
/>
</ChatFooter>
</Chat>
</div>
)
}<script setup lang="ts">
import { ref } from "vue"
import { Avatar } from "~~/registry/bases/newt/ui/avatar"
import {
ChannelHeader,
ChannelHeaderDivider,
ChannelHeaderIcon,
ChannelHeaderInfo,
ChannelHeaderName,
ChannelHeaderTopic,
} from "~~/registry/bases/newt/ui/channel-header"
import { Chat, ChatBody, ChatFooter } from "~~/registry/bases/newt/ui/chat"
import { MessageComposer } from "~~/registry/bases/newt/ui/message-composer"
import {
MessageGroup,
MessageGroupAuthor,
MessageGroupAvatar,
MessageGroupBody,
MessageGroupContent,
MessageGroupHeader,
MessageGroupTime,
} from "~~/registry/bases/newt/ui/message-group"
import { MessageList } from "~~/registry/bases/newt/ui/message-list"
import type { ChatMessage } from "./types"
/*
* A whole channel view: header, scrolling message list, composer. Everything
* here is composed from registry components — the block is the arrangement,
* not new markup, so restyling it is still a matter of overriding a token.
*/
const props = defineProps<{
channelName: string
topic?: string
messages: readonly ChatMessage[]
}>()
const emit = defineEmits<{ send: [message: string] }>()
const value = ref("")
function submit(message: string) {
emit("send", message)
value.value = ""
}
</script>
<template>
<div>
<ChannelHeader>
<ChannelHeaderInfo>
<ChannelHeaderIcon />
<ChannelHeaderName>{{ props.channelName }}</ChannelHeaderName>
<template v-if="props.topic">
<ChannelHeaderDivider />
<ChannelHeaderTopic>{{ props.topic }}</ChannelHeaderTopic>
</template>
</ChannelHeaderInfo>
</ChannelHeader>
<Chat :aria-label="`#${props.channelName} chat`" class="h-96">
<ChatBody focusable :viewport-label="`#${props.channelName} messages`">
<MessageList :label="`Messages in #${props.channelName}`">
<MessageGroup v-for="message in props.messages" :key="message.id">
<MessageGroupAvatar>
<Avatar>{{ message.initials }}</Avatar>
</MessageGroupAvatar>
<MessageGroupBody>
<MessageGroupHeader>
<MessageGroupAuthor>{{ message.author }}</MessageGroupAuthor>
<MessageGroupTime :date-time="message.sentAt">
{{ message.displayTime }}
</MessageGroupTime>
</MessageGroupHeader>
<MessageGroupContent>{{ message.body }}</MessageGroupContent>
</MessageGroupBody>
</MessageGroup>
</MessageList>
</ChatBody>
<ChatFooter>
<MessageComposer
:channel-name="props.channelName"
v-model:value="value"
@submit="submit"
/>
</ChatFooter>
</Chat>
</div>
</template>/*
* `messages` is deliberately a plain array. A block does not know your data
* layer; map onto this shape at the edge of it.
*/
export interface ChatMessage {
id: string
author: string
/** The initials the avatar shows. */
initials: string
body: string
/** ISO timestamp, for the `<time>` element. */
sentAt: string
/** What the reader sees. */
displayTime: string
}export { default as ChatWindow } from "./ChatWindow.vue"
export type { ChatMessage } from "./types"Built fromChannel HeaderChatMessage ListMessage GroupMessage ComposerAvatar
AI chat
A conversation with an assistant: starter prompts, markdown replies, a typing state and the composer, composed from the registry.
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { Avatar } from "@/registry/bases/newt/ui/avatar"
import { Button } from "@/registry/bases/newt/ui/button"
import { Chat, ChatBody, ChatFooter } from "@/registry/bases/newt/ui/chat"
import { Markdown } from "@/registry/bases/newt/ui/markdown"
import { MessageComposer } from "@/registry/bases/newt/ui/message-composer"
import {
MessageGroup,
MessageGroupAuthor,
MessageGroupAvatar,
MessageGroupBody,
MessageGroupBotTag,
MessageGroupContent,
MessageGroupHeader,
MessageGroupTime,
} from "@/registry/bases/newt/ui/message-group"
import { MessageList } from "@/registry/bases/newt/ui/message-list"
import { TypingIndicator } from "@/registry/bases/newt/ui/typing-indicator"
/*
* A conversation with an assistant: who you are talking to, the exchange so
* far, and the composer. Before the first message the list gives way to a
* greeting and a few prompts to start from; while a reply is on its way the
* assistant is shown typing.
*
* The block knows nothing about a model or a transport. It draws `messages`
* and reports what was sent; calling the model, streaming the reply into the
* array and setting `pending` are the application's.
*/
export interface AiChatMessage {
id: string
role: "user" | "assistant"
/** An assistant's body is rendered as chat markdown; a user's as written. */
body: string
sentAt: string
/** Rendered timestamp; the ISO value goes in `sentAt`. */
displayTime: string
}
export interface AiChatProps extends React.ComponentProps<"div"> {
assistantName: string
/** Said quietly beside the name: the model, or what the assistant is for. */
caption?: string
userName?: string
messages: readonly AiChatMessage[]
/** A reply is being written: the assistant is shown typing. */
pending?: boolean
/** The line above the prompts, before the first message. */
greeting?: string
/** Prompts offered before the first message; choosing one sends it. */
suggestions?: readonly string[]
onSend?: (message: string) => void
/**
* Called when the composer's add button is pressed. The composer always
* draws that button, so without this it does nothing: open your own picker.
*/
onAttach?: () => void
}
function initial(name: string): string {
return name.trim().charAt(0).toUpperCase()
}
export function AiChat({
assistantName,
caption,
userName = "You",
messages,
pending = false,
greeting = "How can I help?",
suggestions = [],
onSend,
onAttach,
className,
...props
}: AiChatProps) {
const [value, setValue] = React.useState("")
const empty = messages.length === 0 && !pending
/*
* New text is followed while the reader is at the bottom and left alone once
* they have scrolled up to read something older. Sending always follows.
*/
const body = React.useRef<HTMLDivElement>(null)
const following = React.useRef(true)
React.useEffect(() => {
const element = body.current
if (following.current && element) element.scrollTop = element.scrollHeight
}, [messages, pending])
return (
<div
className={cn(
"overflow-hidden rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-elevated",
className
)}
{...props}
>
<header className="flex items-center gap-3 border-b border-newt-border px-4 py-3">
<Avatar>{initial(assistantName)}</Avatar>
<div className="flex min-w-0 flex-col">
<span className="flex items-center gap-1.5 font-display text-[15px] font-semibold text-newt-text-primary">
{assistantName}
<MessageGroupBotTag aria-label="AI assistant">
AI
</MessageGroupBotTag>
</span>
{caption && (
<span className="truncate text-xs text-newt-text-muted">
{caption}
</span>
)}
</div>
</header>
<Chat aria-label={`Conversation with ${assistantName}`} className="h-96">
<ChatBody
ref={body}
focusable
viewportLabel={`Messages with ${assistantName}`}
onScroll={(event) => {
const { scrollHeight, scrollTop, clientHeight } =
event.currentTarget
following.current = scrollHeight - scrollTop - clientHeight < 48
}}
>
{empty ? (
<div className="flex flex-1 flex-col items-center justify-center gap-4 px-4 py-8 text-center">
<p className="font-display text-xl font-semibold text-newt-text-primary">
{greeting}
</p>
{suggestions.length > 0 && (
<div className="flex max-w-md flex-wrap justify-center gap-2">
{suggestions.map((suggestion) => (
<Button
key={suggestion}
variant="secondary"
size="sm"
className="border border-newt-border"
onClick={() => onSend?.(suggestion)}
>
{suggestion}
</Button>
))}
</div>
)}
</div>
) : (
<MessageList label={`Messages with ${assistantName}`}>
{messages.map((message) => {
const fromAssistant = message.role === "assistant"
const author = fromAssistant ? assistantName : userName
return (
<MessageGroup key={message.id}>
<MessageGroupAvatar>
<Avatar>{initial(author)}</Avatar>
</MessageGroupAvatar>
<MessageGroupBody>
<MessageGroupHeader>
<MessageGroupAuthor>{author}</MessageGroupAuthor>
{fromAssistant && (
<MessageGroupBotTag aria-label="AI assistant">
AI
</MessageGroupBotTag>
)}
<MessageGroupTime dateTime={message.sentAt}>
{message.displayTime}
</MessageGroupTime>
</MessageGroupHeader>
<MessageGroupContent>
{fromAssistant ? (
<Markdown content={message.body} />
) : (
<span className="whitespace-pre-wrap">
{message.body}
</span>
)}
</MessageGroupContent>
</MessageGroupBody>
</MessageGroup>
)
})}
</MessageList>
)}
</ChatBody>
<ChatFooter>
{/*
* The status region is always there, so that its text appearing is
* what a screen reader announces; mounted together with its text, a
* live region is often missed.
*/}
<div role="status" className="flex h-6 items-center px-1">
{pending && (
<TypingIndicator role="none" aria-label={undefined}>
{assistantName} is writing…
</TypingIndicator>
)}
</div>
<MessageComposer
channelName={assistantName}
aria-label={`Message ${assistantName}`}
onAdd={onAttach}
placeholder={`Ask ${assistantName} anything`}
value={value}
onValueChange={setValue}
onSubmit={(message) => {
following.current = true
onSend?.(message)
setValue("")
}}
/>
</ChatFooter>
</Chat>
</div>
)
}<script setup lang="ts">
import { computed, nextTick, ref, watch, type HTMLAttributes } from "vue"
import { Avatar } from "~~/registry/bases/newt/ui/avatar"
import { Button } from "~~/registry/bases/newt/ui/button"
import { Chat, ChatBody, ChatFooter } from "~~/registry/bases/newt/ui/chat"
import { Markdown } from "~~/registry/bases/newt/ui/markdown"
import { MessageComposer } from "~~/registry/bases/newt/ui/message-composer"
import {
MessageGroup,
MessageGroupAuthor,
MessageGroupAvatar,
MessageGroupBody,
MessageGroupBotTag,
MessageGroupContent,
MessageGroupHeader,
MessageGroupTime,
} from "~~/registry/bases/newt/ui/message-group"
import { MessageList } from "~~/registry/bases/newt/ui/message-list"
import { TypingIndicator } from "~~/registry/bases/newt/ui/typing-indicator"
import { cn } from "@/lib/utils"
import type { AiChatMessage } from "./types"
/*
* A conversation with an assistant: who you are talking to, the exchange so
* far, and the composer. Before the first message the list gives way to a
* greeting and a few prompts to start from; while a reply is on its way the
* assistant is shown typing.
*
* The block knows nothing about a model or a transport. It draws `messages`
* and reports what was sent; calling the model, streaming the reply into the
* array and setting `pending` are the application's.
*/
const props = withDefaults(
defineProps<{
class?: HTMLAttributes["class"]
assistantName: string
/** Said quietly beside the name: the model, or what the assistant is for. */
caption?: string
userName?: string
messages: readonly AiChatMessage[]
/** A reply is being written: the assistant is shown typing. */
pending?: boolean
/** The line above the prompts, before the first message. */
greeting?: string
/** Prompts offered before the first message; choosing one sends it. */
suggestions?: readonly string[]
}>(),
{
userName: "You",
pending: false,
greeting: "How can I help?",
suggestions: () => [],
}
)
/** `attach`: the composer's add button was pressed. It always draws that button, so listen for it to open your own picker. */
const emit = defineEmits<{ send: [message: string]; attach: [] }>()
const value = ref("")
const empty = computed(() => props.messages.length === 0 && !props.pending)
function initial(name: string): string {
return name.trim().charAt(0).toUpperCase()
}
function authorOf(message: AiChatMessage): string {
return message.role === "assistant" ? props.assistantName : props.userName
}
/*
* New text is followed while the reader is at the bottom and left alone once
* they have scrolled up to read something older. Sending always follows.
*/
const body = ref<InstanceType<typeof ChatBody> | null>(null)
let following = true
function onScroll(event: Event) {
const element = event.currentTarget
if (element instanceof HTMLElement) {
following =
element.scrollHeight - element.scrollTop - element.clientHeight < 48
}
}
watch(
() => [props.messages, props.pending],
async () => {
if (!following) return
await nextTick()
const element = body.value?.$el
if (element instanceof HTMLElement) element.scrollTop = element.scrollHeight
},
{ deep: true }
)
function submit(message: string) {
following = true
emit("send", message)
value.value = ""
}
</script>
<template>
<div
:class="
cn(
'overflow-hidden rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-elevated',
props.class
)
"
>
<header
class="flex items-center gap-3 border-b border-newt-border px-4 py-3"
>
<Avatar>{{ initial(props.assistantName) }}</Avatar>
<div class="flex min-w-0 flex-col">
<span
class="flex items-center gap-1.5 font-display text-[15px] font-semibold text-newt-text-primary"
>
{{ props.assistantName }}
<MessageGroupBotTag aria-label="AI assistant">AI</MessageGroupBotTag>
</span>
<span
v-if="props.caption"
class="truncate text-xs text-newt-text-muted"
>
{{ props.caption }}
</span>
</div>
</header>
<Chat :aria-label="`Conversation with ${props.assistantName}`" class="h-96">
<ChatBody
ref="body"
focusable
:viewport-label="`Messages with ${props.assistantName}`"
@scroll="onScroll"
>
<div
v-if="empty"
class="flex flex-1 flex-col items-center justify-center gap-4 px-4 py-8 text-center"
>
<p class="font-display text-xl font-semibold text-newt-text-primary">
{{ props.greeting }}
</p>
<div
v-if="props.suggestions.length > 0"
class="flex max-w-md flex-wrap justify-center gap-2"
>
<Button
v-for="suggestion in props.suggestions"
:key="suggestion"
variant="secondary"
size="sm"
class="border border-newt-border"
@click="emit('send', suggestion)"
>
{{ suggestion }}
</Button>
</div>
</div>
<MessageList v-else :label="`Messages with ${props.assistantName}`">
<MessageGroup v-for="message in props.messages" :key="message.id">
<MessageGroupAvatar>
<Avatar>{{ initial(authorOf(message)) }}</Avatar>
</MessageGroupAvatar>
<MessageGroupBody>
<MessageGroupHeader>
<MessageGroupAuthor>{{ authorOf(message) }}</MessageGroupAuthor>
<MessageGroupBotTag
v-if="message.role === 'assistant'"
aria-label="AI assistant"
>
AI
</MessageGroupBotTag>
<MessageGroupTime :datetime="message.sentAt">
{{ message.displayTime }}
</MessageGroupTime>
</MessageGroupHeader>
<MessageGroupContent>
<Markdown
v-if="message.role === 'assistant'"
:content="message.body"
/>
<span v-else class="whitespace-pre-wrap">{{
message.body
}}</span>
</MessageGroupContent>
</MessageGroupBody>
</MessageGroup>
</MessageList>
</ChatBody>
<ChatFooter>
<!--
The status region is always there, so that its text appearing is what
a screen reader announces; mounted together with its text, a live
region is often missed.
-->
<div role="status" class="flex h-6 items-center px-1">
<TypingIndicator
v-if="props.pending"
role="none"
:aria-label="undefined"
>
{{ props.assistantName }} is writing…
</TypingIndicator>
</div>
<MessageComposer
v-model="value"
:channel-name="props.assistantName"
:aria-label="`Message ${props.assistantName}`"
:placeholder="`Ask ${props.assistantName} anything`"
@submit="submit"
@add="emit('attach')"
/>
</ChatFooter>
</Chat>
</div>
</template>/*
* `messages` is deliberately a plain array. The block knows nothing about a
* model or a transport; map onto this shape at the edge of it.
*/
export interface AiChatMessage {
id: string
role: "user" | "assistant"
/** An assistant's body is rendered as chat markdown; a user's as written. */
body: string
/** ISO timestamp, for the `<time>` element. */
sentAt: string
/** What the reader sees. */
displayTime: string
}export { default as AiChat } from "./AiChat.vue"
export type { AiChatMessage } from "./types"Built fromChatMessage ListMessage GroupMessage ComposerMarkdownTyping IndicatorAvatarButton
Server sidebar
The column beside a channel: the server banner, the voice channel and the grouped member list.
import * as React from "react"
import { Avatar } from "@/registry/bases/newt/ui/avatar"
import {
MemberList,
MemberListHeading,
MemberListInfo,
MemberListItem,
MemberListName,
MemberListNameRow,
MemberListSection,
} from "@/registry/bases/newt/ui/member-list"
import {
ServerBanner,
ServerBannerIcon,
ServerBannerInfo,
ServerBannerName,
} from "@/registry/bases/newt/ui/server-banner"
import {
StatusDot,
StatusIndicator,
} from "@/registry/bases/newt/ui/status-indicator"
import type { StatusDotProps } from "@/registry/bases/newt/ui/status-indicator"
import {
VoiceChannel,
VoiceChannelHeader,
VoiceChannelIcon,
VoiceChannelMember,
VoiceChannelMembers,
} from "@/registry/bases/newt/ui/voice-channel"
/*
* The column beside a channel: who the server is, who is in voice, and who is
* around. It is an arrangement of registry components, so a project that wants
* a different order rearranges it rather than restyling anything.
*/
export interface SidebarMember {
id: string
name: string
initials: string
status: NonNullable<StatusDotProps["status"]>
/** The section heading this member belongs under. */
group: string
}
/* The state of each dot in words, for a screen reader. */
const STATUS_LABELS = {
online: "Online",
idle: "Idle",
dnd: "Do not disturb",
offline: "Offline",
streaming: "Streaming",
} as const satisfies Record<SidebarMember["status"], string>
export interface ServerSidebarProps extends React.ComponentProps<"aside"> {
serverName: string
/** Who is currently in the voice channel, in join order. */
voiceChannel?: { name: string; members: readonly string[] }
members: readonly SidebarMember[]
}
export function ServerSidebar({
serverName,
voiceChannel,
members,
className,
...props
}: ServerSidebarProps) {
// Grouped here rather than by the caller: the grouping is a property of how
// this column reads, not of the data.
const groups = React.useMemo(() => {
const byGroup = new Map<string, SidebarMember[]>()
for (const member of members) {
const existing = byGroup.get(member.group) ?? []
existing.push(member)
byGroup.set(member.group, existing)
}
return [...byGroup]
}, [members])
return (
<aside
className={className}
aria-label={`${serverName} sidebar`}
{...props}
>
<ServerBanner>
<ServerBannerIcon>{serverName.slice(0, 1)}</ServerBannerIcon>
<ServerBannerInfo>
<ServerBannerName>{serverName}</ServerBannerName>
</ServerBannerInfo>
</ServerBanner>
{voiceChannel && (
<VoiceChannel>
<VoiceChannelHeader>
<VoiceChannelIcon />
{voiceChannel.name}
</VoiceChannelHeader>
<VoiceChannelMembers>
{voiceChannel.members.map((name) => (
<VoiceChannelMember key={name}>{name}</VoiceChannelMember>
))}
</VoiceChannelMembers>
</VoiceChannel>
)}
<div>
{groups.map(([group, groupMembers]) => (
<MemberListSection key={group}>
<MemberListHeading>
{group} — {groupMembers.length}
</MemberListHeading>
<MemberList>
{groupMembers.map((member) => (
<MemberListItem key={member.id}>
<StatusIndicator>
<Avatar size="sm">{member.initials}</Avatar>
<StatusDot
status={member.status}
label={STATUS_LABELS[member.status]}
/>
</StatusIndicator>
<MemberListInfo>
<MemberListNameRow>
<MemberListName>{member.name}</MemberListName>
</MemberListNameRow>
</MemberListInfo>
</MemberListItem>
))}
</MemberList>
</MemberListSection>
))}
</div>
</aside>
)
}<script setup lang="ts">
import { computed } from "vue"
import { Avatar } from "~~/registry/bases/newt/ui/avatar"
import {
MemberList,
MemberListHeading,
MemberListInfo,
MemberListItem,
MemberListName,
MemberListNameRow,
MemberListSection,
} from "~~/registry/bases/newt/ui/member-list"
import {
ServerBanner,
ServerBannerIcon,
ServerBannerInfo,
ServerBannerName,
} from "~~/registry/bases/newt/ui/server-banner"
import {
StatusDot,
StatusIndicator,
} from "~~/registry/bases/newt/ui/status-indicator"
import {
VoiceChannel,
VoiceChannelHeader,
VoiceChannelIcon,
VoiceChannelMember,
VoiceChannelMembers,
} from "~~/registry/bases/newt/ui/voice-channel"
import type { MemberStatus, SidebarMember, VoiceChannelSummary } from "./types"
/* The state of each dot in words, for a screen reader. */
const STATUS_LABELS = {
online: "Online",
idle: "Idle",
dnd: "Do not disturb",
offline: "Offline",
streaming: "Streaming",
} as const satisfies Record<MemberStatus, string>
/*
* The column beside a channel: who the server is, who is in voice, and who is
* around. It is an arrangement of registry components, so a project that wants
* a different order rearranges it rather than restyling anything.
*/
const props = defineProps<{
serverName: string
voiceChannel?: VoiceChannelSummary
members: readonly SidebarMember[]
}>()
// Grouped here rather than by the caller: the grouping is a property of how
// this column reads, not of the data.
const groups = computed(() => {
const byGroup = new Map<string, SidebarMember[]>()
for (const member of props.members) {
const existing = byGroup.get(member.group) ?? []
existing.push(member)
byGroup.set(member.group, existing)
}
return [...byGroup]
})
</script>
<template>
<aside :aria-label="`${props.serverName} sidebar`">
<ServerBanner>
<ServerBannerIcon>{{ props.serverName.slice(0, 1) }}</ServerBannerIcon>
<ServerBannerInfo>
<ServerBannerName>{{ props.serverName }}</ServerBannerName>
</ServerBannerInfo>
</ServerBanner>
<VoiceChannel v-if="props.voiceChannel">
<VoiceChannelHeader>
<VoiceChannelIcon />
{{ props.voiceChannel.name }}
</VoiceChannelHeader>
<VoiceChannelMembers>
<VoiceChannelMember
v-for="name in props.voiceChannel.members"
:key="name"
>
{{ name }}
</VoiceChannelMember>
</VoiceChannelMembers>
</VoiceChannel>
<div>
<MemberListSection v-for="[group, groupMembers] in groups" :key="group">
<MemberListHeading
>{{ group }} — {{ groupMembers.length }}</MemberListHeading
>
<MemberList>
<MemberListItem v-for="member in groupMembers" :key="member.id">
<StatusIndicator>
<Avatar size="sm">{{ member.initials }}</Avatar>
<StatusDot
:status="member.status"
:label="STATUS_LABELS[member.status]"
/>
</StatusIndicator>
<MemberListInfo>
<MemberListNameRow>
<MemberListName>{{ member.name }}</MemberListName>
</MemberListNameRow>
</MemberListInfo>
</MemberListItem>
</MemberList>
</MemberListSection>
</div>
</aside>
</template>export type MemberStatus = "online" | "idle" | "dnd" | "offline" | "streaming"
/*
* The shape the sidebar reads. A block does not know your data layer; map onto
* this at the edge of it.
*/
export interface SidebarMember {
id: string
name: string
initials: string
status: MemberStatus
/** The section heading this member belongs under. */
group: string
}
export interface VoiceChannelSummary {
name: string
members: readonly string[]
}export { default as ServerSidebar } from "./ServerSidebar.vue"
export type { MemberStatus, SidebarMember, VoiceChannelSummary } from "./types"Built fromServer BannerVoice Channel RowMember ListStatus IndicatorAvatar
Channel sidebar
The column a server is navigated from: its name, its channels as a tree and the user panel at the foot.
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { Avatar } from "@/registry/bases/newt/ui/avatar"
import {
StatusDot,
StatusIndicator,
} from "@/registry/bases/newt/ui/status-indicator"
import type { StatusDotProps } from "@/registry/bases/newt/ui/status-indicator"
import { Tree, type TreeNode } from "@/registry/bases/newt/ui/tree"
import {
UserPanel,
UserPanelActions,
UserPanelButton,
UserPanelInfo,
} from "@/registry/bases/newt/ui/user-panel"
/*
* The shape the sidebar reads. A block does not know your data layer; map
* onto this at the edge of it.
*/
export interface SidebarUser {
name: string
initials: string
status: NonNullable<StatusDotProps["status"]>
/** The line under the name. */
statusText?: string
}
/*
* The state of the dot in words, for a screen reader. The dot speaks it only
* when no status line is written beside it.
*/
const STATUS_LABELS = {
online: "Online",
idle: "Idle",
dnd: "Do not disturb",
offline: "Offline",
streaming: "Streaming",
} as const satisfies Record<SidebarUser["status"], string>
export interface ChannelSidebarProps extends Omit<
React.ComponentProps<"aside">,
"onChange"
> {
serverName: string
/** Categories and their channels, as the tree takes them. */
channels: readonly TreeNode[]
/** Ids of the categories that start open. */
defaultExpanded?: readonly string[]
/** The id of the channel being shown. */
channel?: string
onChannelChange?: (channel: string) => void
user: SidebarUser
/** Called when the settings button in the user panel is pressed. */
onOpenSettings?: () => void
}
/*
* The column a server is navigated from: its name, its channels as a tree and
* the signed-in user's controls pinned to the foot. Muting and deafening are
* kept here as local state because the block has no voice connection to tell;
* lift them when yours does.
*/
export function ChannelSidebar({
serverName,
channels,
defaultExpanded,
channel,
onChannelChange,
user,
onOpenSettings,
className,
...props
}: ChannelSidebarProps) {
const [muted, setMuted] = React.useState(false)
const [deafened, setDeafened] = React.useState(false)
return (
<aside
aria-label={`${serverName} channels`}
className={cn(
"flex h-full min-h-0 flex-col bg-newt-bg-surface",
className
)}
{...props}
>
<header className="border-b border-newt-border px-4 py-3 text-[15px] font-semibold leading-5 text-newt-text-primary">
<span className="block truncate">{serverName}</span>
</header>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
<Tree
label="Channels"
items={channels}
defaultExpanded={defaultExpanded}
value={channel}
onValueChange={onChannelChange}
/>
</div>
<div className="p-2">
<UserPanel>
<StatusIndicator>
<Avatar size="sm">{user.initials}</Avatar>
<StatusDot
status={user.status}
label={
user.statusText === undefined
? STATUS_LABELS[user.status]
: undefined
}
/>
</StatusIndicator>
<UserPanelInfo name={user.name} status={user.statusText} />
<UserPanelActions>
<UserPanelButton
icon="microphone"
label="Mute"
pressed={muted}
onPressedChange={setMuted}
/>
<UserPanelButton
icon="headphones"
label="Deafen"
pressed={deafened}
onPressedChange={setDeafened}
/>
<UserPanelButton
icon="settings"
label="User settings"
onClick={onOpenSettings}
/>
</UserPanelActions>
</UserPanel>
</div>
</aside>
)
}<script setup lang="ts">
import { ref, type HTMLAttributes } from "vue"
import { Avatar } from "~~/registry/bases/newt/ui/avatar"
import {
StatusDot,
StatusIndicator,
} from "~~/registry/bases/newt/ui/status-indicator"
import { Tree, type TreeNode } from "~~/registry/bases/newt/ui/tree"
import {
UserPanel,
UserPanelActions,
UserPanelButton,
UserPanelInfo,
} from "~~/registry/bases/newt/ui/user-panel"
import { cn } from "@/lib/utils"
import type { SidebarUser, UserStatus } from "./types"
/*
* The state of the dot in words, for a screen reader. The dot speaks it only
* when no status line is written beside it.
*/
const STATUS_LABELS = {
online: "Online",
idle: "Idle",
dnd: "Do not disturb",
offline: "Offline",
streaming: "Streaming",
} as const satisfies Record<UserStatus, string>
/*
* The column a server is navigated from: its name, its channels as a tree and
* the signed-in user's controls pinned to the foot. Muting and deafening are
* kept here as local state because the block has no voice connection to tell;
* lift them when yours does.
*/
const props = defineProps<{
class?: HTMLAttributes["class"]
serverName: string
/** Categories and their channels, as the tree takes them. */
channels: readonly TreeNode[]
/** Ids of the categories that start open. */
defaultExpanded?: readonly string[]
user: SidebarUser
}>()
const emit = defineEmits<{
/** Fired when the settings button in the user panel is pressed. */
(e: "openSettings"): void
}>()
/** The id of the channel being shown. */
const channel = defineModel<string>("channel")
const muted = ref(false)
const deafened = ref(false)
</script>
<template>
<aside
:aria-label="`${props.serverName} channels`"
:class="cn('flex h-full min-h-0 flex-col bg-newt-bg-surface', props.class)"
>
<header
class="border-b border-newt-border px-4 py-3 text-[15px] font-semibold leading-5 text-newt-text-primary"
>
<span class="block truncate">{{ props.serverName }}</span>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-2">
<Tree
v-model="channel"
label="Channels"
:items="props.channels"
:default-expanded="props.defaultExpanded"
/>
</div>
<div class="p-2">
<UserPanel>
<StatusIndicator>
<Avatar size="sm">{{ props.user.initials }}</Avatar>
<StatusDot
:status="props.user.status"
:label="
props.user.statusText === undefined
? STATUS_LABELS[props.user.status]
: undefined
"
/>
</StatusIndicator>
<UserPanelInfo
:name="props.user.name"
:status="props.user.statusText"
/>
<UserPanelActions>
<UserPanelButton
v-model:pressed="muted"
icon="microphone"
label="Mute"
/>
<UserPanelButton
v-model:pressed="deafened"
icon="headphones"
label="Deafen"
/>
<UserPanelButton
icon="settings"
label="User settings"
@click="emit('openSettings')"
/>
</UserPanelActions>
</UserPanel>
</div>
</aside>
</template>export type UserStatus = "online" | "idle" | "dnd" | "offline" | "streaming"
/*
* The shape the sidebar reads. A block does not know your data layer; map
* onto this at the edge of it.
*/
export interface SidebarUser {
name: string
initials: string
status: UserStatus
/** The line under the name. */
statusText?: string
}export { default as ChannelSidebar } from "./ChannelSidebar.vue"
export type { SidebarUser, UserStatus } from "./types"Built fromTreeUser PanelStatus IndicatorAvatar
Command panel
A command browser with a selectable suggestion list and a detailed option card.
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import {
BotCommandCard,
BotCommandCardDescription,
BotCommandCardHeader,
BotCommandCardName,
BotCommandCardOption,
BotCommandCardOptions,
} from "@/registry/bases/newt/ui/bot-command-card"
import {
SlashCommandAppIcon,
SlashCommandSuggestion,
SlashCommandSuggestionGroup,
SlashCommandSuggestions,
SlashCommandSuggestionsHeader,
SlashCommandSuggestionsList,
} from "@/registry/bases/newt/ui/slash-command-suggestions"
export interface CommandPanelOption {
name: string
type?: string
required?: boolean
description?: string
}
export interface CommandPanelCommand {
id: string
name: string
description: string
appLabel?: string
options?: readonly CommandPanelOption[]
}
export interface CommandPanelProps extends Omit<
React.ComponentProps<"section">,
"children"
> {
commands: readonly CommandPanelCommand[]
selectedId?: string
defaultSelectedId?: string
onSelectedIdChange?: (id: string) => void
listLabel?: string
emptyLabel?: string
}
export function CommandPanel({
commands,
selectedId: controlledSelectedId,
defaultSelectedId,
onSelectedIdChange,
listLabel = "Available commands",
emptyLabel = "No commands available.",
className,
...props
}: CommandPanelProps) {
const [uncontrolledSelectedId, setUncontrolledSelectedId] = React.useState(
defaultSelectedId ?? commands[0]?.id
)
const instanceId = React.useId().replaceAll(":", "")
const selectedId = controlledSelectedId ?? uncontrolledSelectedId
const selectedIndex = Math.max(
0,
commands.findIndex((command) => command.id === selectedId)
)
const selectedCommand = commands[selectedIndex]
function select(id: string) {
if (controlledSelectedId === undefined) setUncontrolledSelectedId(id)
onSelectedIdChange?.(id)
}
function moveSelection(key: "first" | "last" | "next" | "previous") {
if (commands.length === 0) return
const nextIndex =
key === "first"
? 0
: key === "last"
? commands.length - 1
: key === "next"
? (selectedIndex + 1) % commands.length
: (selectedIndex - 1 + commands.length) % commands.length
const command = commands[nextIndex]
if (command) select(command.id)
}
return (
<section
className={cn(
"grid w-full grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_minmax(18rem,24rem)]",
className
)}
{...props}
>
<SlashCommandSuggestions className="max-w-none">
<SlashCommandSuggestionsList
aria-label={listLabel}
aria-activedescendant={
selectedCommand
? `${instanceId}-command-${selectedCommand.id}`
: undefined
}
tabIndex={0}
onKeyDown={(event) => {
if (event.key === "ArrowDown") {
event.preventDefault()
moveSelection("next")
} else if (event.key === "ArrowUp") {
event.preventDefault()
moveSelection("previous")
} else if (event.key === "Home") {
event.preventDefault()
moveSelection("first")
} else if (event.key === "End") {
event.preventDefault()
moveSelection("last")
}
}}
>
<SlashCommandSuggestionsHeader>
Commands
</SlashCommandSuggestionsHeader>
<SlashCommandSuggestionGroup aria-label={listLabel}>
{commands.map((command) => (
<SlashCommandSuggestion
key={command.id}
id={`${instanceId}-command-${command.id}`}
active={command.id === selectedCommand?.id}
name={command.name}
description={command.description}
appLabel={command.appLabel}
icon={
<SlashCommandAppIcon>
{command.name.slice(0, 1).toUpperCase()}
</SlashCommandAppIcon>
}
onClick={() => select(command.id)}
onMouseEnter={() => select(command.id)}
/>
))}
</SlashCommandSuggestionGroup>
{commands.length === 0 ? (
<p className="px-2 py-4 text-sm text-newt-text-muted">
{emptyLabel}
</p>
) : null}
</SlashCommandSuggestionsList>
</SlashCommandSuggestions>
{selectedCommand ? (
<BotCommandCard className="max-w-none" aria-live="polite">
<BotCommandCardHeader>
<BotCommandCardName>{selectedCommand.name}</BotCommandCardName>
{selectedCommand.appLabel ? (
<span className="text-xs text-newt-text-muted">
{selectedCommand.appLabel}
</span>
) : null}
</BotCommandCardHeader>
<BotCommandCardDescription>
{selectedCommand.description}
</BotCommandCardDescription>
{selectedCommand.options?.length ? (
<BotCommandCardOptions>
{selectedCommand.options.map((option) => (
<BotCommandCardOption key={option.name} {...option} />
))}
</BotCommandCardOptions>
) : null}
</BotCommandCard>
) : (
<div
className="rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-bg-elevated p-4 text-sm text-newt-text-muted"
aria-live="polite"
>
{emptyLabel}
</div>
)}
</section>
)
}<script setup lang="ts">
import { computed, shallowRef, useId } from "vue"
import type { HTMLAttributes } from "vue"
import {
BotCommandCard,
BotCommandCardDescription,
BotCommandCardHeader,
BotCommandCardName,
BotCommandCardOption,
BotCommandCardOptions,
} from "~~/registry/bases/newt/ui/bot-command-card"
import {
SlashCommandAppIcon,
SlashCommandSuggestion,
SlashCommandSuggestionGroup,
SlashCommandSuggestions,
SlashCommandSuggestionsHeader,
SlashCommandSuggestionsList,
} from "~~/registry/bases/newt/ui/slash-command-suggestions"
import { cn } from "@/lib/utils"
import type { CommandPanelCommand } from "./types"
const props = withDefaults(
defineProps<{
commands: readonly CommandPanelCommand[]
selectedId?: string
defaultSelectedId?: string
listLabel?: string
emptyLabel?: string
class?: HTMLAttributes["class"]
}>(),
{
listLabel: "Available commands",
emptyLabel: "No commands available.",
}
)
const emit = defineEmits<{ "update:selectedId": [id: string] }>()
const uncontrolledSelectedId = shallowRef(
props.defaultSelectedId ?? props.commands[0]?.id
)
const instanceId = useId().replaceAll(":", "")
const currentSelectedId = computed(
() => props.selectedId ?? uncontrolledSelectedId.value
)
const selectedIndex = computed(() =>
Math.max(
0,
props.commands.findIndex(
(command) => command.id === currentSelectedId.value
)
)
)
const selectedCommand = computed(() => props.commands[selectedIndex.value])
function select(id: string) {
if (props.selectedId === undefined) uncontrolledSelectedId.value = id
emit("update:selectedId", id)
}
function moveSelection(key: "first" | "last" | "next" | "previous") {
if (props.commands.length === 0) return
const nextIndex =
key === "first"
? 0
: key === "last"
? props.commands.length - 1
: key === "next"
? (selectedIndex.value + 1) % props.commands.length
: (selectedIndex.value - 1 + props.commands.length) %
props.commands.length
const command = props.commands[nextIndex]
if (command) select(command.id)
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === "ArrowDown") {
event.preventDefault()
moveSelection("next")
} else if (event.key === "ArrowUp") {
event.preventDefault()
moveSelection("previous")
} else if (event.key === "Home") {
event.preventDefault()
moveSelection("first")
} else if (event.key === "End") {
event.preventDefault()
moveSelection("last")
}
}
</script>
<template>
<section
:class="
cn(
'grid w-full grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_minmax(18rem,24rem)]',
props.class
)
"
>
<SlashCommandSuggestions class="max-w-none">
<SlashCommandSuggestionsList
:aria-label="props.listLabel"
:aria-activedescendant="
selectedCommand
? `${instanceId}-command-${selectedCommand.id}`
: undefined
"
tabindex="0"
@keydown="handleKeydown"
>
<SlashCommandSuggestionsHeader>Commands</SlashCommandSuggestionsHeader>
<SlashCommandSuggestionGroup :aria-label="props.listLabel">
<SlashCommandSuggestion
v-for="command in props.commands"
:id="`${instanceId}-command-${command.id}`"
:key="command.id"
:active="command.id === selectedCommand?.id"
:name="command.name"
:description="command.description"
:app-label="command.appLabel"
@click="select(command.id)"
@mouseenter="select(command.id)"
>
<template #icon>
<SlashCommandAppIcon>
{{ command.name.slice(0, 1).toUpperCase() }}
</SlashCommandAppIcon>
</template>
</SlashCommandSuggestion>
</SlashCommandSuggestionGroup>
<p
v-if="props.commands.length === 0"
class="px-2 py-4 text-sm text-newt-text-muted"
>
{{ props.emptyLabel }}
</p>
</SlashCommandSuggestionsList>
</SlashCommandSuggestions>
<BotCommandCard
v-if="selectedCommand"
class="max-w-none"
aria-live="polite"
>
<BotCommandCardHeader>
<BotCommandCardName>{{ selectedCommand.name }}</BotCommandCardName>
<span
v-if="selectedCommand.appLabel"
class="text-xs text-newt-text-muted"
>
{{ selectedCommand.appLabel }}
</span>
</BotCommandCardHeader>
<BotCommandCardDescription>
{{ selectedCommand.description }}
</BotCommandCardDescription>
<BotCommandCardOptions v-if="selectedCommand.options?.length">
<BotCommandCardOption
v-for="option in selectedCommand.options"
:key="option.name"
v-bind="option"
/>
</BotCommandCardOptions>
</BotCommandCard>
<div
v-else
class="rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-bg-elevated p-4 text-sm text-newt-text-muted"
aria-live="polite"
>
{{ props.emptyLabel }}
</div>
</section>
</template>export interface CommandPanelOption {
name: string
type?: string
required?: boolean
description?: string
}
export interface CommandPanelCommand {
id: string
name: string
description: string
appLabel?: string
options?: readonly CommandPanelOption[]
}export { default as CommandPanel } from "./CommandPanel.vue"
export type { CommandPanelCommand, CommandPanelOption } from "./types"Settings layout
A settings screen: grouped sections down the side and the chosen section's breadcrumb, heading and content beside them.
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { Breadcrumb, BreadcrumbItem } from "@/registry/bases/newt/ui/breadcrumb"
import {
SideNav,
SideNavGroup,
SideNavItem,
} from "@/registry/bases/newt/ui/side-nav"
/*
* The shape the layout reads. A block does not know your router; map your
* sections onto this at the edge of it.
*/
export interface SettingsSection {
id: string
label: string
/** A count shown beside the entry. */
badge?: number
/** For an entry that destroys something. It is never the current section. */
danger?: boolean
}
export interface SettingsGroup {
/** The small heading over the group. */
label?: string
sections: readonly SettingsSection[]
}
export interface SettingsLayoutProps extends Omit<
React.ComponentProps<"div">,
"title"
> {
/** What is being configured; the first crumb and the nav's name. */
title: string
groups: readonly SettingsGroup[]
/** The id of the section being shown. */
section: string
onSectionChange?: (section: string) => void
}
/*
* A settings screen: the list of sections down the side, and the chosen
* section's heading, breadcrumb and content beside it. The content is the
* children, so each section stays an ordinary component of yours. The
* content column is a plain box and not a `<main>`, because the page the
* block is dropped into has one already. Below 40rem the navigation moves
* above the content.
*/
export function SettingsLayout({
title,
groups,
section,
onSectionChange,
className,
children,
...props
}: SettingsLayoutProps) {
const current = groups
.flatMap((group) => group.sections)
.find((each) => each.id === section)
return (
<div
className={cn(
"flex w-full flex-col bg-newt-bg-elevated sm:flex-row",
className
)}
{...props}
>
<SideNav
aria-label={title}
className="shrink-0 bg-newt-bg-surface px-2 sm:w-56"
>
{groups.map((group, index) => (
<SideNavGroup key={group.label ?? index} label={group.label}>
{group.sections.map((each) => (
<SideNavItem
key={each.id}
badge={each.badge}
variant={each.danger ? "danger" : "default"}
current={!each.danger && each.id === section}
onClick={() => onSectionChange?.(each.id)}
>
{each.label}
</SideNavItem>
))}
</SideNavGroup>
))}
</SideNav>
<div className="flex min-w-0 flex-1 flex-col gap-4 p-6">
<Breadcrumb>
<BreadcrumbItem>{title}</BreadcrumbItem>
<BreadcrumbItem current>{current?.label ?? section}</BreadcrumbItem>
</Breadcrumb>
<h2 className="m-0 text-xl font-semibold leading-6 text-newt-text-primary">
{current?.label ?? section}
</h2>
{children}
</div>
</div>
)
}<script setup lang="ts">
import { computed, type HTMLAttributes } from "vue"
import {
Breadcrumb,
BreadcrumbItem,
} from "~~/registry/bases/newt/ui/breadcrumb"
import {
SideNav,
SideNavGroup,
SideNavItem,
} from "~~/registry/bases/newt/ui/side-nav"
import { cn } from "@/lib/utils"
import type { SettingsGroup } from "./types"
/*
* A settings screen: the list of sections down the side, and the chosen
* section's heading, breadcrumb and content beside it. The content is the
* default slot, so each section stays an ordinary component of yours. The
* content column is a plain box and not a `<main>`, because the page the
* block is dropped into has one already. Below 40rem the navigation moves
* above the content.
*/
const props = defineProps<{
class?: HTMLAttributes["class"]
/** What is being configured; the first crumb and the nav's name. */
title: string
groups: readonly SettingsGroup[]
}>()
/** The id of the section being shown. */
const section = defineModel<string>("section", { required: true })
const current = computed(() =>
props.groups
.flatMap((group) => group.sections)
.find((each) => each.id === section.value)
)
</script>
<template>
<div
:class="
cn('flex w-full flex-col bg-newt-bg-elevated sm:flex-row', props.class)
"
>
<SideNav
:aria-label="props.title"
class="shrink-0 bg-newt-bg-surface px-2 sm:w-56"
>
<SideNavGroup
v-for="(group, index) in props.groups"
:key="group.label ?? index"
:label="group.label"
>
<SideNavItem
v-for="each in group.sections"
:key="each.id"
:badge="each.badge"
:variant="each.danger ? 'danger' : 'default'"
:current="!each.danger && each.id === section"
@click="section = each.id"
>
{{ each.label }}
</SideNavItem>
</SideNavGroup>
</SideNav>
<div class="flex min-w-0 flex-1 flex-col gap-4 p-6">
<Breadcrumb>
<BreadcrumbItem>{{ props.title }}</BreadcrumbItem>
<BreadcrumbItem current>{{ current?.label ?? section }}</BreadcrumbItem>
</Breadcrumb>
<h2 class="m-0 text-xl font-semibold leading-6 text-newt-text-primary">
{{ current?.label ?? section }}
</h2>
<slot />
</div>
</div>
</template>/*
* The shape the layout reads. A block does not know your router; map your
* sections onto this at the edge of it.
*/
export interface SettingsSection {
id: string
label: string
/** A count shown beside the entry. */
badge?: number
/** For an entry that destroys something. It is never the current section. */
danger?: boolean
}
export interface SettingsGroup {
/** The small heading over the group. */
label?: string
sections: readonly SettingsSection[]
}export { default as SettingsLayout } from "./SettingsLayout.vue"
export type { SettingsGroup, SettingsSection } from "./types"Built fromSide NavBreadcrumb
Onboarding
A short setup flow: a stepper, the current step's content and the buttons that move through it.
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/registry/bases/newt/ui/button"
import { Stepper, type StepperStep } from "@/registry/bases/newt/ui/stepper"
/** The wording of the three buttons. */
export interface OnboardingLabels {
back: string
next: string
finish: string
}
export interface OnboardingProps extends Omit<
React.ComponentProps<"section">,
"children" | "onChange"
> {
steps: readonly StepperStep[]
/** Index of the step being shown. Leave undefined to let the block own it. */
step?: number
defaultStep?: number
onStepChange?: (step: number) => void
/** Called when the last step's button is pressed. */
onComplete?: () => void
/** Whether the current step may be left. Defaults to yes. */
canContinue?: boolean
labels?: OnboardingLabels
/** The content of the step whose index it is given. */
children: (step: number) => React.ReactNode
}
const defaultLabels: OnboardingLabels = {
back: "Back",
next: "Next",
finish: "Finish",
}
/*
* A short setup flow: where you are in it, the current step's own content,
* and the two buttons that move through it. The content is a function of the
* step, so each step stays an ordinary component of yours and the block only
* owns the order. Moving to another step moves focus to its heading, so a
* screen reader starts from the new content.
*/
export function Onboarding({
steps,
step,
defaultStep = 0,
onStepChange,
onComplete,
canContinue = true,
labels = defaultLabels,
className,
children,
...props
}: OnboardingProps) {
const [internal, setInternal] = React.useState(defaultStep)
const current = Math.min(step ?? internal, steps.length - 1)
const last = current === steps.length - 1
const heading = React.useRef<HTMLHeadingElement | null>(null)
const moved = React.useRef(false)
React.useEffect(() => {
if (moved.current) heading.current?.focus()
}, [current])
const goTo = (next: number) => {
moved.current = true
if (step === undefined) setInternal(next)
onStepChange?.(next)
}
return (
<section
className={cn(
"flex w-full flex-col gap-6 rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-surface p-6",
className
)}
{...props}
>
<Stepper steps={steps} value={current} />
<div className="flex flex-col gap-4">
<h2
ref={heading}
tabIndex={-1}
className="m-0 text-lg font-semibold leading-6 text-newt-text-primary focus:outline-none"
>
{steps[current]?.title}
</h2>
{children(current)}
</div>
<div className="flex justify-between gap-2">
<Button
variant="secondary"
disabled={current === 0}
onClick={() => goTo(current - 1)}
>
{labels.back}
</Button>
<Button
disabled={!canContinue}
onClick={() => {
if (last) onComplete?.()
else goTo(current + 1)
}}
>
{last ? labels.finish : labels.next}
</Button>
</div>
</section>
)
}<script setup lang="ts">
import { computed, nextTick, ref, type HTMLAttributes } from "vue"
import { Button } from "~~/registry/bases/newt/ui/button"
import { Stepper, type StepperStep } from "~~/registry/bases/newt/ui/stepper"
import { cn } from "@/lib/utils"
import type { OnboardingLabels } from "./types"
/*
* A short setup flow: where you are in it, the current step's own content,
* and the two buttons that move through it. The content is the default slot,
* which is handed the step's index, so each step stays an ordinary component
* of yours and the block only owns the order. Moving to another step moves
* focus to its heading, so a screen reader starts from the new content.
*/
const props = withDefaults(
defineProps<{
class?: HTMLAttributes["class"]
steps: readonly StepperStep[]
/** Whether the current step may be left. */
canContinue?: boolean
labels?: OnboardingLabels
}>(),
{
canContinue: true,
labels: () => ({ back: "Back", next: "Next", finish: "Finish" }),
}
)
const emit = defineEmits<{
/** Fired when the last step's button is pressed. */
(e: "complete"): void
}>()
/** Index of the step being shown. Use `v-model:step` to control it. */
const step = defineModel<number>("step", { default: 0 })
const heading = ref<HTMLHeadingElement | null>(null)
const current = computed(() => Math.min(step.value, props.steps.length - 1))
const last = computed(() => current.value === props.steps.length - 1)
async function goTo(next: number) {
step.value = next
await nextTick()
heading.value?.focus()
}
function forward() {
if (last.value) emit("complete")
else void goTo(current.value + 1)
}
</script>
<template>
<section
:class="
cn(
'flex w-full flex-col gap-6 rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-surface p-6',
props.class
)
"
>
<Stepper :steps="props.steps" :value="current" />
<div class="flex flex-col gap-4">
<h2
ref="heading"
tabindex="-1"
class="m-0 text-lg font-semibold leading-6 text-newt-text-primary focus:outline-none"
>
{{ props.steps[current]?.title }}
</h2>
<slot :step="current" />
</div>
<div class="flex justify-between gap-2">
<Button
variant="secondary"
:disabled="current === 0"
@click="goTo(current - 1)"
>
{{ props.labels.back }}
</Button>
<Button :disabled="!props.canContinue" @click="forward">
{{ last ? props.labels.finish : props.labels.next }}
</Button>
</div>
</section>
</template>/** The wording of the three buttons. */
export interface OnboardingLabels {
back: string
next: string
finish: string
}export { default as Onboarding } from "./Onboarding.vue"
export type { OnboardingLabels } from "./types"