{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"profile-settings","type":"registry:block","title":"Profile settings","description":"A profile form with a photo cropped as it's picked, beside a card that shows how the profile looks to others as you type.","dependencies":["lucide-react"],"registryDependencies":["https://dashral.com/r/utils.json","https://dashral.com/r/lib-motion.json","https://dashral.com/r/avatar-upload.json","https://dashral.com/r/button.json","https://dashral.com/r/input.json","https://dashral.com/r/textarea.json"],"files":[{"path":"registry/dashral/blocks/profile-settings.tsx","type":"registry:file","target":"components/dashral/blocks/profile-settings.tsx","content":"\"use client\"\n\nimport { useEffect, useState } from \"react\"\nimport { Check, Globe, MapPin, TriangleAlert } from \"lucide-react\"\nimport { AvatarUpload } from \"../avatar-upload\"\nimport { Button } from \"../button\"\nimport { Input } from \"../input\"\nimport { Textarea } from \"../textarea\"\nimport { enterMotion, stagger } from \"../lib/motion\"\nimport { cn } from \"../lib/utils\"\n\n/** A profile: the photo is a URL you have, the File just cropped, or null for none. */\nexport type Profile = {\n  photo: File | string | null\n  name: string\n  username: string\n  bio: string\n  website: string\n  location: string\n}\n\nconst sampleProfile: Profile = {\n  photo: \"https://randomuser.me/api/portraits/women/44.jpg\",\n  name: \"Olivia Martin\",\n  username: \"olivia\",\n  bio: \"Product designer at Acme. I draw dashboards people enjoy opening on a Monday.\",\n  website: \"https://olivia.design\",\n  location: \"Jakarta, Indonesia\",\n}\n\n/** \"olivia.design/work\" from \"https://www.olivia.design/work/\", for showing; the link keeps the address as given. */\nconst shortUrl = (url: string) =>\n  url\n    .trim()\n    .replace(/^https?:\\/\\//i, \"\")\n    .replace(/^www\\./i, \"\")\n    .replace(/\\/$/, \"\")\n\n/** A link people can open: \"olivia.design\" gets https:// in front. */\nconst fullUrl = (url: string) => (/^https?:\\/\\//i.test(url.trim()) ? url.trim() : `https://${url.trim()}`)\n\nconst validUrl = (url: string) => {\n  if (!url.trim()) return true\n  try {\n    const { hostname } = new URL(fullUrl(url))\n    return hostname.includes(\".\") && !hostname.endsWith(\".\")\n  } catch {\n    return false\n  }\n}\n\n/**\n * Pictures that cross-fade: a new one fades in over the old, which stays until it has; a removed one fades out over\n * what's under it. So a change never blinks empty.\n */\nfunction Crossfade({ src, className }: { src: string | null; className?: string }) {\n  const [layers, setLayers] = useState<{ src: string; leaving: boolean }[]>(src ? [{ src, leaving: false }] : [])\n  const [shown, setShown] = useState(src)\n  if (shown !== src) {\n    setShown(src)\n    setLayers((all) => [...all.filter((layer) => layer.src !== src).map((layer) => ({ ...layer, leaving: true })), ...(src ? [{ src, leaving: false }] : [])])\n  }\n  const top = layers.at(-1)\n  return layers.map((layer) => (\n    <Layer\n      key={layer.src}\n      src={layer.src}\n      leaving={layer.leaving && layer === top}\n      className={className}\n      // Faded out: gone. Faded in (or failed to load): the pictures under it can go.\n      onDone={() => setLayers((all) => all.filter((item) => (layer.leaving ? item !== layer : !item.leaving)))}\n    />\n  ))\n}\n\nfunction Layer({ src, leaving, className, onDone }: { src: string; leaving: boolean; className?: string; onDone: () => void }) {\n  const [loaded, setLoaded] = useState(false)\n  return (\n    <img\n      src={src}\n      alt=\"\"\n      draggable={false}\n      onLoad={() => setLoaded(true)}\n      onError={onDone}\n      onAnimationEnd={onDone}\n      className={cn(\n        \"absolute inset-0 size-full object-cover\",\n        !loaded && \"opacity-0\",\n        loaded && !leaving && \"animate-in fade-in-0 duration-(--duration-standard) ease-enter\",\n        leaving && \"animate-out fade-out-0 fill-mode-forwards duration-(--duration-standard) ease-exit\",\n        className\n      )}\n    />\n  )\n}\n\n/** Whether two values hold the same fields (a File by identity), so a new object with the same content isn't a change. */\nconst sameFields = <T extends object>(a: T, b: T) => (Object.keys(a) as (keyof T)[]).every((key) => a[key] === b[key]) && Object.keys(a).length === Object.keys(b).length\n\n/** A File's object URL while it's shown, or the URL itself. */\nfunction usePhotoUrl(photo: File | string | null) {\n  const [fileUrl, setFileUrl] = useState<string | null>(null)\n  const isFile = typeof File !== \"undefined\" && photo instanceof File\n  useEffect(() => {\n    if (!isFile) return setFileUrl(null)\n    const next = URL.createObjectURL(photo)\n    setFileUrl(next)\n    return () => URL.revokeObjectURL(next)\n  }, [photo, isFile])\n  return isFile ? fileUrl : (photo as string | null) || null\n}\n\n/**\n * How the profile looks to others: the photo, name and handle, the bio, the website and the place. ProfileSettings\n * shows it beside the form, changing as you type; use it on its own for a profile page or a hover card.\n */\nexport function ProfileCard({ profile, handlePrefix = \"@\", className }: { profile: Profile; handlePrefix?: string; className?: string }) {\n  const photo = usePhotoUrl(profile.photo)\n  const name = profile.name.trim() || \"Your name\"\n  return (\n    <div className={cn(\"overflow-hidden rounded-xl border bg-card\", className)}>\n      {/* A quiet band behind the photo, in the theme's own colours. */}\n      <div aria-hidden className=\"h-16 bg-gradient-to-br from-primary/15 via-primary/5 to-transparent\" />\n      <div className=\"-mt-8 px-5 pb-5\">\n        {/* The initials under the photo, so a new photo cross-fades over the old and a removed one leaves them. */}\n        <span aria-hidden className=\"relative grid size-16 place-items-center overflow-hidden rounded-full bg-muted text-lg font-medium text-muted-foreground ring-4 ring-card\">\n          {initials(name)}\n          <Crossfade src={photo} />\n        </span>\n        <p className=\"mt-3 truncate font-semibold\">{name}</p>\n        {profile.username.trim() && (\n          <p className=\"truncate text-sm text-muted-foreground\">\n            {handlePrefix}\n            {profile.username.trim()}\n          </p>\n        )}\n        {profile.bio.trim() && <p className=\"mt-3 text-sm break-words whitespace-pre-line\">{profile.bio.trim()}</p>}\n        {(profile.website.trim() || profile.location.trim()) && (\n          <ul className=\"mt-4 grid gap-1.5 text-sm text-muted-foreground\">\n            {profile.location.trim() && (\n              <li className=\"flex min-w-0 items-center gap-2\">\n                <MapPin aria-hidden className=\"size-4 shrink-0\" />\n                <span className=\"truncate\">{profile.location.trim()}</span>\n              </li>\n            )}\n            {profile.website.trim() && (\n              <li className=\"flex min-w-0 items-center gap-2\">\n                <Globe aria-hidden className=\"size-4 shrink-0\" />\n                {validUrl(profile.website) ? (\n                  <a href={fullUrl(profile.website)} target=\"_blank\" rel=\"noopener noreferrer\" className=\"truncate text-foreground underline-offset-4 hover:underline\">\n                    {shortUrl(profile.website)}\n                  </a>\n                ) : (\n                  <span className=\"truncate\">{shortUrl(profile.website)}</span>\n                )}\n              </li>\n            )}\n          </ul>\n        )}\n      </div>\n    </div>\n  )\n}\n\n/**\n * A profile settings page: the photo (picked or dropped, cropped to a square), name, username, bio, website and place,\n * beside a card showing how the profile looks to others as you type. Save sends everything to onSave: the photo is a\n * File when it's new, null when it was removed, and the URL you gave when it's unchanged. A handler that throws keeps\n * the changes and says why.\n */\nexport function ProfileSettings({\n  defaultValue = sampleProfile,\n  onSave,\n  title = \"Profile\",\n  description = \"How you appear to your team and on your public page.\",\n  handlePrefix = \"@\",\n  usernamePrefix = \"acme.com/\",\n  bioLimit = 160,\n}: {\n  /** The profile as it's saved now. */\n  defaultValue?: Profile\n  /** Saves the profile; throw an Error to keep the changes and show its message. */\n  onSave?: (profile: Profile) => Promise<void> | void\n  title?: string\n  description?: string\n  /** Before the username on the card: \"@\" by default. */\n  handlePrefix?: string\n  /** Inside the username field, before it: the address of the public page. \"\" for none. */\n  usernamePrefix?: string\n  /** Longest bio, in characters. */\n  bioLimit?: number\n}) {\n  const [saved, setSaved] = useState(defaultValue)\n  const [profile, setProfile] = useState(defaultValue)\n  const [touched, setTouched] = useState<Partial<Record<keyof Profile, boolean>>>({})\n  const [saving, setSaving] = useState(false)\n  const [done, setDone] = useState(false)\n  const [problem, setProblem] = useState<string | null>(null)\n\n  // A new defaultValue (say, loaded from your server) starts the form again from it.\n  // Compared by content, so an object written inline (new on every render) doesn't wipe what's being edited.\n  const [given, setGiven] = useState(defaultValue)\n  if (!sameFields(given, defaultValue)) {\n    setGiven(defaultValue)\n    setSaved(defaultValue)\n    setProfile(defaultValue)\n    setTouched({})\n  }\n\n  // \"Saved\" shows on the button for a moment.\n  useEffect(() => {\n    if (!done) return\n    const timer = setTimeout(() => setDone(false), 2000)\n    return () => clearTimeout(timer)\n  }, [done])\n\n  const errors: Partial<Record<keyof Profile, string>> = {}\n  if (!profile.name.trim()) errors.name = \"Write your name.\"\n  const username = profile.username.trim()\n  if (!username) errors.username = \"Pick a username.\"\n  else if (!/^[a-z0-9_-]{3,30}$/.test(username)) errors.username = \"3 to 30 lowercase letters, numbers, - or _.\"\n  if (profile.bio.length > bioLimit) errors.bio = `Up to ${bioLimit} characters.`\n  if (!validUrl(profile.website)) errors.website = \"That doesn't look like a web address.\"\n  const invalid = Object.keys(errors).length > 0\n\n  const dirty = !sameFields(profile, saved)\n\n  function change<K extends keyof Profile>(key: K, value: Profile[K]) {\n    setProfile((current) => ({ ...current, [key]: value }))\n    setDone(false)\n  }\n  const blur = (key: keyof Profile) => () => setTouched((current) => ({ ...current, [key]: true }))\n  // An error shows once you've left the field, or tried to save.\n  const shown = (key: keyof Profile) => (touched[key] ? errors[key] : undefined)\n\n  async function save(event: React.FormEvent<HTMLFormElement>) {\n    event.preventDefault()\n    if (saving) return\n    setTouched({ name: true, username: true, bio: true, website: true, location: true })\n    if (invalid || !dirty) return\n    setSaving(true)\n    setProblem(null)\n    const next = { ...profile, name: profile.name.trim(), username, bio: profile.bio.trim(), website: profile.website.trim(), location: profile.location.trim() }\n    try {\n      await onSave?.(next)\n      setSaved(next)\n      setProfile(next)\n      setDone(true)\n    } catch (error) {\n      setProblem(error instanceof Error ? error.message : \"Your profile didn't save. Try again.\")\n    } finally {\n      setSaving(false)\n    }\n  }\n\n  function discard() {\n    setProfile(saved)\n    setTouched({})\n    setProblem(null)\n  }\n\n  return (\n    <div className=\"min-h-full bg-background p-4 sm:p-6\">\n      <div className=\"mx-auto max-w-4xl space-y-4\">\n        <div>\n          <h2 className=\"text-lg font-semibold tracking-[-0.01em]\">{title}</h2>\n          <p className=\"text-sm text-muted-foreground\">{description}</p>\n          {problem && (\n            <p role=\"alert\" className=\"mt-3 flex items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2 text-sm text-destructive-text\">\n              <TriangleAlert aria-hidden className=\"size-4 shrink-0\" /> {problem}\n            </p>\n          )}\n        </div>\n\n        <div className=\"grid items-start gap-4 md:grid-cols-[minmax(0,1fr)_18rem]\">\n          <form onSubmit={save} noValidate className={cn(enterMotion, \"rounded-xl border bg-card\")} style={stagger(0, 60)}>\n            {/* Held still while it saves, so nothing typed meanwhile is overwritten when it's done. */}\n            <fieldset disabled={saving} className=\"grid min-w-0 gap-5 p-5\">\n              <AvatarUpload\n                label=\"Photo\"\n                value={profile.photo}\n                onValueChange={(file) => change(\"photo\", file)}\n                fallback={initials(profile.name)}\n                maxSize={10 * 1024 * 1024}\n                description=\"JPG, PNG or WebP, up to 10 MB. You crop it to a square.\"\n              />\n              <div className=\"grid gap-4 sm:grid-cols-2\">\n                <Input\n                  label=\"Name\"\n                  value={profile.name}\n                  onChange={(event) => change(\"name\", event.target.value)}\n                  onBlur={blur(\"name\")}\n                  error={shown(\"name\")}\n                  autoComplete=\"name\"\n                  maxLength={80}\n                  required\n                />\n                <Input\n                  label=\"Username\"\n                  value={profile.username}\n                  // Usernames are lowercase; spaces become dashes as you type.\n                  onChange={(event) => change(\"username\", event.target.value.toLowerCase().replace(/\\s+/g, \"-\"))}\n                  onBlur={blur(\"username\")}\n                  error={shown(\"username\")}\n                  prefix={usernamePrefix || undefined}\n                  autoComplete=\"username\"\n                  autoCapitalize=\"none\"\n                  spellCheck={false}\n                  maxLength={30}\n                  required\n                />\n              </div>\n              <Textarea\n                label=\"Bio\"\n                value={profile.bio}\n                onChange={(event) => change(\"bio\", event.target.value)}\n                onBlur={blur(\"bio\")}\n                error={shown(\"bio\")}\n                placeholder=\"A line or two about you\"\n                rows={3}\n                labelAction={\n                  <span className={cn(\"tabular-nums\", profile.bio.length > bioLimit && \"text-destructive-text\")}>\n                    {profile.bio.length}/{bioLimit}\n                  </span>\n                }\n              />\n              <div className=\"grid gap-4 sm:grid-cols-2\">\n                <Input\n                  label=\"Website\"\n                  type=\"url\"\n                  inputMode=\"url\"\n                  value={profile.website}\n                  onChange={(event) => change(\"website\", event.target.value)}\n                  onBlur={blur(\"website\")}\n                  error={shown(\"website\")}\n                  placeholder=\"yoursite.com\"\n                  autoComplete=\"url\"\n                  autoCapitalize=\"none\"\n                  spellCheck={false}\n                />\n                <Input\n                  label=\"Location\"\n                  value={profile.location}\n                  onChange={(event) => change(\"location\", event.target.value)}\n                  placeholder=\"City, country\"\n                  autoComplete=\"address-level2\"\n                  maxLength={60}\n                />\n              </div>\n            </fieldset>\n            <div className=\"flex flex-wrap items-center justify-end gap-2 border-t px-5 py-3\">\n              {dirty && !saving && (\n                <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={discard}>\n                  Discard\n                </Button>\n              )}\n              <Button type=\"submit\" size=\"sm\" loading={saving} disabled={!dirty && !done}>\n                {done ? (\n                  <>\n                    <Check aria-hidden /> Saved\n                  </>\n                ) : (\n                  \"Save profile\"\n                )}\n              </Button>\n            </div>\n          </form>\n\n          <aside aria-label=\"Preview\" className={cn(enterMotion, \"space-y-2 md:sticky md:top-6\")} style={stagger(1, 60)}>\n            <p className=\"text-xs font-medium text-muted-foreground\">How others see you</p>\n            <ProfileCard profile={profile} handlePrefix={handlePrefix} />\n          </aside>\n        </div>\n      </div>\n    </div>\n  )\n}\n\n/** \"Olivia Martin\" → \"OM\". */\nconst initials = (name: string) =>\n  name\n    .trim()\n    .split(/\\s+/)\n    .slice(0, 2)\n    .map((part) => part[0]?.toUpperCase() ?? \"\")\n    .join(\"\")\n"}],"cssVars":{"theme":{"color-destructive-foreground":"var(--destructive-foreground)","color-destructive-text":"var(--destructive-text)","ease-standard":"var(--ease-standard)","ease-enter":"var(--ease-enter)","ease-exit":"var(--ease-exit)","ease-spring":"var(--ease-spring)"},"light":{"destructive-foreground":"oklch(0.985 0 0)","destructive-text":"#bd2800","duration-fast":"160ms","duration-standard":"240ms","duration-considered":"480ms","ease-standard":"cubic-bezier(0.2, 0, 0, 1)","ease-enter":"cubic-bezier(0, 0, 0, 1)","ease-exit":"cubic-bezier(0.3, 0, 1, 1)","ease-spring":"linear(0, 0.071 4%, 0.234 8%, 0.433 12%, 0.626 17%, 0.791 21%, 0.917 25%, 1.004 29%, 1.055 33%, 1.079 38%, 1.083 42%, 1.075 46%, 1.06 50%, 1.043 54%, 1.027 58%, 1.015 62%, 1.005 67%, 0.998 71%, 0.995 75%, 0.993 79%, 0.993 83%, 0.994 88%, 0.995 92%, 0.997 96%, 1)"},"dark":{"destructive-foreground":"oklch(0.2 0 0)","destructive-text":"#ff8a5c"}}}