src/examples/profile/Headless.tsx'use client'
import { Avatar, type ProfileUpdate, useLinkedAccounts, useUser } from '@synqauth/react'
import { type FormEvent, useState } from 'react'
// The profile headless: useUser reads it, and update() sends only the
// fields given (null clears one). Every call answers { data, error }, so the
// form says it saved, or shows the API's own reason when it refuses.
//
// Their picture is theirs to choose: uploadPicture() sends a file through
// the app's route mount to Synq's storage, setPictureFrom() uses a linked
// account's, and removePicture() leaves none. <Avatar> shows it, or, with
// none, the app's own default: here a color of the app's own, picked from
// their avatar_seed, the same in every app of the brand.
const COLORS = ['#f97316', '#14b8a6', '#8b5cf6', '#ec4899', '#22c55e', '#3b82f6']
const swatch = (seed: string) => COLORS[seed.charCodeAt(0) % COLORS.length]
export function ProfileHeadless() {
const { profile, update, uploadPicture, setPictureFrom, removePicture } = useUser()
const { data: accounts } = useLinkedAccounts()
const [outcome, setOutcome] = useState<{ ok: boolean; text: string } | null>(null)
if (!profile) return <p>Loading…</p>
const said = (error: { message: string } | null) =>
setOutcome(error ? { ok: false, text: error.message } : { ok: true, text: 'Saved' })
async function save(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const form = new FormData(event.currentTarget)
const field = (name: string) => {
const value = form.get(name)
return typeof value === 'string' && value.trim() ? value.trim() : null
}
const changes: ProfileUpdate = { name: field('name'), username: field('username') }
said((await update(changes)).error)
}
return (
<form onSubmit={(event) => void save(event)}>
<Avatar
size={64}
fallback={(seed) => (
<svg viewBox="0 0 1 1" width={64} height={64}>
<rect width="1" height="1" fill={swatch(seed)} />
</svg>
)}
/>
{/* Only where Synq keeps pictures: elsewhere these answer storage_unavailable. */}
{profile.picture_choices && (
<label>
Picture{' '}
<input
type="file"
accept="image/png,image/jpeg,image/webp,image/gif"
onChange={(event) => {
const file = event.target.files?.[0]
if (file) void uploadPicture(file).then(({ error }) => said(error))
}}
/>
</label>
)}
{accounts
?.filter((account) => profile.picture_choices && account.has_picture)
.map((account) => (
<button
key={account.id}
type="button"
onClick={() => void setPictureFrom(account.id).then(({ error }) => said(error))}
>
Use my {account.provider} picture
</button>
))}
{profile.picture && (
<button type="button" onClick={() => void removePicture().then(({ error }) => said(error))}>
Remove picture
</button>
)}
<label>
Name <input name="name" defaultValue={profile.name ?? ''} />
</label>
<label>
Username <input name="username" defaultValue={profile.username ?? ''} />
</label>
<button type="submit">Save profile</button>
<p role={outcome?.ok === false ? 'alert' : 'status'}>{outcome?.text}</p>
</form>
)
}