Skip to main content
Version: v1 (Current)

Composable and flow helper API

Generated from public Vue/TypeScript exports by pnpm docs:generate. Edit source comments and stories to update this reference. Types describe the declared API; browser/device constraints are covered in the guides. This catalog reflects source commit fc6bfb108634735f1657e533206c3f8702ad357d; match your installed package and typed manifest before using an export. Source review does not establish registry-release availability.

badgeVariants​

import { badgeVariants } from '@gxp-dev/app-ui'

Returns string.

ParameterTypeRequired / default
props(ConfigVariants<{ variant: { default: string; secondary: string; destructive: string; outline: string; }; }> & ClassProp) | undefinedOptional

buildElementRules​

Compiles a FormElementDef's declarative validation props into a vee-validate typed schema (Zod under the hood). Pass validation.rules to replace the generated schema entirely.

import { buildElementRules } from '@gxp-dev/app-ui'

Returns TypedSchema<any, any> | undefined.

ParameterTypeRequired / default
elementFormElementDefRequired

element options​

NameTypeOptionalDescription
typeFormElementTypeNo—
namestringNoField name — the key this element's value is stored under.
labelstring | undefinedYes—
placeholderstring | undefinedYes—
helpstring | undefinedYesHelper text rendered under the control (FormDescription).
tooltipstring | undefinedYesInfo-icon tooltip rendered next to the label.
requiredboolean | undefinedYes—
disabledboolean | undefinedYes—
optionsFormElementOption[] | undefinedYesChoice list for select / autocomplete / radio / checkbox-group / toggle-group.
defaultValueunknownYes—
validationFormElementValidation | undefinedYes—
minnumber | undefinedYesnumber / slider / range / rating bounds and step.
maxnumber | undefinedYes—
stepnumber | undefinedYes—
rowsnumber | undefinedYestextarea rows.
multipleboolean | undefinedYesfile: allow multiple files / accepted mime types.
acceptstring | undefinedYes—
when((values: Record<string, unknown>) => boolean) | undefinedYesShow this element only when the predicate over current values is true.
controlPropsRecord<string, unknown> | undefinedYesExtra props forwarded verbatim to the underlying control.
classstring | undefinedYes—

buildElementSchema​

import { buildElementSchema } from '@gxp-dev/app-ui'

Returns ZodType<any, ZodTypeDef, any> | undefined.

ParameterTypeRequired / default
elementFormElementDefRequired

element options​

NameTypeOptionalDescription
typeFormElementTypeNo—
namestringNoField name — the key this element's value is stored under.
labelstring | undefinedYes—
placeholderstring | undefinedYes—
helpstring | undefinedYesHelper text rendered under the control (FormDescription).
tooltipstring | undefinedYesInfo-icon tooltip rendered next to the label.
requiredboolean | undefinedYes—
disabledboolean | undefinedYes—
optionsFormElementOption[] | undefinedYesChoice list for select / autocomplete / radio / checkbox-group / toggle-group.
defaultValueunknownYes—
validationFormElementValidation | undefinedYes—
minnumber | undefinedYesnumber / slider / range / rating bounds and step.
maxnumber | undefinedYes—
stepnumber | undefinedYes—
rowsnumber | undefinedYestextarea rows.
multipleboolean | undefinedYesfile: allow multiple files / accepted mime types.
acceptstring | undefinedYes—
when((values: Record<string, unknown>) => boolean) | undefinedYesShow this element only when the predicate over current values is true.
controlPropsRecord<string, unknown> | undefinedYesExtra props forwarded verbatim to the underlying control.
classstring | undefinedYes—

buttonVariants​

import { buttonVariants } from '@gxp-dev/app-ui'

Returns string.

ParameterTypeRequired / default
props(ConfigVariants<{ variant: { default: string; destructive: string; outline: string; secondary: string; ghost: string; link: string; }; size: { default: string; sm: string; lg: string; icon: string; "icon-sm": string; "icon-lg": string; }; }> & ClassProp) | undefinedOptional

cn​

Merge Tailwind CSS classes with clsx Handles conditional classes and resolves conflicts

import { cn } from '@gxp-dev/app-ui'

Returns string.

ParameterTypeRequired / default
inputsClassValue[]Required

convertToCanvasBlob​

Convert an image file to a canvas-generated blob. This standardizes the format to match camera captures.

import { convertToCanvasBlob } from '@gxp-dev/app-ui'

Returns Promise<Blob>.

ParameterTypeRequired / default
fileFileRequired
outputTypestring'image/jpeg'
qualitynumber1.0

file options​

NameTypeOptionalDescription
lastModifiednumberNoThe lastModified read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). MDN Reference
namestringNoThe name read-only property of the File interface returns the name of the file represented by a File object. MDN Reference
webkitRelativePathstringNoThe webkitRelativePath read-only property of the File interface contains a string which specifies the file's path relative to the directory selected by the user in an input element with its webkitdirectory attribute set. MDN Reference
sizenumberNoThe size read-only property of the Blob interface returns the size of the Blob or File in bytes. MDN Reference
typestringNoThe type read-only property of the Blob interface returns the MIME type of the file. MDN Reference
arrayBuffer() => Promise<ArrayBuffer>NoThe arrayBuffer() method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. MDN Reference
bytes() => Promise<Uint8Array<ArrayBuffer>>NoThe bytes() method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. MDN Reference
slice(start?: number, end?: number, contentType?: string) => BlobNoThe slice() method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called. MDN Reference
stream() => ReadableStream<Uint8Array<ArrayBuffer>>NoThe stream() method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob. MDN Reference
text() => Promise<string>NoThe text() method of the string containing the contents of the blob, interpreted as UTF-8. MDN Reference

delay​

Promise-based delay

import { delay } from '@gxp-dev/app-ui'

Returns Promise<void>.

ParameterTypeRequired / default
msnumberRequired

flattenElements​

Collect every element across a list of sections.

import { flattenElements } from '@gxp-dev/app-ui'

Returns FormElementDef[].

ParameterTypeRequired / default
sectionsFormSectionDef[]Required

flattenSectionElements​

Collect every element of a section, including nested sections'.

import { flattenSectionElements } from '@gxp-dev/app-ui'

Returns FormElementDef[].

ParameterTypeRequired / default
sectionFormSectionDefRequired

section options​

NameTypeOptionalDescription
idstringNo—
titlestring | undefinedYes—
descriptionstring | undefinedYes—
columns1 | 2 | 3 | 4 | undefinedYesGrid columns for this section's elements (default 1).
elementsFormElementDef[] | undefinedYes—
sectionsFormSectionDef[] | undefinedYesNested child sections, rendered after elements.
when((values: Record<string, unknown>) => boolean) | undefinedYesShow this section only when the predicate over current values is true.
classstring | undefinedYes—

initialValuesFor​

Initial form values derived from element defaultValues and types.

import { initialValuesFor } from '@gxp-dev/app-ui'

Returns Record<string, unknown>.

ParameterTypeRequired / default
sectionsFormSectionDef[]Required

loadFonts​

Dynamically load custom fonts via

import { loadFonts } from '@gxp-dev/app-ui'

Returns void.

ParameterTypeRequired / default
settingsFontSettingsRequired
assetsFontAssetsRequired
import { navigationMenuTriggerStyle } from '@gxp-dev/app-ui'

Returns string.

ParameterTypeRequired / default
propsClassProp | undefinedOptional

parseAIResponse​

Parse AI/LLM response text, extracting JSON from markdown code blocks

import { parseAIResponse } from '@gxp-dev/app-ui'

Returns Record<string, unknown>.

ParameterTypeRequired / default
responseTextstringRequired

preloadAssets​

Preload image assets by fetching them in parallel

import { preloadAssets } from '@gxp-dev/app-ui'

Returns Promise<Response>[].

ParameterTypeRequired / default
assetUrlsRecord<string, unknown>Required

processUploadedImage​

Process an uploaded image file to match camera capture format.

import { processUploadedImage } from '@gxp-dev/app-ui'

Returns Promise<Blob>.

ParameterTypeRequired / default
fileFileRequired

file options​

