The avatar editor
The slot strip, the item grid, locked items, the draft and its one save, and another fan's avatar.
Letting a fan dress their avatar. Four pieces: the avatar itself, a strip of slots, a grid of items, and a save bar.
The shape
import { Avatar } from '@xborglabs/fanbase-react'
export function AvatarEditor() {
return (
<Avatar.Provider>
<AvatarStage />
<SlotStrip />
<ItemGrid />
<SaveBar />
</Avatar.Provider>
)
}One provider around all four. The provider holds the draft, so an item picked in the grid shows on the avatar at once. Two providers would be two separate drafts that know nothing about each other.
AvatarStage is the render from the previous page.
The slot strip
state.editableSlots is the slots worth showing as a strip: everything the fan has changed from its default, and everything they are allowed to change.
state.slotOptions is every slot except the body, for a picker that filters the grid. Add your own "All" option in front:
import { AVATAR_ALL_SLOTS, resolveMessage, useAvatar } from '@xborglabs/fanbase-react'
function SlotPicker({ value, onChange }: { value: string; onChange: (slotId: string) => void }) {
const { state } = useAvatar()
return (
<select value={value} onChange={(e) => onChange(e.target.value)}>
<option value={AVATAR_ALL_SLOTS}>{resolveMessage('Profile.allTypes')}</option>
{state.slotOptions.map((slot) => (
<option key={slot.slotId} value={slot.slotId}>{slot.name}</option>
))}
</select>
)
}Which slot is selected is your state. Pass it to the grid to filter, and to the 3D scene so the camera moves in on it.
The item grid
useAvatarItems returns one page of items, filtered on the platform.
import { resolveMessage, useAvatarItems } from '@xborglabs/fanbase-react'
function ItemGrid({ slotId, onlyOwned, page }: { slotId: string; onlyOwned: boolean; page: number }) {
const { items, pageMeta, reason } = useAvatarItems({ slotId, onlyOwned, page })
if (reason === 'EMPTY') return <EmptyInventory />
return (
<>
<ul>
{items.map((item) => (
<li key={item.itemId} data-locked={item.isLocked} data-equipped={item.isEquipped}>
<img src={item.metadata.medias.select?.displayUrl} alt={item.name} />
</li>
))}
</ul>
<Pager page={pageMeta.page} totalPages={pageMeta.totalPages} />
</>
)
}| Input | Does |
|---|---|
slotId | Only items for that slot. AVATAR_ALL_SLOTS for no filter. |
onlyOwned | Only items the fan holds |
rarity | Only that rarity |
page | Which page, from 1. Sixteen items a page. |
Each item comes back with three things worked out:
| Field | Means |
|---|---|
isLocked | The fan cannot wear it yet |
isEquipped | It is on the avatar in the current draft, saved or not |
isDefaultItem | It is the slot's default |
Reset page to 1 whenever the slot or the owned toggle changes.
The grid works for a signed-out fan, with everything locked. The owned toggle means nothing without a session, so hide it for guests. Its labels are Inventory.allItems and Inventory.myItems, each taking your noun as {items}.
An empty grid
When reason is EMPTY, there are three strings: Inventory.emptyTitle, Inventory.emptyDescription and Inventory.goToQuests, the last as a link to your quests. They take your own nouns:
resolveMessage('Inventory.emptyDescription', undefined, { quests: 'quests', item: 'wearable' })One item
Tapping an item opens its detail. useAvatarItem({ itemId }) reads it.
Show the rarity with Inventory.rarity. and the item's rarity, how many the fan holds from balance.total, and the description through Parser, because it is rich text.
How to unlock it
For a locked item, tell the fan where to get it.
import { getAvatarUnlockSources } from '@xborglabs/fanbase-react'
const sources = getAvatarUnlockSources(item)| Field | Holds | Link to |
|---|---|---|
sources.quests | Quests that reward it, each with a questId | Your quest page |
sources.events | Events that reward it, each with an eventId | Your event page |
sources.vaulted | true when nothing hands it out right now | Nowhere. Say so, with Inventory.noQuestAvailableTitle. |
Equip
<Avatar.Equip item={item} asChild>
<button type="button" />
</Avatar.Equip>One button that does both. It reads "Equip" when the item is off and "Unequip" when it is on, and it disables itself when the item cannot be worn. Leave the button empty and the label is filled in for you.
Nothing is saved yet. The avatar changes, and the save bar counts one more change.
When an item cannot be equipped
actions.equip(item) from useAvatar() does the same thing in code and returns why it refused, or null when it worked.
| Reason | Means | Do |
|---|---|---|
ITEM_LOCKED | The fan does not hold it | Show how to unlock it |
ITEM_ALREADY_ALLOCATED | Another slot is wearing it | Take it off there first |
SLOT_NOT_EDITABLE | That slot is fixed | Hide equip for it |
SLOT_REQUIRED | The slot cannot be emptied and has no default | Hide unequip for it |
AUTH_REQUIRED | Signed out | A sign-in prompt |
SLOT_NOT_FOUND and SLOT_CATEGORY_MISMATCH mean the item was offered for the wrong slot. A fan cannot cause either. Log them.
The save bar
import { Avatar, resolveMessage, useAvatar } from '@xborglabs/fanbase-react'
function SaveBar() {
const { state } = useAvatar()
if (!state.isDirty) return null
return (
<div role="status">
<p>{resolveMessage('Inventory.changesSince', undefined, { count: state.changesCount })}</p>
{state.saveError ? <p role="alert">{state.saveError.message}</p> : null}
<Avatar.Save asChild><button type="button" /></Avatar.Save>
<Avatar.Reset asChild><button type="button" /></Avatar.Reset>
</div>
)
}state.changesCount is how many slots differ from what is saved. Putting a slot back to how it was takes it off the count.
Avatar.Save sends every change in one request. It is all or nothing: either the whole outfit saves or none of it does. Avatar.Reset throws the draft away and reloads what is saved.
The cooldown
After a save, the button holds for 15 seconds and counts down in its own label. That is deliberate, and it is why you leave the button's text to the SDK: put your own text in it and the countdown is gone.
To change the wait, pass saveCooldownMs to Avatar.Provider. 0 turns it off.
When a save fails
The error is on state.saveError, and the draft is kept. The fan's choices stay on screen so they can fix the one thing and try again. When the refusal maps to one of the reasons in the table above, it is on state.saveErrorReason.
actions.save() never throws. It resolves with { saved, reason, error }.
Leaving with unsaved changes
Guard your own navigation on state.isDirty. The copy is ready: Inventory.unsavedChangesTitle and Inventory.unsavedChangesAlert, with Inventory.continueEdit and Inventory.noSave for the two buttons. The first two take your noun as {avatar}.
Equipping in one tap
Outside the editor there is no draft. An item card on a home page or a "new this week" strip wants one tap that saves at once. useAllocateAvatarSlots is that.
import { resolveAvatarItemAction, resolveMessage, useAllocateAvatarSlots, useAvatarItems } from '@xborglabs/fanbase-react'
function TopItems() {
const { items } = useAvatarItems({ limit: 4 })
const { toggle, isPending } = useAllocateAvatarSlots()
return items.map((item) => (
<button
key={item.itemId}
type="button"
disabled={isPending}
onClick={() => void toggle(item).catch(() => openItemDetail(item))}
>
{resolveMessage(`Inventory.${resolveAvatarItemAction(item)}`)}
</button>
))
}resolveAvatarItemAction(item) returns unlock, equip or unequip, which is also the string key. toggle equips or unequips and saves. On a locked item it rejects without sending anything, which is your cue to open the item's detail.
Confirm with Inventory.equipSuccess or Inventory.unequipSuccess, each taking the item's name as {item}.
Another fan's avatar
usePublicAvatar({ handle }) reads someone else's avatar, signed in or not.
const { layers, aspectRatio, equippedItems } = usePublicAvatar({ handle })handle is the fan's full handle, including the # and digits after it. It is row.user.handle on a leaderboard row.
It is always the 2D stack, rendered exactly like your own. And it is read-only: no equip, no save bar.
Components and hooks
| Name | Use |
|---|---|
Avatar.Provider | Holds the draft |
Avatar.Equip | Equip or unequip an item in the draft |
Avatar.Unequip | Clear a slot back to its default, by slotId |
Avatar.Save | Save every change at once |
Avatar.Reset | Discard the draft |
useAvatarItems | One page of the item grid |
useAvatarItem | One item |
useAllocateAvatarSlots | Equip in one tap, outside the editor |
usePublicAvatar | Another fan's avatar |
The four buttons take asChild and render your element. Full props in Components.
Checklist
- One provider wraps the avatar, the grid and the save bar
- Equipping in the grid changes the avatar before anything is saved
- Taking an item off shows the slot's default, not an empty space
- A locked item cannot be equipped, and says how to get it
- Save sends one request, and a failed save keeps the fan's choices
- The save button shows its countdown
- Leaving with unsaved changes asks first
- Another fan's avatar has no editing controls