feat(chat): ask several questions in one interaction with ask_questions

A turn can pose a questionnaire (single and multiple choice, free text,
skippable) and read the answers back, rendered in the chat with the
shadcn-vue questionnaire. The gateway contract gains a questionnaire ask and a
can_question capability; answers travel as a JSON object keyed by question name
and are checked against the questions that were asked.
This commit is contained in:
sam committed 2026-10-19 03:30:47 +11:00
1 parent 31ac8f1338
commit 5c47ebd05b
30 files changed
+3211 -392

No files matched your search

@@ -0,0 +1,453 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type {
ItemRegistration,
QuestionnaireItemDefinition,
QuestionnaireShortcutMode,
} from './useQuestionnaire'
import { cn } from '@/lib/utils'
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
import {
compareDocumentOrder,
createQuestionnaireCollection,
getInitialItemName,
getShortcutFromKey,
isAnswerFilled,
isRadioTarget,
isTextEntryTarget,
provideQuestionnaireRootContext,
} from './useQuestionnaire'
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
/** Item shown first. Ignored when `item` is provided. */
defaultItem?: string
/** Controlled active item. Use with `v-model:item`. */
item?: string
/** Declares the item order, and the choice order shortcuts are assigned in. */
items?: readonly QuestionnaireItemDefinition[]
/** Set to `false` to run native constraint validation on answered items. */
noValidate?: boolean
/** Assigns a keyboard shortcut to every choice. */
shortcuts?: QuestionnaireShortcutMode
}>(), {
noValidate: true,
})
const emits = defineEmits<{
'reset': [event: Event]
'submit': [event: Event]
'update:item': [item: string]
}>()
interface PendingFocus {
name: string
target: 'invalid' | 'item'
}
const rootElement = ref<HTMLFormElement | null>(null)
const registrations = shallowRef<ItemRegistration[]>([])
const domVersion = ref(0)
const pendingFocus = shallowRef<PendingFocus | null>(null)
const collection = computed(() => createQuestionnaireCollection(props.items))
const uncontrolledItem = ref<string | null>(
getInitialItemName(collection.value, props.defaultItem),
)
const controlled = computed(() => props.item !== undefined)
const activeItemName = computed(() => (controlled.value ? props.item! : uncontrolledItem.value))
const shortcuts = computed(() => props.shortcuts ?? null)
const nativeValidation = computed(() => props.noValidate === false)
let previousActiveItemName = activeItemName.value
const runtimeItems = computed(() => {
// Re-sort whenever items are added to or removed from the DOM.
void domVersion.value
return registrations.value
.filter(registration => !registration.isDisabled())
.sort((first, second) => compareDocumentOrder(first.element, second.element))
})
const runtimeItemByName = computed(
() => new Map(runtimeItems.value.map(runtimeItem => [runtimeItem.name, runtimeItem])),
)
/** `items` is authoritative when provided, so items can be declared before they render. */
const logicalItems = computed<readonly { name: string }[]>(
() => collection.value?.enabledItems ?? runtimeItems.value,
)
const currentIndex = computed(
() => logicalItems.value.findIndex(logicalItem => logicalItem.name === activeItemName.value),
)
const activeItem = computed(() => {
if (currentIndex.value < 0 || !activeItemName.value) {
return null
}
return runtimeItemByName.value.get(activeItemName.value) ?? null
})
const activeDefinition = computed(() =>
activeItemName.value ? collection.value?.itemByName.get(activeItemName.value) : undefined,
)
const activeItemRequired = computed(() => {
if (currentIndex.value < 0) {
return null
}
return activeDefinition.value
? Boolean(activeDefinition.value.required)
: (activeItem.value?.isRequired() ?? false)
})
const activeItemStatus = computed(() => {
if (currentIndex.value < 0) {
return null
}
return activeItem.value?.status() ?? (activeItemName.value ? 'unanswered' : null)
})
const orderedRegistrations = computed(() => {
if (!collection.value) {
return runtimeItems.value
}
return collection.value.enabledItems.flatMap((definition) => {
const registration = runtimeItemByName.value.get(definition.name)
return registration ? [registration] : []
})
})
const total = computed(() => logicalItems.value.length)
const current = computed(() => (currentIndex.value < 0 ? 0 : currentIndex.value + 1))
const first = computed(() => total.value > 0 && currentIndex.value === 0)
const last = computed(() => total.value > 0 && currentIndex.value === total.value - 1)
function setItem(nextItem: string, focusTarget: PendingFocus['target'] = 'item') {
if (nextItem === activeItemName.value) {
return
}
pendingFocus.value = { name: nextItem, target: focusTarget }
if (!controlled.value) {
uncontrolledItem.value = nextItem
}
emits('update:item', nextItem)
}
function registerItem(registration: ItemRegistration) {
registrations.value = [
...registrations.value.filter(
current => current.element !== registration.element && current.name !== registration.name,
),
registration,
]
return () => {
registrations.value = registrations.value.filter(current => current !== registration)
}
}
function setItemAt(index: number, focusTarget: PendingFocus['target'] = 'item') {
const nextItem = logicalItems.value[index]
if (nextItem) {
setItem(nextItem.name, focusTarget)
}
}
function goPrevious() {
if (currentIndex.value <= 0) {
return
}
setItemAt(currentIndex.value - 1)
}
function goNext() {
if (!activeItem.value || currentIndex.value >= total.value - 1) {
return
}
if (!activeItem.value.validate()) {
activeItem.value.focusInvalid()
return
}
setItemAt(currentIndex.value + 1)
}
function confirmCurrent() {
if (!activeItem.value) {
return
}
if (!activeItem.value.validate()) {
activeItem.value.focusInvalid()
return
}
if (last.value) {
rootElement.value?.requestSubmit()
return
}
setItemAt(currentIndex.value + 1)
}
function skipCurrent() {
if (!activeItem.value || activeItem.value.isRequired()) {
return
}
activeItem.value.skip()
if (!last.value) {
setItemAt(currentIndex.value + 1)
return
}
queueMicrotask(() => {
rootElement.value?.requestSubmit()
})
}
function handleReset(event: Event) {
emits('reset', event)
if (event.defaultPrevented) {
return
}
for (const registration of registrations.value) {
registration.reset()
}
const resetItemName = collection.value
? getInitialItemName(collection.value, props.defaultItem)
: (runtimeItems.value.find(registration => registration.name === props.defaultItem)?.name
?? runtimeItems.value[0]?.name)
if (resetItemName) {
setItem(resetItemName)
}
}
function handleSubmit(event: Event) {
const firstInvalidItem = orderedRegistrations.value.find(registration => !registration.validate())
if (firstInvalidItem) {
event.preventDefault()
setItem(firstInvalidItem.name, 'invalid')
if (firstInvalidItem.name === activeItemName.value) {
firstInvalidItem.focusInvalid()
pendingFocus.value = null
}
return
}
emits('submit', event)
}
function handleKeydown(event: KeyboardEvent) {
if (
event.defaultPrevented
|| event.isComposing
|| event.keyCode === 229
|| !activeItem.value
|| !(event.target instanceof Element)
) {
return
}
if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey) {
event.preventDefault()
if (!event.repeat) {
confirmCurrent()
}
return
}
if (event.metaKey || event.ctrlKey || event.altKey) {
return
}
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
const moved = activeItem.value.moveAnswerFocus(
event.target,
event.key === 'ArrowDown' ? 'next' : 'previous',
)
if (moved) {
event.preventDefault()
return
}
}
if (
(event.key === 'ArrowLeft' || event.key === 'ArrowRight')
&& !isTextEntryTarget(event.target)
&& !isRadioTarget(event.target)
) {
event.preventDefault()
if (event.repeat) {
return
}
if (event.key === 'ArrowLeft') {
goPrevious()
}
else if (activeItem.value.status() !== 'unanswered') {
goNext()
}
return
}
if (event.key === 'Enter') {
const answer = activeItem.value.getAnswerByElement(event.target)
if (!answer) {
return
}
event.preventDefault()
if (!event.repeat && isAnswerFilled(answer)) {
confirmCurrent()
}
return
}
if (!shortcuts.value || isTextEntryTarget(event.target)) {
return
}
const shortcut = getShortcutFromKey(event.key, shortcuts.value)
const answer = shortcut ? activeItem.value.getAnswerByShortcut(shortcut) : null
if (!answer) {
return
}
event.preventDefault()
if (event.repeat) {
return
}
answer.element.focus()
if (answer.type === 'choice') {
answer.element.click()
}
}
watch(
() => [activeItemName.value, currentIndex.value, total.value, activeItem.value] as const,
() => {
if (total.value === 0) {
return
}
if (currentIndex.value < 0) {
const firstItem = logicalItems.value[0]
if (!firstItem) {
return
}
if (!controlled.value && activeItemName.value === null) {
uncontrolledItem.value = firstItem.name
return
}
setItem(firstItem.name)
return
}
const focus = pendingFocus.value
const activeItemChanged = previousActiveItemName !== activeItemName.value
previousActiveItemName = activeItemName.value
if (!focus || focus.name !== activeItemName.value) {
if (controlled.value && activeItemChanged) {
pendingFocus.value = null
activeItem.value?.focus()
}
return
}
if (focus.target === 'invalid') {
activeItem.value?.focusInvalid()
}
else {
activeItem.value?.focus()
}
pendingFocus.value = null
},
{ flush: 'post', immediate: true },
)
let observer: MutationObserver | null = null
onMounted(() => {
if (!rootElement.value || typeof MutationObserver === 'undefined') {
return
}
observer = new MutationObserver(() => {
domVersion.value += 1
})
observer.observe(rootElement.value, { childList: true, subtree: true })
})
onBeforeUnmount(() => {
observer?.disconnect()
observer = null
})
provideQuestionnaireRootContext({
activeItem,
activeItemName,
activeItemRequired,
activeItemStatus,
current,
domVersion,
first,
goNext,
goPrevious,
itemDefinitionByName: computed(() => collection.value?.itemByName ?? null),
last,
nativeValidation,
registerItem,
shortcuts,
skipCurrent,
total,
})
</script>
<template>
<form
ref="rootElement"
data-slot="questionnaire"
:data-shortcuts="shortcuts ?? undefined"
:novalidate="props.noValidate"
:class="cn('gap-4 flex w-full min-w-0 flex-col', props.class)"
@keydown="handleKeydown"
@reset="handleReset"
@submit="handleSubmit"
>
<slot :current="current" :first="first" :last="last" :total="total" />
</form>
</template>
@@ -0,0 +1,26 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
}>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="questionnaire-actions"
:as="props.as"
:as-child="props.asChild"
:class="cn(
'gap-2 sm:min-h-8 grid min-h-11 w-full grid-cols-[minmax(0,1fr)_auto_auto] items-center',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,198 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { CheckIcon } from '@lucide/vue'
import { cn } from '@/lib/utils'
import { computed, onBeforeUnmount, ref, useId, watch } from 'vue'
import { getAnswerKeyShortcuts, injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<{
/** Controlled checked state. Use with `v-model:checked`. */
checked?: boolean
class?: HTMLAttributes['class']
/** Checks the choice on mount and after a native form reset. */
defaultChecked?: boolean
disabled?: boolean
/** Submitted as the answer of the parent item. */
value: string
}>(), {
// `undefined` keeps the choice uncontrolled. Without this default, Vue casts
// the absent boolean prop to `false` and every choice looks controlled.
checked: undefined,
defaultChecked: false,
disabled: false,
})
const emits = defineEmits<{
'change': [event: Event]
'update:checked': [checked: boolean]
}>()
const item = injectQuestionnaireItemContext()
const answerId = useId()
const inputElement = ref<HTMLInputElement | null>(null)
const initialDefaultChecked = props.defaultChecked
const controlled = computed(() => props.checked !== undefined)
const disabled = computed(() => item.disabled.value || props.disabled)
const selected = computed(() => item.selectedAnswerIds.value.includes(answerId))
const checked = computed(() => {
if (!controlled.value) {
return selected.value
}
// A skipped item clears every answer, including controlled ones.
return item.status.value === 'skipped' ? false : props.checked!
})
const type = computed(() => (item.multiple.value ? 'checkbox' : 'radio'))
const shortcut = computed(() =>
item.shortcutByChoiceValue.value?.get(props.value)
?? item.shortcutByAnswerId.value.get(answerId)
?? null)
function syncCheckedElement() {
if (inputElement.value && inputElement.value.checked !== checked.value) {
inputElement.value.checked = checked.value
}
}
function handleChange(event: Event) {
emits('change', event)
if (event.defaultPrevented) {
syncCheckedElement()
return
}
const nextChecked = (event.target as HTMLInputElement).checked
emits('update:checked', nextChecked)
if (!controlled.value) {
item.setAnswerSelectionFromInteraction(answerId, nextChecked)
return
}
// Re-selecting the same controlled choice has to clear the skipped state.
if (item.status.value === 'skipped' && props.checked === nextChecked) {
item.setAnswerSelectionFromInteraction(answerId, props.checked)
}
// Checking a radio clears its siblings, so the whole group has to re-sync in
// case the host keeps the previous answer.
item.requestControlSync()
}
const unregisterSelection = item.registerAnswerSelection(answerId, initialDefaultChecked)
let unregisterControl: (() => void) | null = null
watch([inputElement, disabled, () => props.disabled, () => props.value], ([element]) => {
unregisterControl?.()
unregisterControl = null
if (!element) {
return
}
unregisterControl = item.registerAnswerControl({
disabled: disabled.value,
element,
id: answerId,
ownDisabled: props.disabled,
type: 'choice',
value: props.value,
})
}, { flush: 'post' })
watch(() => props.defaultChecked, (defaultChecked) => {
item.setAnswerDefault(answerId, defaultChecked)
})
watch([() => props.checked, item.resetVersion], () => {
if (controlled.value) {
item.syncControlledAnswerSelection(answerId, props.checked!)
}
}, { immediate: true })
watch(item.controlSyncVersion, syncCheckedElement, { flush: 'post' })
watch([checked, inputElement, () => props.defaultChecked, item.resetVersion], () => {
if (!inputElement.value) {
return
}
// Keep the native reset target aligned with the questionnaire owned default,
// including controlled choices whose `checked` prop stays authoritative.
inputElement.value.defaultChecked = controlled.value ? props.checked! : props.defaultChecked
syncCheckedElement()
}, { flush: 'post' })
onBeforeUnmount(() => {
unregisterControl?.()
unregisterControl = null
unregisterSelection()
})
</script>
<template>
<label
data-slot="questionnaire-choice"
:data-checked="checked ? '' : undefined"
:data-disabled="disabled ? '' : undefined"
:data-invalid="item.invalid.value ? '' : undefined"
:data-shortcut="shortcut ?? undefined"
:data-type="type"
:data-unchecked="checked ? undefined : ''"
:class="cn(
'border-input dark:bg-input/20 hover:bg-muted/50 data-checked:border-primary/40 data-checked:bg-muted dark:data-checked:bg-muted data-invalid:border-destructive has-[>input:focus-visible]:border-ring has-[>input:focus-visible]:ring-ring/50 gap-2.5 rounded-lg border bg-transparent px-3 py-2.5 text-sm has-[>input:focus-visible]:ring-3 group/questionnaire-choice relative flex min-h-11 cursor-pointer items-start text-start transition-colors outline-none select-none',
'data-disabled:pointer-events-none data-disabled:cursor-not-allowed data-disabled:opacity-50',
props.class,
)"
>
<input
:id="answerId"
ref="inputElement"
data-slot="questionnaire-choice-input"
class="absolute inset-0 z-10 size-full cursor-pointer opacity-0"
:aria-invalid="item.invalid.value || undefined"
:aria-keyshortcuts="getAnswerKeyShortcuts(shortcut, !disabled && checked)"
:checked="checked"
:data-checked="checked ? '' : undefined"
:data-unchecked="checked ? undefined : ''"
:disabled="disabled"
:name="item.status.value === 'skipped' ? undefined : item.name.value"
:required="item.required.value && !item.multiple.value && !item.hasInputAnswer.value"
:type="type"
:value="props.value"
@change="handleChange"
>
<span
aria-hidden="true"
data-slot="questionnaire-choice-indicator"
class="border-input dark:bg-input/30 group-data-checked/questionnaire-choice:bg-primary dark:group-data-checked/questionnaire-choice:bg-primary group-data-checked/questionnaire-choice:text-primary-foreground group-data-checked/questionnaire-choice:border-primary size-4 translate-y-[--spacing(0.45)] group-has-data-[slot=questionnaire-choice-description]/questionnaire-choice:translate-y-0.5 rounded-[4px] pointer-events-none relative flex shrink-0 items-center justify-center border group-data-[type=radio]/questionnaire-choice:rounded-full"
>
<span
data-slot="questionnaire-choice-indicator-dot"
class="bg-primary-foreground size-2 hidden rounded-full group-data-[type=checkbox]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block"
/>
<CheckIcon data-slot="questionnaire-choice-indicator-check" class="size-3.5 hidden group-data-[type=radio]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block" />
</span>
<span
data-slot="questionnaire-choice-label"
class="gap-0.5 flex min-w-0 flex-1 flex-col leading-snug"
>
<slot :checked="checked" :disabled="disabled" :shortcut="shortcut" :type="type" />
</span>
<span
v-if="shortcut"
aria-hidden="true"
data-slot="questionnaire-choice-shortcut"
class="border-input bg-background text-muted-foreground size-5 translate-y-[--spacing(0.45)] group-has-data-[slot=questionnaire-choice-description]/questionnaire-choice:translate-y-0.5 items-center justify-center rounded-md border font-mono text-[0.625rem] font-medium leading-none pointer-events-none ms-auto hidden shrink-0 group-data-[shortcut]/questionnaire-choice:inline-flex"
>
{{ shortcut }}
</span>
</label>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<span
data-slot="questionnaire-choice-description"
:class="cn('text-muted-foreground', props.class)"
>
<slot />
</span>
</template>
@@ -0,0 +1,27 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
}>(), {
as: 'div',
})
const item = injectQuestionnaireItemContext()
</script>
<template>
<Primitive
data-slot="questionnaire-choices"
:as="props.as"
:as-child="props.asChild"
:data-shortcuts="item.shortcuts.value ?? undefined"
:class="cn('gap-2 group/questionnaire-choices grid min-w-0', props.class)"
>
<slot :shortcuts="item.shortcuts.value" />
</Primitive>
</template>
@@ -0,0 +1,59 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { ComponentPublicInstance, HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { onBeforeUnmount, onMounted, ref, useId } from 'vue'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
id?: string
}>(), {
as: 'p',
})
const item = injectQuestionnaireItemContext()
const primitiveRef = ref<ComponentPublicInstance | null>(null)
const fallbackId = props.id ?? useId()
const descriptionId = ref(fallbackId)
let unregisterDescription = item.registerDescription(descriptionId.value)
onMounted(() => {
// With `as-child` the rendered child can bring its own id, for example a
// DialogDescription. Adopt it so both descriptions point at one element.
const element = primitiveRef.value?.$el as HTMLElement | undefined
const renderedId = element?.id
if (!renderedId) {
if (element) {
element.id = fallbackId
}
return
}
if (renderedId !== descriptionId.value) {
unregisterDescription()
descriptionId.value = renderedId
unregisterDescription = item.registerDescription(renderedId)
}
})
onBeforeUnmount(() => unregisterDescription())
</script>
<template>
<Primitive
v-bind="props.asChild ? {} : { id: descriptionId }"
ref="primitiveRef"
data-slot="questionnaire-description"
:as="props.as"
:as-child="props.asChild"
:class="cn('text-sm text-pretty text-muted-foreground', props.class)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,44 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed, onBeforeUnmount, useId } from 'vue'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
id?: string
}>(), {
as: 'p',
})
const item = injectQuestionnaireItemContext()
const errorId = props.id ?? useId()
const unregisterError = item.registerError(errorId)
const fallback = computed(() =>
item.required.value
? 'Choose an answer to continue.'
: 'Choose an answer or skip this question.')
onBeforeUnmount(unregisterError)
</script>
<template>
<Primitive
:id="errorId"
data-slot="questionnaire-error"
:as="props.as"
:as-child="props.asChild"
:data-invalid="item.invalid.value ? '' : undefined"
:hidden="!item.invalid.value"
:role="item.invalid.value ? 'alert' : undefined"
:class="cn('mt-2 text-sm text-destructive', props.class)"
>
<slot :invalid="item.invalid.value">
{{ fallback }}
</slot>
</Primitive>
</template>
@@ -0,0 +1,160 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type { QuestionnaireInputType } from './useQuestionnaire'
import { cn } from '@/lib/utils'
import { computed, nextTick, onBeforeUnmount, ref, useId, watch } from 'vue'
import {
getAnswerKeyShortcuts,
hasInputValue,
injectQuestionnaireItemContext,
} from './useQuestionnaire'
defineOptions({
// The wrapper is the root element, so attributes have to reach the input.
inheritAttrs: false,
})
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
/** Fills the answer on mount and after a native form reset. */
defaultValue?: string | number
disabled?: boolean
/** Controlled value. Use with `v-model`. */
modelValue?: string | number
type?: QuestionnaireInputType
}>(), {
disabled: false,
type: 'text',
})
const emits = defineEmits<{
'update:modelValue': [value: string]
}>()
const item = injectQuestionnaireItemContext()
const answerId = useId()
const inputElement = ref<HTMLInputElement | null>(null)
const initialDefaultFilled = hasInputValue(props.defaultValue)
const uncontrolledValue = ref(String(props.defaultValue ?? ''))
const controlled = computed(() => props.modelValue !== undefined)
const defaultFilled = computed(() => hasInputValue(props.defaultValue))
const disabled = computed(() => item.disabled.value || props.disabled)
// Vue re-applies `value` on every render, so the input always renders the value
// the questionnaire owns instead of an undefined binding that would clear it.
const value = computed(() =>
controlled.value ? String(props.modelValue ?? '') : uncontrolledValue.value)
const filled = computed(() => hasInputValue(value.value))
const selected = computed(() => item.selectedAnswerIds.value.includes(answerId))
function syncValueElement() {
if (inputElement.value && inputElement.value.value !== value.value) {
inputElement.value.value = value.value
}
}
function handleInput(event: Event) {
const nextValue = (event.target as HTMLInputElement).value
emits('update:modelValue', nextValue)
if (controlled.value) {
// The host owns the value, so restore whatever it kept.
nextTick(syncValueElement)
return
}
uncontrolledValue.value = nextValue
item.setAnswerSelectionFromInteraction(answerId, hasInputValue(nextValue))
}
const unregisterSelection = item.registerAnswerSelection(answerId, initialDefaultFilled)
let unregisterControl: (() => void) | null = null
watch([inputElement, disabled, () => props.disabled], ([element]) => {
unregisterControl?.()
unregisterControl = null
if (!element) {
return
}
unregisterControl = item.registerAnswerControl({
disabled: disabled.value,
element,
id: answerId,
ownDisabled: props.disabled,
type: 'input',
value: '',
})
}, { flush: 'post' })
watch(defaultFilled, (nextDefaultFilled) => {
item.setAnswerDefault(answerId, nextDefaultFilled)
})
// Watching the value as well as `filled` lets a host update clear the skipped
// state even when the answer stays filled.
watch([value, filled], () => {
if (controlled.value) {
item.syncControlledAnswerSelection(answerId, filled.value)
}
}, { immediate: true })
watch(item.resetVersion, () => {
if (!controlled.value) {
uncontrolledValue.value = String(props.defaultValue ?? '')
}
})
watch([value, inputElement], () => {
if (!inputElement.value) {
return
}
// A native form reset restores `defaultValue`, so keep it in sync with the
// value the questionnaire owns.
inputElement.value.defaultValue = String(
(controlled.value ? props.modelValue : props.defaultValue) ?? '',
)
}, { flush: 'post' })
onBeforeUnmount(() => {
unregisterControl?.()
unregisterControl = null
unregisterSelection()
})
</script>
<template>
<div
data-slot="questionnaire-input-wrapper"
class="w-full group/questionnaire-input relative min-w-0"
>
<input
v-bind="$attrs"
:id="answerId"
ref="inputElement"
data-slot="questionnaire-input"
:aria-invalid="item.invalid.value || undefined"
:aria-keyshortcuts="getAnswerKeyShortcuts(null, !disabled && filled && selected)"
:data-disabled="disabled ? '' : undefined"
:data-empty="filled ? undefined : ''"
:data-filled="filled ? '' : undefined"
:data-invalid="item.invalid.value ? '' : undefined"
:disabled="disabled"
:form="selected ? undefined : ''"
:name="selected ? item.name.value : undefined"
:type="props.type"
:value="value"
:class="cn(
'dark:bg-input/30 border-input focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 disabled:bg-input/50 dark:disabled:bg-input/80 h-8 rounded-lg border bg-transparent px-2.5 py-1 text-base focus-visible:ring-3 aria-invalid:ring-3 md:text-sm min-h-11 w-full min-w-0 transition-[color,box-shadow,background-color] outline-none disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-0',
'selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground',
props.class,
)"
@input="handleInput"
>
</div>
</template>
@@ -0,0 +1,467 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type { AnswerControlRegistration, QuestionnaireItemStatus } from './useQuestionnaire'
import { cn } from '@/lib/utils'
import { computed, onBeforeUnmount, ref, shallowRef, useAttrs, watch } from 'vue'
import {
compareDocumentOrder,
getShortcutByChoiceValue,
getShortcutKeys,
injectQuestionnaireRootContext,
isAnswerFilled,
isEmptyNavigableInput,
isRadioTarget,
isTextEntryTarget,
provideQuestionnaireItemContext,
} from './useQuestionnaire'
defineOptions({
inheritAttrs: false,
})
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
/** Excludes the item from the questionnaire without unmounting it. */
disabled?: boolean
/** Marks the item invalid from outside, for example after schema validation. */
invalid?: boolean
/** Renders choices as checkboxes and keeps every selected answer. */
multiple?: boolean
/** Submitted under this name, and used to activate the item. */
name: string
/** Requires an answer before the questionnaire can continue. */
required?: boolean
}>(), {
disabled: false,
invalid: false,
multiple: false,
required: false,
})
const emits = defineEmits<{
'update:status': [status: QuestionnaireItemStatus]
}>()
const attrs = useAttrs()
const root = injectQuestionnaireRootContext()
const itemElement = ref<HTMLFieldSetElement | null>(null)
const answerControls = shallowRef<AnswerControlRegistration[]>([])
const selectedAnswerIds = ref<string[]>([])
const validationAttempted = ref(false)
const skipped = ref(false)
const resetVersion = ref(0)
const controlSyncVersion = ref(0)
const descriptionIds = ref<string[]>([])
const errorIds = ref<string[]>([])
const titleIds = ref<string[]>([])
let defaultSelectedAnswerIds: string[] = []
const active = computed(() => !props.disabled && root.activeItemName.value === props.name)
const orderedAnswerControls = computed(() => {
// Re-sort whenever answers are added to or removed from the DOM.
void root.domVersion.value
return [...answerControls.value].sort((first, second) =>
compareDocumentOrder(first.element, second.element))
})
const answers = computed(() => orderedAnswerControls.value.filter(answer => !answer.disabled))
const answered = computed(() =>
answers.value.some(answer => selectedAnswerIds.value.includes(answer.id)))
const status = computed<QuestionnaireItemStatus>(() => {
if (skipped.value) {
return 'skipped'
}
return answered.value ? 'answered' : 'unanswered'
})
const intentionallySkipped = computed(() => status.value === 'skipped' && !props.required)
const valid = computed(() =>
props.disabled
|| intentionallySkipped.value
|| (!props.invalid && status.value === 'answered'))
const invalid = computed(() =>
!props.disabled
&& !intentionallySkipped.value
&& (props.invalid || (validationAttempted.value && !valid.value)))
const hasInputAnswer = computed(() => answers.value.some(answer => answer.type === 'input'))
const itemDefinition = computed(() => root.itemDefinitionByName.value?.get(props.name))
const shortcutByChoiceValue = computed(() =>
root.itemDefinitionByName.value
? getShortcutByChoiceValue(itemDefinition.value, root.shortcuts.value)
: null)
const shortcutByAnswerId = computed(() => {
// Choice values from `items` take precedence, so shortcuts stay stable.
if (shortcutByChoiceValue.value) {
return new Map<string, string>()
}
const keys = getShortcutKeys(root.shortcuts.value)
const shortcutAnswers = answers.value.filter(answer => answer.type === 'choice')
return new Map(
shortcutAnswers
.slice(0, keys.length)
.flatMap((answer, index) => (keys[index] ? [[answer.id, keys[index]!] as const] : [])),
)
})
// Only set when the title does not render as the legend, which already names
// the fieldset on its own.
const labelledBy = computed(() =>
[...titleIds.value, attrs['aria-labelledby']].filter(Boolean).join(' ') || undefined)
const describedBy = computed(() =>
[...descriptionIds.value, ...(invalid.value ? errorIds.value : []), attrs['aria-describedby']]
.filter(Boolean)
.join(' ') || undefined)
const keyShortcuts = computed(() =>
[
attrs['aria-keyshortcuts'],
active.value ? 'Meta+Enter Control+Enter' : undefined,
active.value && answers.value.length ? 'ArrowUp ArrowDown' : undefined,
active.value && !root.first.value ? 'ArrowLeft' : undefined,
active.value && !root.last.value && status.value !== 'unanswered' ? 'ArrowRight' : undefined,
]
.filter(Boolean)
.join(' ') || undefined)
function updateAnswerSelected(answerId: string, selected: boolean) {
if (!selected) {
selectedAnswerIds.value = selectedAnswerIds.value.filter(current => current !== answerId)
return
}
if (!props.multiple) {
selectedAnswerIds.value = [answerId]
return
}
if (!selectedAnswerIds.value.includes(answerId)) {
selectedAnswerIds.value = [...selectedAnswerIds.value, answerId]
}
}
function setAnswerSelectionFromInteraction(answerId: string, selected: boolean) {
skipped.value = false
updateAnswerSelected(answerId, selected)
}
function syncControlledAnswerSelection(answerId: string, selected: boolean) {
if (selected) {
skipped.value = false
}
updateAnswerSelected(answerId, selected)
}
function registerAnswerSelection(answerId: string, defaultSelected: boolean) {
if (defaultSelected) {
defaultSelectedAnswerIds = [
...defaultSelectedAnswerIds.filter(current => current !== answerId),
answerId,
]
if (!props.multiple) {
if (!selectedAnswerIds.value.length) {
selectedAnswerIds.value = [answerId]
}
}
else if (!selectedAnswerIds.value.includes(answerId)) {
selectedAnswerIds.value = [...selectedAnswerIds.value, answerId]
}
}
return () => {
defaultSelectedAnswerIds = defaultSelectedAnswerIds.filter(current => current !== answerId)
selectedAnswerIds.value = selectedAnswerIds.value.filter(current => current !== answerId)
}
}
function setAnswerDefault(answerId: string, defaultSelected: boolean) {
if (defaultSelected) {
if (!defaultSelectedAnswerIds.includes(answerId)) {
defaultSelectedAnswerIds = [...defaultSelectedAnswerIds, answerId]
}
return
}
defaultSelectedAnswerIds = defaultSelectedAnswerIds.filter(current => current !== answerId)
}
/**
* Selecting a controlled choice clears the native checked state of the other
* choices in the group, so every control re-syncs after an interaction the host
* may have rejected.
*/
function requestControlSync() {
controlSyncVersion.value += 1
}
function registerAnswerControl(registration: AnswerControlRegistration) {
answerControls.value = [
...answerControls.value.filter(
current => current.element !== registration.element && current.id !== registration.id,
),
registration,
]
return () => {
answerControls.value = answerControls.value.filter(current => current !== registration)
}
}
function registerDescription(descriptionId: string) {
if (!descriptionIds.value.includes(descriptionId)) {
descriptionIds.value = [...descriptionIds.value, descriptionId]
}
return () => {
descriptionIds.value = descriptionIds.value.filter(current => current !== descriptionId)
}
}
function registerTitle(titleId: string) {
if (!titleIds.value.includes(titleId)) {
titleIds.value = [...titleIds.value, titleId]
}
return () => {
titleIds.value = titleIds.value.filter(current => current !== titleId)
}
}
function registerError(errorId: string) {
if (!errorIds.value.includes(errorId)) {
errorIds.value = [...errorIds.value, errorId]
}
return () => {
errorIds.value = errorIds.value.filter(current => current !== errorId)
}
}
function validate() {
validationAttempted.value = true
if (!valid.value) {
return false
}
if (!root.nativeValidation.value) {
return true
}
const invalidAnswer = answers.value.find(
answer =>
isAnswerFilled(answer) && answer.element.willValidate && !answer.element.validity.valid,
)
if (!invalidAnswer) {
return true
}
invalidAnswer.element.focus()
invalidAnswer.element.reportValidity()
return false
}
function focus() {
itemElement.value?.focus()
}
function focusInvalid() {
const selectedInput = itemElement.value?.querySelector<HTMLInputElement>(
'input[data-filled][name]:not(:disabled)',
)
const firstControl = itemElement.value?.querySelector<HTMLElement>(
'input:not([type=hidden]):not(:disabled), textarea:not(:disabled)',
)
;(selectedInput ?? firstControl ?? itemElement.value)?.focus()
}
function reset() {
validationAttempted.value = false
skipped.value = false
selectedAnswerIds.value = props.multiple
? [...defaultSelectedAnswerIds]
: defaultSelectedAnswerIds.slice(0, 1)
resetVersion.value += 1
}
function skip() {
if (props.required) {
return
}
selectedAnswerIds.value = []
skipped.value = true
}
function getAnswerByElement(element: Element) {
return answers.value.find(answer => answer.element === element) ?? null
}
function getAnswerByShortcut(shortcut: string) {
if (shortcutByChoiceValue.value) {
const choiceValue = Array.from(shortcutByChoiceValue.value.entries()).find(
([, choiceShortcut]) => choiceShortcut === shortcut,
)?.[0]
return (
answers.value.find(answer => answer.type === 'choice' && answer.value === choiceValue) ?? null
)
}
const answerId = Array.from(shortcutByAnswerId.value.entries()).find(
([, answerShortcut]) => answerShortcut === shortcut,
)?.[0]
return answers.value.find(answer => answer.id === answerId) ?? null
}
function moveAnswerFocus(currentElement: Element, direction: 'next' | 'previous') {
const currentIndex = answers.value.findIndex(answer => answer.element === currentElement)
const currentAnswer = currentIndex < 0 ? null : (answers.value[currentIndex] ?? null)
if (
!answers.value.length
|| (isTextEntryTarget(currentElement) && !isEmptyNavigableInput(currentAnswer))
|| (currentIndex < 0 && currentElement !== itemElement.value)
) {
return false
}
const nextAnswer
= currentIndex < 0
? (answers.value.find(isAnswerFilled)
?? (direction === 'next' ? answers.value[0] : answers.value[answers.value.length - 1]))
: answers.value[
(currentIndex + (direction === 'next' ? 1 : -1) + answers.value.length)
% answers.value.length
]
if (!nextAnswer || nextAnswer.element === currentElement) {
return false
}
// Radio groups already move focus with the arrow keys.
if (
currentIndex >= 0
&& isRadioTarget(currentElement)
&& isRadioTarget(nextAnswer.element)
) {
return false
}
nextAnswer.element.focus()
if (nextAnswer.type === 'choice' && isRadioTarget(nextAnswer.element)) {
nextAnswer.element.click()
}
return true
}
watch(status, (nextStatus) => {
emits('update:status', nextStatus)
})
watch(() => props.multiple, (multiple, wasMultiple) => {
if (!wasMultiple || multiple) {
return
}
const selectedAnswer = answers.value.find(answer => selectedAnswerIds.value.includes(answer.id))
selectedAnswerIds.value = selectedAnswer ? [selectedAnswer.id] : []
})
let unregisterItem: (() => void) | null = null
watch([itemElement, () => props.name], ([element, name]) => {
unregisterItem?.()
unregisterItem = null
if (!element) {
return
}
unregisterItem = root.registerItem({
element,
focus,
focusInvalid,
getAnswerByElement,
getAnswerByShortcut,
getChoices: () =>
orderedAnswerControls.value.flatMap(answer =>
answer.type === 'choice' ? [{ disabled: answer.ownDisabled, value: answer.value }] : []),
isDisabled: () => props.disabled,
isRequired: () => props.required,
moveAnswerFocus,
name,
reset,
skip,
status: () => status.value,
validate,
})
}, { flush: 'post' })
onBeforeUnmount(() => {
unregisterItem?.()
unregisterItem = null
})
provideQuestionnaireItemContext({
active,
controlSyncVersion,
disabled: computed(() => props.disabled),
hasInputAnswer,
invalid,
multiple: computed(() => props.multiple),
name: computed(() => props.name),
registerAnswerControl,
registerAnswerSelection,
registerDescription,
registerError,
registerTitle,
requestControlSync,
required: computed(() => props.required),
resetVersion,
selectedAnswerIds,
setAnswerDefault,
setAnswerSelectionFromInteraction,
shortcutByAnswerId,
shortcutByChoiceValue,
shortcuts: root.shortcuts,
status,
syncControlledAnswerSelection,
})
</script>
<template>
<fieldset
v-bind="attrs"
ref="itemElement"
data-slot="questionnaire-item"
:aria-describedby="describedBy"
:aria-invalid="invalid || undefined"
:aria-keyshortcuts="keyShortcuts"
:aria-labelledby="labelledBy"
:data-active="active ? '' : undefined"
:data-disabled="props.disabled ? '' : undefined"
:data-invalid="invalid ? '' : undefined"
:data-multiple="props.multiple ? '' : undefined"
:data-required="props.required ? '' : undefined"
:data-status="status"
:disabled="props.disabled"
:hidden="!active"
:inert="!active"
tabindex="-1"
:class="cn('flex flex-col gap-4 min-w-0 border-0 p-0 outline-none', props.class)"
>
<slot :active="active" :invalid="invalid" :status="status" />
</fieldset>
</template>
@@ -0,0 +1,77 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'default',
})
const emits = defineEmits<{
click: [event: MouseEvent]
}>()
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.total.value > 1 && !root.last.value)
const shortcut = computed(() => (visible.value && !props.disabled ? 'Enter' : null))
function handleClick(event: MouseEvent) {
emits('click', event)
// `disabled` does not block clicks once `as` or `as-child` renders something
// other than a button.
if (props.disabled) {
event.preventDefault()
return
}
if (!event.defaultPrevented) {
root.goNext()
}
}
</script>
<template>
<Primitive
data-slot="questionnaire-next"
type="button"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:aria-keyshortcuts="shortcut ?? undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-shortcut="shortcut ?? undefined"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0',
props.class,
)"
@click="handleClick"
>
<slot>Next</slot>
</Primitive>
</template>
@@ -0,0 +1,74 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'outline',
})
const emits = defineEmits<{
click: [event: MouseEvent]
}>()
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.total.value > 1 && !root.first.value)
function handleClick(event: MouseEvent) {
emits('click', event)
// `disabled` does not block clicks once `as` or `as-child` renders something
// other than a button.
if (props.disabled) {
event.preventDefault()
return
}
if (!event.defaultPrevented) {
root.goPrevious()
}
}
</script>
<template>
<Primitive
data-slot="questionnaire-previous"
type="button"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-1 row-start-1 min-h-11 justify-self-start sm:min-h-0',
props.class,
)"
@click="handleClick"
>
<slot>Previous</slot>
</Primitive>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
}>(), {
as: 'div',
})
const root = injectQuestionnaireRootContext()
const label = computed(() =>
root.total.value ? `Question ${root.current.value} of ${root.total.value}` : undefined)
</script>
<template>
<Primitive
aria-label="Questionnaire progress"
aria-live="polite"
data-slot="questionnaire-progress"
role="progressbar"
:aria-valuemax="root.total.value || undefined"
:aria-valuemin="root.total.value ? 1 : undefined"
:aria-valuenow="root.total.value ? root.current.value : undefined"
:aria-valuetext="label"
:as="props.as"
:as-child="props.asChild"
:data-current="root.current.value"
:data-first="root.first.value ? '' : undefined"
:data-last="root.last.value ? '' : undefined"
:data-total="root.total.value"
:class="cn(
'text-xs min-h-[1lh] w-fit min-w-[14ch] font-medium text-muted-foreground tabular-nums',
props.class,
)"
>
<slot
:current="root.current.value"
:first="root.first.value"
:last="root.last.value"
:total="root.total.value"
>
{{ label }}
</slot>
</Primitive>
</template>
@@ -0,0 +1,74 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'outline',
})
const emits = defineEmits<{
click: [event: MouseEvent]
}>()
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.activeItemRequired.value === false)
function handleClick(event: MouseEvent) {
emits('click', event)
// `disabled` does not block clicks once `as` or `as-child` renders something
// other than a button.
if (props.disabled) {
event.preventDefault()
return
}
if (!event.defaultPrevented) {
root.skipCurrent()
}
}
</script>
<template>
<Primitive
data-slot="questionnaire-skip"
type="button"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-2 row-start-1 min-h-11 justify-self-end sm:min-h-0',
props.class,
)"
@click="handleClick"
>
<slot>Skip</slot>
</Primitive>
</template>
@@ -0,0 +1,57 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'default',
})
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.total.value > 0 && root.last.value)
const shortcut = computed(() => (visible.value && !props.disabled ? 'Enter' : null))
</script>
<template>
<Primitive
data-slot="questionnaire-submit"
type="submit"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:aria-keyshortcuts="shortcut ?? undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-shortcut="shortcut ?? undefined"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0',
props.class,
)"
>
<slot>Submit</slot>
</Primitive>
</template>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { ComponentPublicInstance, HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { onBeforeUnmount, onMounted, ref, useId } from 'vue'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
id?: string
}>(), {
as: 'legend',
})
const item = injectQuestionnaireItemContext()
const primitiveRef = ref<ComponentPublicInstance | null>(null)
const fallbackId = props.id ?? useId()
let unregisterTitle: (() => void) | null = null
onMounted(() => {
const element = primitiveRef.value?.$el as HTMLElement | undefined
// A legend already names the fieldset. Anything else, for example a
// DialogTitle rendered through `as-child`, has to name it explicitly.
if (!element || element.tagName === 'LEGEND') {
return
}
if (!element.id) {
element.id = fallbackId
}
unregisterTitle = item.registerTitle(element.id)
})
onBeforeUnmount(() => unregisterTitle?.())
</script>
<template>
<Primitive
v-bind="props.id ? { id: props.id } : {}"
ref="primitiveRef"
data-slot="questionnaire-title"
:as="props.as"
:as-child="props.asChild"
:class="cn('text-base leading-snug font-medium [&:not(:has(~[data-slot=questionnaire-description]))]:mb-4 cn-font-heading text-pretty', props.class)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,28 @@
export { default as Questionnaire } from './Questionnaire.vue'
export { default as QuestionnaireActions } from './QuestionnaireActions.vue'
export { default as QuestionnaireChoice } from './QuestionnaireChoice.vue'
export { default as QuestionnaireChoiceDescription } from './QuestionnaireChoiceDescription.vue'
export { default as QuestionnaireChoices } from './QuestionnaireChoices.vue'
export { default as QuestionnaireDescription } from './QuestionnaireDescription.vue'
export { default as QuestionnaireError } from './QuestionnaireError.vue'
export { default as QuestionnaireInput } from './QuestionnaireInput.vue'
export { default as QuestionnaireItem } from './QuestionnaireItem.vue'
export { default as QuestionnaireNext } from './QuestionnaireNext.vue'
export { default as QuestionnairePrevious } from './QuestionnairePrevious.vue'
export { default as QuestionnaireProgress } from './QuestionnaireProgress.vue'
export { default as QuestionnaireSkip } from './QuestionnaireSkip.vue'
export { default as QuestionnaireSubmit } from './QuestionnaireSubmit.vue'
export { default as QuestionnaireTitle } from './QuestionnaireTitle.vue'
export type {
QuestionnaireChoiceDefinition,
QuestionnaireInputType,
QuestionnaireItemDefinition,
QuestionnaireItemStatus,
QuestionnaireShortcutMode,
} from './useQuestionnaire'
export {
injectQuestionnaireItemContext,
injectQuestionnaireRootContext,
} from './useQuestionnaire'
@@ -0,0 +1,271 @@
import type { ComputedRef, Ref } from 'vue'
import { createContext } from 'reka-ui'
export type QuestionnaireItemStatus = 'unanswered' | 'answered' | 'skipped'
export type QuestionnaireShortcutMode = 'letters' | 'numbers'
export type QuestionnaireInputType
= | 'date'
| 'datetime-local'
| 'email'
| 'month'
| 'number'
| 'password'
| 'search'
| 'tel'
| 'text'
| 'time'
| 'url'
| 'week'
export interface QuestionnaireChoiceDefinition {
disabled?: boolean
value: string
}
export interface QuestionnaireItemDefinition {
choices?: readonly QuestionnaireChoiceDefinition[]
disabled?: boolean
name: string
required?: boolean
}
export interface ChoiceRegistration {
disabled: boolean
value: string
}
export interface AnswerControlRegistration {
disabled: boolean
element: HTMLInputElement
id: string
ownDisabled: boolean
type: 'choice' | 'input'
value: string
}
export interface ItemRegistration {
element: HTMLFieldSetElement
focus: () => void
focusInvalid: () => void
getAnswerByElement: (element: Element) => AnswerControlRegistration | null
getAnswerByShortcut: (shortcut: string) => AnswerControlRegistration | null
getChoices: () => ChoiceRegistration[]
isDisabled: () => boolean
isRequired: () => boolean
moveAnswerFocus: (element: Element, direction: 'next' | 'previous') => boolean
name: string
reset: () => void
skip: () => void
status: () => QuestionnaireItemStatus
validate: () => boolean
}
export interface QuestionnaireRootContext {
activeItem: ComputedRef<ItemRegistration | null>
activeItemName: ComputedRef<string | null>
activeItemRequired: ComputedRef<boolean | null>
activeItemStatus: ComputedRef<QuestionnaireItemStatus | null>
current: ComputedRef<number>
domVersion: Ref<number>
first: ComputedRef<boolean>
goNext: () => void
goPrevious: () => void
itemDefinitionByName: ComputedRef<Map<string, QuestionnaireItemDefinition> | null>
last: ComputedRef<boolean>
nativeValidation: ComputedRef<boolean>
registerItem: (registration: ItemRegistration) => () => void
shortcuts: ComputedRef<QuestionnaireShortcutMode | null>
skipCurrent: () => void
total: ComputedRef<number>
}
export interface QuestionnaireItemContext {
active: ComputedRef<boolean>
/** Bumped after a controlled answer interaction so every control re-syncs. */
controlSyncVersion: Ref<number>
disabled: ComputedRef<boolean>
hasInputAnswer: ComputedRef<boolean>
invalid: ComputedRef<boolean>
multiple: ComputedRef<boolean>
name: ComputedRef<string>
registerAnswerControl: (registration: AnswerControlRegistration) => () => void
registerAnswerSelection: (answerId: string, defaultSelected: boolean) => () => void
registerDescription: (descriptionId: string) => () => void
registerError: (errorId: string) => () => void
/** Only used when the title does not render as the fieldset legend. */
registerTitle: (titleId: string) => () => void
requestControlSync: () => void
required: ComputedRef<boolean>
resetVersion: Ref<number>
selectedAnswerIds: Ref<string[]>
setAnswerDefault: (answerId: string, defaultSelected: boolean) => void
setAnswerSelectionFromInteraction: (answerId: string, selected: boolean) => void
shortcutByAnswerId: ComputedRef<Map<string, string>>
shortcutByChoiceValue: ComputedRef<Map<string, string> | null>
shortcuts: ComputedRef<QuestionnaireShortcutMode | null>
status: ComputedRef<QuestionnaireItemStatus>
syncControlledAnswerSelection: (answerId: string, selected: boolean) => void
}
export const [injectQuestionnaireRootContext, provideQuestionnaireRootContext]
= createContext<QuestionnaireRootContext>('Questionnaire')
export const [injectQuestionnaireItemContext, provideQuestionnaireItemContext]
= createContext<QuestionnaireItemContext>('QuestionnaireItem')
export function hasInputValue(value: unknown) {
if (Array.isArray(value)) {
return value.some(item => String(item).trim().length > 0)
}
return value !== undefined && value !== null && String(value).trim().length > 0
}
export function getShortcutKeys(shortcuts: QuestionnaireShortcutMode | null) {
if (shortcuts === 'letters') {
return Array.from({ length: 26 }, (_, index) => String.fromCharCode(65 + index))
}
if (shortcuts === 'numbers') {
return Array.from({ length: 9 }, (_, index) => String(index + 1))
}
return []
}
export function getShortcutFromKey(key: string, shortcuts: QuestionnaireShortcutMode) {
const normalizedKey = shortcuts === 'letters' ? key.toUpperCase() : key
return getShortcutKeys(shortcuts).includes(normalizedKey) ? normalizedKey : null
}
export function getAnswerKeyShortcuts(shortcut: string | null, filled: boolean) {
return [shortcut, filled ? 'Enter' : null].filter(Boolean).join(' ') || undefined
}
export function isAnswerFilled(answer: AnswerControlRegistration) {
if (answer.type === 'choice') {
return answer.element.checked
}
return answer.element.hasAttribute('name') && hasInputValue(answer.element.value)
}
export function isEmptyNavigableInput(answer: AnswerControlRegistration | null) {
return (
answer?.type === 'input'
&& ['email', 'password', 'search', 'tel', 'text', 'url'].includes(answer.element.type)
&& !hasInputValue(answer.element.value)
)
}
export function isTextEntryTarget(element: Element) {
if (element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {
return true
}
if (element instanceof HTMLInputElement) {
return !['button', 'checkbox', 'radio', 'reset', 'submit'].includes(element.type)
}
return element instanceof HTMLElement && element.isContentEditable
}
export function isRadioTarget(element: Element) {
return element instanceof HTMLInputElement && element.type === 'radio'
}
/**
* Sort registrations by the position of their element in the document, so that
* navigation always follows the rendered order instead of the mount order.
*/
export function compareDocumentOrder(first: Element, second: Element) {
if (first === second) {
return 0
}
const position = first.compareDocumentPosition(second)
if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
return -1
}
if (position & Node.DOCUMENT_POSITION_PRECEDING) {
return 1
}
return 0
}
export interface QuestionnaireCollection {
enabledItems: QuestionnaireItemDefinition[]
itemByName: Map<string, QuestionnaireItemDefinition>
items: readonly QuestionnaireItemDefinition[]
}
export function createQuestionnaireCollection(
items: readonly QuestionnaireItemDefinition[] | undefined,
): QuestionnaireCollection | null {
if (items === undefined) {
return null
}
return {
enabledItems: items.filter(item => !item.disabled),
itemByName: new Map(items.map(item => [item.name, item])),
items,
}
}
export function getInitialItemName(
collection: QuestionnaireCollection | null,
defaultItem: string | undefined,
) {
if (!collection) {
return defaultItem ?? null
}
const defaultDefinition = defaultItem ? collection.itemByName.get(defaultItem) : undefined
if (defaultDefinition && !defaultDefinition.disabled) {
return defaultDefinition.name
}
return collection.enabledItems[0]?.name ?? null
}
/**
* Map every enabled choice of an item definition to a keyboard shortcut, so
* that shortcuts stay stable regardless of how choices are rendered.
*/
export function getShortcutByChoiceValue(
item: QuestionnaireItemDefinition | undefined,
shortcuts: QuestionnaireShortcutMode | null,
) {
const shortcutByChoiceValue = new Map<string, string>()
if (!item || !shortcuts) {
return shortcutByChoiceValue
}
const keys = getShortcutKeys(shortcuts)
let shortcutIndex = 0
for (const choice of item.choices ?? []) {
if (choice.disabled) {
continue
}
const shortcut = keys[shortcutIndex]
if (!shortcut) {
break
}
shortcutByChoiceValue.set(choice.value, shortcut)
shortcutIndex += 1
}
return shortcutByChoiceValue
}