NameTypeOptionalDescription
lastModifiednumberNoThe lastModified read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). MDN Reference
namestringNoThe name read-only property of the File interface returns the name of the file represented by a File object. MDN Reference
webkitRelativePathstringNoThe webkitRelativePath read-only property of the File interface contains a string which specifies the file's path relative to the directory selected by the user in an input element with its webkitdirectory attribute set. MDN Reference
sizenumberNoThe size read-only property of the Blob interface returns the size of the Blob or File in bytes. MDN Reference
typestringNoThe type read-only property of the Blob interface returns the MIME type of the file. MDN Reference
arrayBuffer() => Promise<ArrayBuffer>NoThe arrayBuffer() method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. MDN Reference
bytes() => Promise<Uint8Array<ArrayBuffer>>NoThe bytes() method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. MDN Reference
slice(start?: number, end?: number, contentType?: string) => BlobNoThe slice() method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called. MDN Reference
stream() => ReadableStream<Uint8Array<ArrayBuffer>>NoThe stream() method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob. MDN Reference
text() => Promise<string>NoThe text() method of the string containing the contents of the blob, interpreted as UTF-8. MDN Reference

readExperienceDefaults​

import { readExperienceDefaults } from '@gxp-dev/app-ui'

Returns ExperiencePageDefaults.

ParameterTypeRequired / default
componentComponentRequired

Returned values and methods​

NameTypeDescription
actionExperienceAction | undefined—
resultKeystring | undefined—

simulateNfcScan​

Utility for testing: simulate an NFC scan event

import { simulateNfcScan } from '@gxp-dev/app-ui'

Returns void.

ParameterTypeRequired / default
uidstringRequired
tagTypestring'TAG_ISO_14443_3'

throttle​

Throttle a function to only execute once per wait period

import { throttle } from '@gxp-dev/app-ui'

Returns ThrottledFunction<T>.

ParameterTypeRequired / default
funcTRequired
waitnumberRequired
optionsThrottleOptions{}

options options​

NameTypeOptionalDescription
leadingboolean | undefinedYes—
trailingboolean | undefinedYes—

Returned values and methods​

NameTypeDescription
cancel() => void—

timeAgo​

Human-readable relative time string from an ISO date string

import { timeAgo } from '@gxp-dev/app-ui'

Returns string.

ParameterTypeRequired / default
isoStringstringRequired

useAnimations​

import { useAnimations } from '@gxp-dev/app-ui'

Returns UseAnimationsReturn.

Returned values and methods​

NameTypeDescription
animatingClassesComputedRef<string[]>—
pageAnimationRef<string, string>—
init(props: { globalSettings?: AnimationSettings; }) => void—
animatePage(vars?: AnimationVars, reverse?: boolean) => Promise<void>—
setSettings(settings?: AnimationSettings) => voidDeclarative model: apply the global animation settings.
resolveTransition(direction: AnimationDirection, leavingVars?: LeavingVars) => TransitionClassesDeclarative model: resolve the <transition> active classes for one move. Returns empty strings when animation is disabled (→ instant swap).

useCameraBorder​

import { useCameraBorder } from '@gxp-dev/app-ui'

Returns UseCameraBorderReturn.

Returned values and methods​

NameTypeDescription
selectedBorderRef<CameraBorder | null, CameraBorder | null>—
canvasDimensionsRef<CanvasDimensions, CanvasDimensions>—
drawBorder(imageSrc: string) => Promise<string>—
reset() => void—

useChatMedia​

Headless multi-participant chat media manager. Owns local audio/video/screen capture lifecycle and a registry of remote participant streams. Transport (Mediasoup, plain WebRTC peerconnections, server-relayed RTC, …) is your concern: provide handlers.onTrackStarted to push the local tracks to your producers, and call addParticipantTrack when a remote track arrives.

import { useChatMedia } from '@gxp-dev/app-ui'

Returns UseChatMediaReturn.

ParameterTypeRequired / default
optionsUseChatMediaOptions{}

options options​

NameTypeOptionalDescription
audioConstraintsMediaTrackConstraints | undefinedYes—
videoConstraintsMediaTrackConstraints | undefinedYes—
screenConstraintsDisplayMediaStreamOptions | undefinedYes—
handlersChatTrackHandlers | undefinedYes—

Returned values and methods​

NameTypeDescription
localAudioStreamRef<MediaStream | null, MediaStream | null>—
localVideoStreamRef<MediaStream | null, MediaStream | null>—
localScreenStreamRef<MediaStream | null, MediaStream | null>—
isMutedRef<boolean, boolean>—
isVideoOffRef<boolean, boolean>—
isScreenSharingRef<boolean, boolean>—
hasAudioComputedRef<boolean>—
hasVideoComputedRef<boolean>—
participantStreamsRef<Map<string, MediaStream>, Map<string, MediaStream>>—
startAudioCapture(constraints?: MediaTrackConstraints) => Promise<MediaStream>—
stopAudioCapture() => Promise<void>—
startVideoCapture(constraints?: MediaTrackConstraints) => Promise<MediaStream>—
stopVideoCapture() => Promise<void>—
startScreenShare(options?: DisplayMediaStreamOptions) => Promise<MediaStream>—
stopScreenShare() => Promise<void>—
toggleMute() => Promise<void>—
toggleVideo() => Promise<void>—
setParticipantStream(participantId: string, stream: MediaStream) => void—
addParticipantTrack(participantId: string, track: MediaStreamTrack) => MediaStream—
removeParticipant(participantId: string) => void—
getParticipantStream(participantId: string) => MediaStream | undefined—
cleanup() => void—

useChatMessages​

Headless chat-message state container. Owns the reactive message list, pagination cursor, reply/edit UI state, and push-event handlers. I/O is your responsibility — pass in an api object whose methods talk to your backend (REST, GraphQL, RPC, …) and the composable wraps them with optimistic local updates.

import { useChatMessages } from '@gxp-dev/app-ui'

Returns UseChatMessagesReturn.

ParameterTypeRequired / default
optionsUseChatMessagesOptionsRequired

options options​

NameTypeOptionalDescription
apiChatMessagesApiNo—
deletedPlaceholderstring | undefinedYesWhen set, replace [Message deleted] with your own placeholder text.
defaultLimitnumber | undefinedYesDefault page size for loadHistory.

Returned values and methods​

NameTypeDescription
messagesRef<ChatMessage[], ChatMessage[]>—
isLoadingRef<boolean, boolean>—
hasMoreRef<boolean, boolean>—
replyingToRef<ChatMessage | null, ChatMessage | null>—
editingMessageRef<ChatMessage | null, ChatMessage | null>—
messageCountComputedRef<number>—
oldestMessageIdComputedRef<string | number | undefined>—
newestMessageIdComputedRef<string | number | undefined>—
loadHistory(opts?: LoadHistoryOptions) => Promise<ChatMessage[]>—
sendMessage(content: string, attachments?: File[]) => Promise<ChatMessage>—
editMessage(id: ChatMessage["id"], newContent: string) => Promise<void>—
deleteMessage(id: ChatMessage["id"]) => Promise<void>—
addReaction(id: ChatMessage["id"], emoji: string) => Promise<void>—
removeReaction(id: ChatMessage["id"], emoji: string) => Promise<void>—
setReplyTo(message: ChatMessage | null) => void—
cancelReply() => void—
setEditing(message: ChatMessage | null) => void—
cancelEditing() => void—
clearMessages() => void—
handleNewMessage(message: ChatMessage) => void—
handleMessageEdited(data: { messageId: ChatMessage["id"]; content: string; editedAt?: string; }) => void—
handleMessageDeleted(messageId: ChatMessage["id"]) => void—
handleReactionAdded(data: { messageId: ChatMessage["id"]; emoji: string; participantId: string | number; }) => void—
handleReactionRemoved(data: { messageId: ChatMessage["id"]; emoji: string; participantId: string | number; }) => void—

useErrors​

import { useErrors } from '@gxp-dev/app-ui'

Returns UseErrorsReturn.

Returned values and methods​

NameTypeDescription
errorMessagesRef<string[], string[]>—
addError(message: string) => void—
removeError(index: number) => void—
clearErrors() => void—

useExperience​

import { useExperience } from '@gxp-dev/app-ui'

Returns UseExperienceReturn.

ParameterTypeRequired / default
configExperienceFlowConfigRequired

config options​

NameTypeOptionalDescription
pagesExperiencePageDef[]No—
apiExperienceApi | undefinedYes—
initialContextExperienceContext | undefinedYes—
onComplete((ctx: ExperienceContext) => void) | undefinedYesFired after the last page completes successfully.
onError((err: Error, ctx: ExperienceContext) => boolean | void) | undefinedYesFired when an action throws. Return true to swallow and stay on the page.

Returned values and methods​

NameTypeDescription
pagesComputedRef<ExperiencePageDef[]>—
currentPageComputedRef<ExperiencePageDef | null>—
pageNameComputedRef<string | null>—
indexRef<number, number>—
revisionRef<number, number>Session revision; reset remounts even when the first page stays selected.
isFirstComputedRef<boolean>—
isLastComputedRef<boolean>—
contextExperienceContext—
busyRef<boolean, boolean>—
errorRef<Error | null, Error | null>—
next(data?: unknown) => Promise<void>—
back() => void—
goTo(name: string) => Promise<void>—
reset() => void—
clearError() => void—
retry() => Promise<void>Rerun the failed action using the last submitted payload.
transitionRef<{ direction: "forward" | "back"; leavingVars: Record<string, unknown>; }, { direction: "forward" | "back"; leavingVars: Record<string, unknown>; }>Direction + leaving-page vars of the last navigation; the renderer reads this to pick the directional transition (set by next/back/goTo alike).

useExperienceApi​

Adapter that turns a callApi function into the named operations the experience flow expects. Pages bind to these operations by name via action: 'publishPost' etc. — keeping pages free of HTTP knowledge.

import { useExperienceApi } from '@gxp-dev/app-ui'

Returns ExperienceApi.

ParameterTypeRequired / default
optionsUseExperienceApiOptionsRequired

options options​

NameTypeOptionalDescription
callApiCallApiNo—
overridesPartial<ExperienceApi> | undefinedYesOverride or replace any individual operation.
endpointsPartial<Record<keyof ExperienceApi, string>> | undefinedYesOverride the default endpoint strings.

Returned values and methods​

NameTypeDescription
publishPost(data: PublishPostInput) => Promise<unknown>—
fetchPost(id: string | number, opts?: { include?: string[]; }) => Promise<unknown>—
fetchRecentPosts() => Promise<unknown>—
tagPost(id: string | number, tags: unknown[]) => Promise<unknown>—
createPrintJob(data: { social_stream_post_id: string | number; access_point_id?: string | number; }) => Promise<unknown>—
processImage(data: { blob: Blob; prompt?: string; background_remover?: boolean; background_generator?: boolean; }) => Promise<unknown>—
refinePrompt(prompt: string) => Promise<unknown>—
generateImages(data: { prompt: string; count?: number; }) => Promise<unknown>—
analyzeSketch(data: { blob: Blob; }) => Promise<unknown>—
call<T = unknown>(endpoint: string, payload?: unknown) => Promise<T>Escape hatch: pass through to the underlying callApi

useMedia​

import { useMedia } from '@gxp-dev/app-ui'

Returns UseMediaReturn.

Returned values and methods​

NameTypeDescription
devicesRef<MediaDevice[], MediaDevice[]>—
videoStreamRef<MediaStream | null, MediaStream | null>—
videoDeviceIdComputedRef<string | undefined>—
audioStreamRef<MediaStream | null, MediaStream | null>—
audioDeviceIdComputedRef<string | undefined>—
changingDeviceRef<boolean, boolean>—
recordingErrorRef<Error | null, Error | null>Async MediaRecorder/export failure for capture pages and custom clients.
videoBlobRef<Blob | null, Blob | null>—
videoURLRef<string | null, string | null>—
audioBlobRef<Blob | null, Blob | null>—
audioURLRef<string | null, string | null>—
audioVolumeWaveRef<number[], number[]>—
photoBlobRef<Blob | null, Blob | null>—
photoURLRef<string | null, string | null>—
facingModeComputedRef<string | undefined>—
currentFacingModeRef<string, string>—
getTrack(stream: MediaStream | null) => MediaStreamTrack | undefined—
setVideoDevice(device?: SetDeviceOptions) => Promise<MediaStream | undefined>—
setAudioDevice(device?: SetDeviceOptions) => Promise<MediaStream | undefined>—
startRecording(options: RecordingOptions) => void—
stopRecording() => void—
processUploadedVideo(file: File, targetAspectRatio?: number | null) => Promise<Blob>—
scaleCanvas(video: HTMLVideoElement, targetAspectRatio?: number | null) => ScaleCanvasResult—
drawToCanvas(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D, s: SourceRect, video: HTMLVideoElement, mirrored: boolean) => void—
resetState() => void—
requestCameraPermission(defaultMode?: string) => Promise<MediaStream>—
requestDevicePermission(constraints?: MediaStreamConstraints) => Promise<MediaStream>—
getAvailableDevices(kind?: MediaDeviceKind) => Promise<MediaDeviceInfo[]>—
isMobileDevice() => boolean—

useNfcListener​

import { useNfcListener } from '@gxp-dev/app-ui'

Returns UseNfcListenerReturn.

Returned values and methods​

NameTypeDescription
registerHandler(handler: NfcHandler) => () => void—

useQuestion​

Shared logic for question-shaped components (radio, multiple choice, essay, …). Pulls common state out so each component can focus on its own rendering.

import { useQuestion } from '@gxp-dev/app-ui'

Returns UseQuestionReturn<T>.

ParameterTypeRequired / default
propsUseQuestionInputProps<T>Required
emitUseQuestionEmit<T>Required

props options​

NameTypeOptionalDescription
questionQuestionDefinitionNo—
modelValueT | undefinedYes—
disabledboolean | undefinedYes—
readonlyboolean | undefinedYes—
showResultboolean | undefinedYes—
isCorrectboolean | null | undefinedYes—
feedbackstring | null | undefinedYes—

Returned values and methods​

NameTypeDescription
questionTextComputedRef<string>—
questionHintComputedRef<string>—
pointsComputedRef<number>—
isInteractiveComputedRef<boolean>—
resultClassComputedRef<"" | "question--correct" | "question--incorrect">—
displayFeedbackComputedRef<string | null>—
explanationComputedRef<string | null>—
updateAnswer(value: T) => void—
submitAnswer(value?: T | undefined) => void—
normalizeOptions(options: ReadonlyArray<string | UseQuestionOption>) => UseQuestionOption[]—

useScanning​

import { useScanning } from '@gxp-dev/app-ui'

Returns UseScanningReturn.

Returned values and methods​

NameTypeDescription
scanIsOpenRef<boolean, boolean>—
registeredScannerRef<boolean, boolean>—
ocrRef<boolean, boolean>—
openScanner() => void—
closeScanner() => void—
resetScanState() => void—

useStreamingAudio​

Continuous-stream audio I/O primitive. Use cases: - Real-time AI voice apps (Gemini Live, Realtime API, etc.) that emit PCM chunks and need them stitched into seamless playback. - Streaming TTS where audio arrives interleaved with other events. - Any pipeline that needs simultaneous mic capture + analyser visualisation + interruptible chunked playback. The playback path goes through a MediaStreamDestination + <audio> element so the browser's echo cancellation can use it as the AEC reference signal.

import { useStreamingAudio } from '@gxp-dev/app-ui'

Returns UseStreamingAudioReturn.

ParameterTypeRequired / default
optionsUseStreamingAudioOptions{}

options options​

NameTypeOptionalDescription
sampleRatenumber | undefinedYesSample rate for the AudioContext. Defaults to 48000 (good for ASR/TTS).
speechThresholdnumber | undefinedYesWhen the mic level crosses this, the speech-detection callback fires. 0-100 scale.
speechDebounceMsnumber | undefinedYesMinimum ms between speech-detection callback fires.
fftSizenumber | undefinedYesForce AnalyserNode FFT size.

Returned values and methods​

NameTypeDescription
audioContextRef<AudioContext | null, AudioContext | null>—
analyserRef<AnalyserNode | null, AnalyserNode | null>—
audioStreamRef<MediaStream | null, MediaStream | null>—
isCapturingRef<boolean, boolean>—
isMutedRef<boolean, boolean>—
audioLevelRef<number, number>Smoothed mic level on a 0-100 scale, updated each animation frame while capturing.
initialize() => Promise<AudioContext>—
startCapture(constraints?: MediaTrackConstraints) => Promise<MediaStream>—
stopCapture() => void—
toggleMute() => void—
cleanup() => void—
playPCMChunk(data: ArrayBuffer | Int16Array | string, sampleRate?: number) => voidSchedule a PCM16 chunk for sequential playback.
interruptPlayback() => voidStop everything in the playback queue and reset the scheduler.
getWaveformData() => Uint8Array—
getFrequencyData() => Uint8Array—
setSpeechDetectionCallback(cb: ((level: number) => void) | null) => void—

useToast​

Composable for showing toast notifications via vue-sonner. Requires the <Toaster /> component to be mounted in your app. Falls back to console logging if toast is unavailable.

import { useToast } from '@gxp-dev/app-ui'

Returns UseToastReturn.

Returned values and methods​

NameTypeDescription
success(message: string, options?: ToastOptions) => string | numberShow a success toast
error(message: string, options?: ToastOptions) => string | numberShow an error toast
warning(message: string, options?: ToastOptions) => string | numberShow a warning toast
info(message: string, options?: ToastOptions) => string | numberShow an info toast
show(message: string, options?: ToastOptions) => string | numberShow a generic toast
loading(message: string, options?: ToastOptions) => string | numberShow a loading toast, returns ID for updating
dismiss(id?: string | number) => voidDismiss a toast by ID, or all toasts if no ID
promise<T>(promise: Promise<T>, messages: { loading: string; success: string | ((data: T) => string); error: string | ((error: unknown) => string); }) => string | numberShow a promise-based toast

useWebSocket​

Generic WebSocket composable with auto-reconnect, event routing, and optional auth. Abstracted from the Gemini Live signaling pattern. Provides a clean API for JSON-based WebSocket communication with automatic reconnection.

import { useWebSocket } from '@gxp-dev/app-ui'

Returns UseWebSocketReturn.

ParameterTypeRequired / default
optionsUseWebSocketOptions{}

options options​

NameTypeOptionalDescription
authTokenstring | undefinedYesAuthentication token sent as first message after connection opens
authTypestring | undefinedYesMessage type field used for auth request (default: 'auth')
authResponseTypestring | undefinedYesMessage type expected in successful auth response (default: 'authenticated')
maxReconnectAttemptsnumber | undefinedYesMaximum reconnection attempts before status becomes 'failed' (default: 5)
reconnectDelaynumber | undefinedYesInitial delay between reconnection attempts in ms (default: 2000)
reconnectBackoffnumber | undefinedYesMultiply delay by this factor after each failed attempt (default: 1.5)
autoReconnectboolean | undefinedYesAutomatically reconnect on unexpected close (default: true)
autoDisconnectboolean | undefinedYesAutomatically disconnect on component unmount (default: true)
protocolsstring | string[] | undefinedYesProtocols to pass to WebSocket constructor
onOpen((event: Event) => void) | undefinedYesCalled when the connection opens (before auth)
onClose((event: CloseEvent) => void) | undefinedYesCalled when the connection closes
onError((event: Event) => void) | undefinedYesCalled on WebSocket error

Returned values and methods​

NameTypeDescription
statusReadonly<Ref<WebSocketStatus, WebSocketStatus>>Current connection status
reconnectCountReadonly<Ref<number, number>>Number of reconnection attempts so far
lastErrorReadonly<Ref<string | null, string | null>>Last error message, if any
connect(url: string, options?: { token?: string; }) => Promise<void>Connect to a WebSocket URL
send(type: string, data?: Record<string, unknown>) => voidSend a typed message (serialized to JSON)
sendRaw(data: string | ArrayBuffer | Blob) => voidSend raw string data
on(type: string, handler: (data: Record<string, unknown>) => void) => voidRegister a handler for a message type
off(type: string) => voidUnregister a handler for a message type
disconnect(code?: number, reason?: string) => voidDisconnect and clean up
isConnected() => booleanWhether the WebSocket is currently open

uuid​

Generate a UUID v4 string

import { uuid } from '@gxp-dev/app-ui'

Returns string.

withExperienceDefaults​

Attach experience-flow defaults (default action, result key) to a page component so the orchestrator can apply them when the user hasn't. Mutates component and returns it.

import { withExperienceDefaults } from '@gxp-dev/app-ui'

Returns C.

ParameterTypeRequired / default
componentCRequired
defaultsExperiencePageDefaultsRequired

defaults options​

NameTypeOptionalDescription
actionExperienceAction | undefinedYes—
resultKeystring | undefinedYes—

badgeVariants example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

buildElementRules example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

buildElementSchema example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

buttonVariants example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

cn example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

convertToCanvasBlob example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

delay example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

flattenElements example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

flattenSectionElements example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

initialValuesFor example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

loadFonts example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

parseAIResponse example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

preloadAssets example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

processUploadedImage example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

readExperienceDefaults example​

import { defineComponent, h } from 'vue'
import {
useExperience, useExperienceApi, withExperienceDefaults, readExperienceDefaults,
type CallApi,
} from '@gxp-dev/app-ui'

export function createDemoFlow() {
const Choice = defineComponent({
emits: ['next'],
setup(_props, { emit }) {
return () => h('button', { type: 'button', onClick: () => emit('next', 'portrait') }, 'Choose portrait')
},
})
const ChoicePage = withExperienceDefaults(Choice, { resultKey: 'selection' })
const defaults = readExperienceDefaults(ChoicePage)
const flow = useExperience({ pages: [{ name: 'choose', component: ChoicePage }] })
return { flow, defaults }
}

export function createApiBridge(callApi: CallApi) {
// In a DevTools app, bridge the store's operation ID, declared dependency
// identifier, and payload. Map used action endpoints to actual manifest IDs.
return useExperienceApi({ callApi })
}

simulateNfcScan example​

<script lang="ts" setup>
import { ref, onBeforeUnmount } from 'vue'
import { useNfcListener, simulateNfcScan, type NfcScanData } from '@gxp-dev/app-ui'

const log = ref<NfcScanData[]>([])
const { registerHandler } = useNfcListener()

const unregister = registerHandler((data) => {
log.value.unshift(data)
if (log.value.length > 8) log.value.pop()
})

onBeforeUnmount(unregister)

const fire = (): void => simulateNfcScan(crypto.randomUUID().slice(0, 8), 'iso-14443-a')
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[460px] max-w-full">
<h3 class="text-base font-semibold">useNfcListener demo</h3>

<button class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground" @click="fire">
simulateNfcScan()
</button>

<div>
<p class="mb-1 text-xs font-semibold text-muted-foreground">scan log</p>
<ul class="max-h-48 space-y-1 overflow-y-auto rounded-md bg-muted p-2 font-mono text-xs">
<li v-for="(entry, i) in log" :key="i">
uid={{ entry.uid }} type={{ entry.tagType }} t={{ entry.timestamp }}
</li>
<li v-if="!log.length" class="text-muted-foreground italic">no scans yet</li>
</ul>
</div>
</div>
</template>

throttle example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

timeAgo example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

useAnimations example​

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useAnimations } from '@gxp-dev/app-ui'

const props = defineProps<{
pageAnimationType?: string
pageAnimationSpeed?: string
}>()

const { init, animatingClasses, animatePage } = useAnimations()

const reapply = (): void => {
init({
globalSettings: {
page_animation_type: props.pageAnimationType ?? 'animate__fadeIn',
page_animation_speed: props.pageAnimationSpeed ?? 'animate__normal',
},
})
}
reapply()
watch(() => [props.pageAnimationType, props.pageAnimationSpeed], reapply)

const counter = ref(0)
const inFlight = ref(false)

const animate = async (reverse = false): Promise<void> => {
inFlight.value = true
await animatePage({ pluginVars: { animate_next: true, animate_prev: true } }, reverse)
counter.value++
inFlight.value = false
}
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[480px] max-w-full">
<h3 class="text-base font-semibold">useAnimations demo</h3>

<div class="flex gap-2">
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" :disabled="inFlight" @click="animate(false)">
Next
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" :disabled="inFlight" @click="animate(true)">
Previous
</button>
</div>

<div class="grid h-32 place-items-center rounded-md bg-muted p-4">
<div :class="animatingClasses">
<div class="rounded-md bg-primary px-6 py-3 font-semibold text-primary-foreground">
Frame #{{ counter }}
</div>
</div>
</div>

<pre class="rounded-md bg-muted p-3 font-mono text-xs">{{ { animatingClasses } }}</pre>
<p class="text-xs text-muted-foreground">
Note: animation classes come from animate.css. Pages in real use ship an animate.css import; this preview just shows the class strings.
</p>
</div>
</template>

useCameraBorder example​

<script lang="ts" setup>
import { ref } from 'vue'
import { useCameraBorder } from '@gxp-dev/app-ui'

const { selectedBorder, canvasDimensions, drawBorder, reset } = useCameraBorder()

canvasDimensions.value = { width: 600, height: 600 }

const SAMPLE_PHOTO = 'https://placehold.co/600x600/0ea5e9/fff?text=Photo'
const BORDERS = [
{ label: 'Frame A', src: 'https://placehold.co/600x600/ef4444/fff?text=Frame+A&font=raleway' },
{ label: 'Frame B', src: 'https://placehold.co/600x600/16a34a/fff?text=Frame+B&font=raleway' },
{ label: 'Frame C', src: 'https://placehold.co/600x600/9333ea/fff?text=Frame+C&font=raleway' },
]

const result = ref<string>('')
const error = ref<string>('')

const compose = async (): Promise<void> => {
error.value = ''
try {
result.value = await drawBorder(SAMPLE_PHOTO)
} catch (err) {
error.value = (err as Error).message
}
}
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[520px] max-w-full">
<h3 class="text-base font-semibold">useCameraBorder demo</h3>

<div>
<p class="mb-1 text-xs font-semibold text-muted-foreground">choose a border</p>
<div class="flex gap-2">
<button
v-for="b in BORDERS"
:key="b.src"
type="button"
:class="['overflow-hidden rounded-md border-2 transition-all', selectedBorder?.src === b.src ? 'border-primary' : 'border-transparent']"
@click="selectedBorder = b"
>
<img :src="b.src" :alt="b.label" class="h-16 w-16 object-cover" />
</button>
</div>
</div>

<div class="flex gap-2">
<button class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground" :disabled="!selectedBorder" @click="compose">
drawBorder(SAMPLE_PHOTO)
</button>
<button class="rounded-md bg-secondary px-4 py-2 text-sm font-medium text-secondary-foreground" @click="reset">
reset
</button>
</div>

<div v-if="result">
<p class="mb-1 text-xs font-semibold text-muted-foreground">result</p>
<img :src="result" alt="Composed" class="w-full rounded-md border border-border" />
</div>
<p v-if="error" class="text-sm text-destructive">{{ error }}</p>

<pre class="rounded-md bg-muted p-3 font-mono text-xs">{{ { selectedBorder, canvasDimensions } }}</pre>
</div>
</template>

useChatMedia example​

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useChatMedia, type ChatTrackKind } from '@gxp-dev/app-ui'

const log = ref<string[]>([])
const pushLog = (msg: string): void => {
log.value.unshift(`${new Date().toLocaleTimeString()} · ${msg}`)
if (log.value.length > 12) log.value.pop()
}

const media = useChatMedia({
handlers: {
onTrackStarted: (_track, kind: ChatTrackKind) => pushLog(`onTrackStarted(${kind})`),
onTrackStopping: (kind: ChatTrackKind) => pushLog(`onTrackStopping(${kind})`),
onAudioPaused: () => pushLog('onAudioPaused'),
onAudioResumed: () => pushLog('onAudioResumed'),
onVideoPaused: () => pushLog('onVideoPaused'),
onVideoResumed: () => pushLog('onVideoResumed'),
},
})

const videoRef = ref<HTMLVideoElement | null>(null)
const screenRef = ref<HTMLVideoElement | null>(null)

const wrap = async (label: string, fn: () => Promise<unknown> | unknown): Promise<void> => {
try {
await fn()
} catch (err) {
pushLog(`${label} failed: ${(err as Error).message}`)
}
}

const startAudio = (): Promise<void> => wrap('startAudio', () => media.startAudioCapture())
const startVideo = (): Promise<void> =>
wrap('startVideo', async () => {
await media.startVideoCapture()
if (videoRef.value && media.localVideoStream.value) {
videoRef.value.srcObject = media.localVideoStream.value
}
})
const startScreen = (): Promise<void> =>
wrap('startScreen', async () => {
await media.startScreenShare()
if (screenRef.value && media.localScreenStream.value) {
screenRef.value.srcObject = media.localScreenStream.value
}
})

const summary = computed(() => ({
hasAudio: media.hasAudio.value,
hasVideo: media.hasVideo.value,
isMuted: media.isMuted.value,
isVideoOff: media.isVideoOff.value,
isScreenSharing: media.isScreenSharing.value,
participants: media.participantStreams.value.size,
}))
</script>

<template>
<div class="space-y-4 rounded-lg border border-border bg-card p-4 text-card-foreground w-[640px] max-w-full">
<h3 class="text-base font-semibold">useChatMedia demo</h3>

<div class="flex flex-wrap gap-2">
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="startAudio">
Start audio
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="media.toggleMute()">
{{ media.isMuted.value ? 'Unmute' : 'Mute' }}
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="startVideo">
Start video
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="media.toggleVideo()">
Toggle video
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="startScreen">
Start screen
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="media.cleanup()">
Cleanup
</button>
</div>

<div class="grid grid-cols-2 gap-3">
<div>
<p class="mb-1 text-xs text-muted-foreground">local video</p>
<video ref="videoRef" autoplay playsinline muted class="h-32 w-full rounded-md bg-black object-cover" />
</div>
<div>
<p class="mb-1 text-xs text-muted-foreground">screen share</p>
<video ref="screenRef" autoplay playsinline muted class="h-32 w-full rounded-md bg-black object-cover" />
</div>
</div>

<pre class="rounded-md bg-muted p-3 font-mono text-xs">{{ summary }}</pre>

<div>
<p class="mb-1 text-xs font-semibold text-muted-foreground">handler log</p>
<ul class="max-h-32 space-y-0.5 overflow-y-auto rounded-md bg-background p-2 font-mono text-xs">
<li v-for="(line, i) in log" :key="i">{{ line }}</li>
<li v-if="!log.length" class="text-muted-foreground italic">no events yet</li>
</ul>
</div>
</div>
</template>

useChatMessages example​

<script lang="ts" setup>
import { ref } from 'vue'
import { useChatMessages, type ChatMessage, type ChatMessagesApi } from '@gxp-dev/app-ui'

let nextId = 0

// In-memory mock api so the demo is fully self-contained.
const seed: ChatMessage[] = [
{ id: ++nextId, content: 'Welcome to the demo room 👋' },
{ id: ++nextId, content: 'Try sending a message, then click "Simulate inbound" to see the push handler.' },
]

const mockApi: ChatMessagesApi = {
loadHistory: async () => ({ messages: [...seed], hasMore: false }),
sendMessage: async (input) => {
await new Promise((r) => setTimeout(r, 250))
return { id: ++nextId, content: input.content, reply_to: input.reply_to ?? null }
},
editMessage: async () => undefined,
deleteMessage: async () => undefined,
addReaction: async () => undefined,
removeReaction: async () => undefined,
}

const chat = useChatMessages({ api: mockApi })
chat.loadHistory()

const draft = ref('')

const send = async (): Promise<void> => {
if (!draft.value.trim()) return
const created = await chat.sendMessage(draft.value)
chat.handleNewMessage(created)
draft.value = ''
}

const simulateInbound = (): void => {
chat.handleNewMessage({
id: ++nextId,
content: 'A wild bot appears 🤖',
})
}

const reactTo = (messageId: ChatMessage['id'], emoji: string): void => {
chat.handleReactionAdded({ messageId, emoji, participantId: 'me' })
}
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[500px] max-w-full">
<h3 class="text-base font-semibold">useChatMessages demo</h3>

<div class="h-64 space-y-2 overflow-y-auto rounded-md border border-border bg-background p-3">
<div
v-for="m in chat.messages.value"
:key="m.id"
class="rounded-md bg-muted p-2 text-sm"
:class="{ 'opacity-50': m.is_deleted }"
>
<p>{{ m.content }}</p>
<div class="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
<span>#{{ m.id }}</span>
<span v-if="m.is_edited">(edited)</span>
<button class="hover:text-primary" @click="reactTo(m.id, '👍')">👍</button>
<button class="hover:text-primary" @click="reactTo(m.id, '🎉')">🎉</button>
<button v-if="!m.is_deleted" class="hover:text-destructive" @click="chat.deleteMessage(m.id)">delete</button>
<span v-if="m.reactions?.length" class="ml-auto flex gap-1">
<span v-for="r in m.reactions" :key="r.emoji" class="rounded-full bg-primary/10 px-2 py-0.5 text-xs">
{{ r.emoji }} {{ r.count }}
</span>
</span>
</div>
</div>
</div>

<div class="flex gap-2">
<input
v-model="draft"
class="flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm"
placeholder="Type a message…"
@keyup.enter="send"
/>
<button class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground" @click="send">
Send
</button>
<button class="rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground" @click="simulateInbound">
Simulate inbound
</button>
</div>

<div class="rounded-md bg-muted p-3 font-mono text-xs">
<div>count: {{ chat.messageCount.value }} · loading: {{ chat.isLoading.value }} · hasMore: {{ chat.hasMore.value }}</div>
</div>
</div>
</template>

useErrors example​

<script lang="ts" setup>
import { ref } from 'vue'
import { useErrors } from '@gxp-dev/app-ui'

const { errorMessages, addError, removeError, clearErrors } = useErrors()
const draft = ref('Something went wrong')
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[480px] max-w-full">
<h3 class="text-base font-semibold">useErrors demo</h3>

<div class="flex gap-2">
<input
v-model="draft"
class="flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm"
placeholder="Error message…"
/>
<button class="rounded-md bg-destructive px-3 py-2 text-sm font-medium text-destructive-foreground" @click="addError(draft)">
addError
</button>
<button class="rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground" @click="clearErrors">
clear all
</button>
</div>

<ul v-if="errorMessages.length" class="space-y-1">
<li
v-for="(msg, i) in errorMessages"
:key="i"
class="flex items-center justify-between gap-2 rounded-md border border-destructive bg-destructive/10 p-2 text-sm text-destructive"
>
<span>{{ msg }}</span>
<button class="text-xs underline hover:no-underline" @click="removeError(i)">remove</button>
</li>
</ul>
<p v-else class="text-sm italic text-muted-foreground">no errors</p>

<pre class="rounded-md bg-muted p-3 font-mono text-xs">{{ { count: errorMessages.length, errorMessages } }}</pre>
</div>
</template>

useExperience example​

<script lang="ts" setup>
import { defineComponent, h } from 'vue'
import { useExperience, ExperienceFlow } from '@gxp-dev/app-ui'

const StubPage = (name: string, color: string) =>
defineComponent({
name,
emits: ['next', 'back'],
setup(_, { emit }) {
return () =>
h(
'section',
{
class: 'flex h-full w-full flex-col items-center justify-center gap-4 p-8 text-center',
style: { background: color },
},
[
h('h1', { class: 'text-2xl font-bold text-white drop-shadow' }, name),
h('div', { class: 'flex gap-2' }, [
h(
'button',
{ class: 'rounded-md bg-white/20 px-3 py-1 text-sm text-white', onClick: () => emit('back') },
'back',
),
h(
'button',
{ class: 'rounded-md bg-white px-3 py-1 text-sm font-semibold text-foreground', onClick: () => emit('next') },
'next →',
),
]),
],
)
},
})

const flow = useExperience({
pages: [
{ name: 'one', component: StubPage('Page One', '#0ea5e9') },
{ name: 'two', component: StubPage('Page Two', '#9333ea') },
{ name: 'three', component: StubPage('Page Three', '#16a34a') },
],
onComplete: () => flow.reset(),
})
</script>

<template>
<div class="grid h-[420px] w-[640px] grid-cols-[200px_1fr] overflow-hidden rounded-lg border border-border bg-card">
<aside class="space-y-3 border-r border-border bg-muted p-3 text-xs">
<div>
<div class="font-mono text-base"><strong>{{ flow.pageName.value }}</strong></div>
<div class="text-muted-foreground">
index {{ flow.index.value }} · busy {{ flow.busy.value }}
</div>
</div>
<div class="flex flex-wrap gap-1">
<button
v-for="p in flow.pages.value"
:key="p.name"
class="rounded-md border bg-card px-2 py-0.5 hover:bg-background"
:class="{ 'border-primary bg-primary/10': flow.pageName.value === p.name }"
@click="flow.goTo(p.name)"
>
{{ p.name }}
</button>
</div>
<button class="rounded-md bg-secondary px-3 py-1 text-secondary-foreground" @click="flow.reset()">reset</button>
</aside>
<main class="relative">
<ExperienceFlow :flow="flow" />
</main>
</div>
</template>

useExperienceApi example​

<script setup lang="ts">
import { ref } from 'vue'
import { useExperienceApi, type CallApi } from '@gxp-dev/app-ui'

const output = ref('No request yet')
const callApi: CallApi = async <T = unknown>(operation: string, payload?: unknown): Promise<T> => {
// Local mock only. Real apps provide their authenticated platform-store bridge.
return { operation, payload, id: 'demo-post' } as T
}
const api = useExperienceApi({ callApi })
async function publish() {
const result = await api.publishPost({ caption: 'Hello from the AppUI demo' })
output.value = JSON.stringify(result, null, 2)
}
</script>
<template>
<div class="space-y-4 rounded-lg border bg-card p-6 text-card-foreground">
<button type="button" class="primaryButton" @click="publish">Simulate publication</button>
<pre class="overflow-auto text-sm" role="status">{{ output }}</pre>
</div>
</template>

useMedia example​

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useMedia } from '@gxp-dev/app-ui'

const media = useMedia()
const videoRef = ref<HTMLVideoElement | null>(null)
const audioRef = ref<HTMLAudioElement | null>(null)

watch(media.videoStream, (stream) => {
if (videoRef.value) videoRef.value.srcObject = stream
})
watch(media.audioURL, (url) => {
if (audioRef.value) audioRef.value.src = url ?? ''
})

const log = ref<string[]>([])
const push = (msg: string): void => {
log.value.unshift(`${new Date().toLocaleTimeString()} · ${msg}`)
if (log.value.length > 12) log.value.pop()
}

const wrap = async (label: string, fn: () => Promise<unknown> | unknown): Promise<void> => {
try {
await fn()
push(`${label} ok`)
} catch (err) {
push(`${label} failed: ${(err as Error).message}`)
}
}

const takePhoto = (): void => {
if (!videoRef.value) return
const { canvas, ctx, s } = media.scaleCanvas(videoRef.value, 1)
if (!ctx) return
media.drawToCanvas(canvas, ctx, s, videoRef.value, true)
canvas.toBlob((blob) => {
if (blob) {
media.photoBlob.value = blob
push('photo captured')
}
})
}
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[640px] max-w-full">
<h3 class="text-base font-semibold">useMedia demo</h3>

<div class="flex flex-wrap gap-2">
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="wrap('setVideoDevice', () => media.setVideoDevice({ facingMode: 'user' }))">
camera
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="wrap('setAudioDevice', () => media.setAudioDevice())">
mic
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="takePhoto" :disabled="!media.videoStream.value">
photo
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="wrap('startRecording', () => media.startRecording({ audio: true, video: videoRef ?? undefined }))">
start record
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="media.stopRecording()">
stop record
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="media.resetState()">
reset
</button>
</div>

<div class="grid grid-cols-2 gap-3">
<div>
<p class="mb-1 text-xs text-muted-foreground">live video</p>
<video ref="videoRef" autoplay playsinline muted class="aspect-square w-full rounded-md bg-black object-cover" />
</div>
<div>
<p class="mb-1 text-xs text-muted-foreground">last photo</p>
<img v-if="media.photoURL.value" :src="media.photoURL.value" class="aspect-square w-full rounded-md object-cover" />
<div v-else class="grid aspect-square w-full place-items-center rounded-md bg-muted text-sm text-muted-foreground">none</div>
</div>
</div>

<div v-if="media.audioURL.value">
<p class="mb-1 text-xs text-muted-foreground">last audio</p>
<audio ref="audioRef" controls class="w-full" />
</div>

<pre class="rounded-md bg-muted p-3 font-mono text-xs">{{ {
hasVideo: !!media.videoStream.value,
hasAudio: !!media.audioStream.value,
facingMode: media.currentFacingMode.value,
isMobile: media.isMobileDevice(),
devicesCount: media.devices.value.length,
} }}</pre>

<ul class="max-h-32 space-y-0.5 overflow-y-auto rounded-md bg-background p-2 font-mono text-xs">
<li v-for="(line, i) in log" :key="i">{{ line }}</li>
<li v-if="!log.length" class="italic text-muted-foreground">no events</li>
</ul>
</div>
</template>

useNfcListener example​

<script lang="ts" setup>
import { ref, onBeforeUnmount } from 'vue'
import { useNfcListener, simulateNfcScan, type NfcScanData } from '@gxp-dev/app-ui'

const log = ref<NfcScanData[]>([])
const { registerHandler } = useNfcListener()

const unregister = registerHandler((data) => {
log.value.unshift(data)
if (log.value.length > 8) log.value.pop()
})

onBeforeUnmount(unregister)

const fire = (): void => simulateNfcScan(crypto.randomUUID().slice(0, 8), 'iso-14443-a')
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[460px] max-w-full">
<h3 class="text-base font-semibold">useNfcListener demo</h3>

<button class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground" @click="fire">
simulateNfcScan()
</button>

<div>
<p class="mb-1 text-xs font-semibold text-muted-foreground">scan log</p>
<ul class="max-h-48 space-y-1 overflow-y-auto rounded-md bg-muted p-2 font-mono text-xs">
<li v-for="(entry, i) in log" :key="i">
uid={{ entry.uid }} type={{ entry.tagType }} t={{ entry.timestamp }}
</li>
<li v-if="!log.length" class="text-muted-foreground italic">no scans yet</li>
</ul>
</div>
</div>
</template>

useQuestion example​

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useQuestion, type QuestionDefinition } from '@gxp-dev/app-ui'

const props = defineProps<{
questionDef?: QuestionDefinition
disabled?: boolean
readonly?: boolean
showResult?: boolean
isCorrect?: boolean | null
feedback?: string | null
}>()

const lastEvent = ref<string | null>(null)

const proxyProps = reactive({
question: props.questionDef ?? { label: 'What is 2 + 2?', points: 5, feedbackCorrect: 'Yes!' },
modelValue: '',
disabled: props.disabled ?? false,
readonly: props.readonly ?? false,
showResult: props.showResult ?? false,
isCorrect: props.isCorrect ?? null,
feedback: props.feedback ?? null,
})

const emit = (event: 'update:modelValue' | 'answer', value: unknown): void => {
lastEvent.value = `${event}(${JSON.stringify(value)})`
if (event === 'update:modelValue') proxyProps.modelValue = String(value ?? '')
}

const q = useQuestion(proxyProps, emit)
</script>

<template>
<div class="space-y-4 rounded-lg border border-border bg-card p-6 text-card-foreground">
<div>
<h3 class="text-lg font-semibold">{{ q.questionText.value }}</h3>
<p v-if="q.questionHint.value" class="text-sm text-muted-foreground">{{ q.questionHint.value }}</p>
<p class="mt-1 text-xs text-muted-foreground">
worth {{ q.points.value }} pts · interactive: {{ q.isInteractive.value }}
</p>
</div>

<input
v-model="proxyProps.modelValue"
type="text"
:disabled="!q.isInteractive.value"
class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
placeholder="Your answer…"
@input="q.updateAnswer(($event.target as HTMLInputElement).value)"
/>

<button
type="button"
class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
:disabled="!q.isInteractive.value"
@click="q.submitAnswer()"
>
Submit answer
</button>

<div v-if="q.displayFeedback.value" class="rounded-md p-3 text-sm" :class="q.resultClass.value === 'question--correct' ? 'bg-green-100 text-green-900' : 'bg-red-100 text-red-900'">
<strong>Feedback:</strong> {{ q.displayFeedback.value }}
<p v-if="q.explanation.value" class="mt-1 text-xs opacity-80">{{ q.explanation.value }}</p>
</div>

<div class="rounded-md bg-muted p-3 font-mono text-xs">
<div><strong>last event:</strong> {{ lastEvent ?? '(none)' }}</div>
<div><strong>modelValue:</strong> {{ JSON.stringify(proxyProps.modelValue) }}</div>
</div>
</div>
</template>

useScanning example​

<script lang="ts" setup>
import { useScanning } from '@gxp-dev/app-ui'

const { scanIsOpen, registeredScanner, ocr, openScanner, closeScanner, resetScanState } = useScanning()

const dispatchResetAll = (): void => {
document.body.dispatchEvent(new Event('reset-all'))
}
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[420px] max-w-full">
<h3 class="text-base font-semibold">useScanning demo</h3>

<div class="flex flex-wrap gap-2">
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="openScanner">
Open
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="closeScanner">
Close
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="resetScanState">
Reset
</button>
<button class="rounded-md bg-muted px-3 py-1.5 text-sm font-medium" @click="dispatchResetAll">
Dispatch 'reset-all'
</button>
</div>

<div class="rounded-md bg-muted p-3 font-mono text-xs">
scanIsOpen: <strong>{{ scanIsOpen }}</strong><br/>
registeredScanner: <strong>{{ registeredScanner }}</strong><br/>
ocr: <strong>{{ ocr }}</strong>
</div>

<div v-if="scanIsOpen" class="rounded-md border border-primary bg-primary/10 p-3 text-sm">
Scanner is open. (In a real app this would mount BarcodeScanner.)
</div>
</div>
</template>

useStreamingAudio example​

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useStreamingAudio } from '@gxp-dev/app-ui'

const log = ref<string[]>([])
const pushLog = (msg: string): void => {
log.value.unshift(`${new Date().toLocaleTimeString()} · ${msg}`)
if (log.value.length > 12) log.value.pop()
}

const audio = useStreamingAudio()
audio.setSpeechDetectionCallback((level) => pushLog(`speech detected at level ${level}`))

const wrap = async (label: string, fn: () => Promise<unknown> | void): Promise<void> => {
try {
await fn()
pushLog(label + ' ok')
} catch (err) {
pushLog(`${label} failed: ${(err as Error).message}`)
}
}

const onStart = (): Promise<void> => wrap('startCapture', () => audio.startCapture())

/**
* Generate a 250ms 440Hz sine-wave PCM16 chunk and feed it through the
* playback queue so users can hear the scheduler at work.
*/
const playTone = (): void => {
const rate = 24000
const length = rate * 0.25
const buffer = new Int16Array(length)
for (let i = 0; i < length; i++) {
buffer[i] = Math.sin((i / rate) * Math.PI * 2 * 440) * 0.3 * 32767
}
audio.playPCMChunk(buffer, rate)
pushLog('queued 250ms 440Hz tone')
}

const playSequence = async (): Promise<void> => {
// 4 chunks in rapid succession to demonstrate seamless concatenation.
for (let i = 0; i < 4; i++) {
playTone()
await new Promise((r) => setTimeout(r, 30))
}
}

const summary = computed(() => ({
isCapturing: audio.isCapturing.value,
isMuted: audio.isMuted.value,
level: audio.audioLevel.value,
hasContext: audio.audioContext.value !== null,
}))
</script>

<template>
<div class="space-y-4 rounded-lg border border-border bg-card p-4 text-card-foreground w-[520px] max-w-full">
<h3 class="text-base font-semibold">useStreamingAudio demo</h3>

<div class="flex flex-wrap gap-2">
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="audio.initialize()">
Initialize
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="onStart">
Start capture
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="audio.toggleMute()">
{{ audio.isMuted.value ? 'Unmute' : 'Mute' }}
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="playTone">
Play tone
</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="playSequence">
Play 4-chunk sequence
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="audio.interruptPlayback()">
Interrupt
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="audio.cleanup()">
Cleanup
</button>
</div>

<div class="h-3 w-full overflow-hidden rounded-full bg-muted">
<div
class="h-full bg-primary transition-[width] duration-100"
:style="{ width: audio.audioLevel.value + '%' }"
/>
</div>

<pre class="rounded-md bg-muted p-3 font-mono text-xs">{{ summary }}</pre>

<div>
<p class="mb-1 text-xs font-semibold text-muted-foreground">log</p>
<ul class="max-h-32 space-y-0.5 overflow-y-auto rounded-md bg-background p-2 font-mono text-xs">
<li v-for="(line, i) in log" :key="i">{{ line }}</li>
<li v-if="!log.length" class="text-muted-foreground italic">no events yet</li>
</ul>
</div>
</div>
</template>

useToast example​

<script lang="ts" setup>
import { ref } from 'vue'
import { useToast } from '@gxp-dev/app-ui'
import { Toaster } from '@gxp-dev/app-ui'

const toast = useToast()
const draft = ref('Hello from useToast')

const fakePromise = (success = true): Promise<string> =>
new Promise((resolve, reject) =>
setTimeout(() => (success ? resolve('done') : reject(new Error('failed'))), 1200),
)
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[480px] max-w-full">
<h3 class="text-base font-semibold">useToast demo</h3>

<input v-model="draft" class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />

<div class="grid grid-cols-3 gap-2">
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="toast.success(draft)">success</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="toast.error(draft)">error</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="toast.warning(draft)">warning</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="toast.info(draft)">info</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="toast.show(draft)">show</button>
<button class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground" @click="toast.loading(draft)">loading</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="toast.promise(fakePromise(true), { loading: 'Working…', success: 'OK!', error: 'Nope' })">
promise (ok)
</button>
<button class="rounded-md bg-secondary px-3 py-1.5 text-sm font-medium text-secondary-foreground" @click="toast.promise(fakePromise(false), { loading: 'Working…', success: 'OK!', error: (e: unknown) => String(e) })">
promise (fail)
</button>
<button class="rounded-md bg-muted px-3 py-1.5 text-sm font-medium" @click="toast.dismiss()">dismiss all</button>
</div>

<Toaster />
</div>
</template>

useWebSocket example​

<script lang="ts" setup>
import { ref, onBeforeUnmount } from 'vue'
import { useWebSocket } from '@gxp-dev/app-ui'

const ws = useWebSocket()
const url = ref('wss://echo.websocket.events')
const draft = ref('hello')
const log = ref<string[]>([])

const pushLog = (msg: string): void => {
log.value.unshift(`${new Date().toLocaleTimeString()} · ${msg}`)
if (log.value.length > 12) log.value.pop()
}

ws.on('echo', (data) => pushLog(`echo: ${JSON.stringify(data)}`))

const connect = async (): Promise<void> => {
pushLog(`connecting to ${url.value}`)
try {
await ws.connect(url.value)
pushLog('connected')
} catch (err) {
pushLog(`connect failed: ${(err as Error).message}`)
}
}

const send = (): void => {
ws.send('echo', { content: draft.value })
pushLog(`sent echo: ${draft.value}`)
}

onBeforeUnmount(() => ws.disconnect())
</script>

<template>
<div class="space-y-3 rounded-lg border border-border bg-card p-4 text-card-foreground w-[520px] max-w-full">
<h3 class="text-base font-semibold">useWebSocket demo</h3>

<div class="flex gap-2">
<input v-model="url" class="flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm" />
<button class="rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground" @click="connect">connect</button>
<button class="rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground" @click="ws.disconnect()">disconnect</button>
</div>

<div class="flex gap-2">
<input v-model="draft" class="flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm" />
<button class="rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground" :disabled="ws.status.value !== 'connected'" @click="send">
send('echo', …)
</button>
</div>

<pre class="rounded-md bg-muted p-3 font-mono text-xs">{{ { status: ws.status.value, reconnectCount: ws.reconnectCount.value, lastError: ws.lastError.value, isConnected: ws.isConnected() } }}</pre>

<ul class="max-h-40 space-y-0.5 overflow-y-auto rounded-md bg-background p-2 font-mono text-xs">
<li v-for="(line, i) in log" :key="i">{{ line }}</li>
<li v-if="!log.length" class="italic text-muted-foreground">no events</li>
</ul>
</div>
</template>

uuid example​

import {
cn, delay, uuid, timeAgo, throttle, buttonVariants, badgeVariants, navigationMenuTriggerStyle, parseAIResponse, preloadAssets, loadFonts,
processUploadedImage, convertToCanvasBlob, buildElementRules, buildElementSchema,
flattenElements, flattenSectionElements, initialValuesFor,
type FormSectionDef,
} from '@gxp-dev/app-ui'

export const sections: FormSectionDef[] = [{
id: 'profile', title: 'Profile',
elements: [{ type: 'email', name: 'email', label: 'Email', required: true }],
}]

export function prepareForm() {
const elements = flattenElements(sections)
const profileFields = flattenSectionElements(sections[0])
const initialValues = initialValuesFor(sections)
const schema = buildElementSchema(elements[0])
const rules = buildElementRules(elements[0])
return { profileFields, initialValues, schema, rules }
}

export function describeSession(createdAt: string, active: boolean) {
return { id: uuid(), age: timeAgo(createdAt), class: cn('rounded-md p-4', active && 'bg-primary') }
}
export const parseGeneratedData = (text: string) => parseAIResponse(text)
export const waitBeforeRetry = () => delay(250)
export const throttleLayout = (update: () => void) => throttle(update, 100)
// Call the returned function's cancel() during component teardown.
export const warmAssets = (urls: Record<string, unknown>) => Promise.all(preloadAssets(urls))
export const installBrandFont = (fontUrl: string) => loadFonts(
{ heading_1_font_family: 'custom' }, { heading_1_font_family_custom: fontUrl },
)
// These functions require browser image/canvas support. Processing preserves the
// original upload on conversion failure; explicit conversion rejects failures.
export const preparePhoto = (file: File) => processUploadedImage(file)
export const exportPhotoPng = (file: File) => convertToCanvasBlob(file, 'image/png', 1)

export const styleChoices = () => ({
button: buttonVariants({ variant: 'outline', size: 'sm' }),
badge: badgeVariants({ variant: 'secondary' }),
navigation: navigationMenuTriggerStyle(),
})

withExperienceDefaults example​

import { defineComponent, h } from 'vue'
import {
useExperience, useExperienceApi, withExperienceDefaults, readExperienceDefaults,
type CallApi,
} from '@gxp-dev/app-ui'

export function createDemoFlow() {
const Choice = defineComponent({
emits: ['next'],
setup(_props, { emit }) {
return () => h('button', { type: 'button', onClick: () => emit('next', 'portrait') }, 'Choose portrait')
},
})
const ChoicePage = withExperienceDefaults(Choice, { resultKey: 'selection' })
const defaults = readExperienceDefaults(ChoicePage)
const flow = useExperience({ pages: [{ name: 'choose', component: ChoicePage }] })
return { flow, defaults }
}

export function createApiBridge(callApi: CallApi) {
// In a DevTools app, bridge the store's operation ID, declared dependency
// identifier, and payload. Map used action endpoints to actual manifest IDs.
return useExperienceApi({ callApi })
}

On this page