* Add drafts functionality to composer - Add local storage layer for drafts (filesystem on native, IndexedDB on web) - Add "Drafts" button to composer top bar showing badge with draft count - Modify discard prompt to offer "Save Draft" option - Add `restore_from_draft` action to composer reducer - Support saving/restoring: text, facets, images, labels, threadgate, quote/link embeds - Add placeholder hooks for future server API integration - Add unit tests for draft serialization Note: Video/GIF restoration marked as TODO for future implementation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix drafts button: always visible, adjacent to post button - Make drafts button always visible (not just when drafts exist) - Move button to be adjacent to the publish button - If composer is empty: opens drafts list directly - If composer has content: shows prompt to save/discard before viewing drafts - Add badge showing draft count when drafts exist Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update drafts button: text-only, ghost/primary style - Show "Drafts" or "Drafts (N)" as text, no icon - Use ghost variant with primary color - Match Cancel button styling Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove draft count from button, just show "Drafts" Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Increase drafts button horizontal padding and gap Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Use InnerFlatList and Dialog.Header for drafts dialog - Switch from ScrollableInner to InnerFlatList - Add Dialog.Header with back button in left slot - Use sticky header Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Track draft ID in composer state machine Adds draftId to ComposerState so that editing an existing draft and saving it again updates the draft rather than creating a new one. - Add draftId?: string to ComposerState type - Set draftId when restoring from draft via restore_from_draft action - Pass existingDraftId to save functions from composerState.draftId - Add PageX icon for empty drafts state Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add clear action to discard composer content When pressing the Drafts button with content in the composer, the user can choose to discard. This now properly clears the composer by dispatching a 'clear' action that resets to an empty state. - Add 'clear' action type to ComposerAction - Implement clear case in composerReducer (resets to single empty post) - Add handleClearComposer callback in Composer.tsx - Pass onDiscard prop through ComposerTopBar to DraftsButton - Call onDiscard before opening drafts dialog on discard Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Track dirty state to skip discard prompt for unchanged drafts When a draft is loaded and the user hasn't made any changes, closing the composer should not show the discard prompt since nothing would be lost. - Add isDirty field to ComposerState - Set isDirty: true on all content-modifying actions - Set isDirty: false on restore_from_draft, clear, and initial state - Update onPressCancel to only show prompt if no draft or isDirty Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Redesign drafts list to show full thread preview - Display all posts in a draft thread, not just the first - First post uses larger avatar (42px), subsequent posts nested with smaller avatar (32px) and thread connector line - Show author avatar, display name, handle, and relative timestamp - Add overflow menu button (placeholder) on first post - Display full text instead of truncated preview - Add media preview component for images, GIFs, and videos - Card layout with rounded corners and proper spacing - Add gap separators between draft cards in list Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix draft item styling based on feedback - Add border and shadow to draft cards - Remove trash button, move delete to overflow menu prompt - Remove size differences for thread posts (same avatar/text size) - Add spacing between header and first draft item - Change prompt wording to "Discard draft" Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Use real image embed components for draft preview Replace custom image preview with AutoSizedImage for single images and ImageLayoutGrid for multiple images. This gives drafts the same polished image display as regular posts. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Improve drafts dialog platform handling - Render header outside FlatList on native, inside on web - Use web() helper for conditional web-only props - Replace ItemSeparatorComponent with mt_lg margin on items - Add minHeight on web for better dialog sizing - Simplify header structure Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Mark composer as clean after saving draft Add mark_saved action that resets isDirty to false and updates the draftId. This is dispatched after successfully saving a draft, allowing the user to close the composer without a discard prompt since their changes have been saved. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Apply dirty tracking to Drafts button prompt Only show the save/discard prompt when pressing the Drafts button if the composer has unsaved changes (isDirty). If the content is unchanged from a loaded draft or was just saved, go directly to the drafts list. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix re-saving drafts with existing media When re-saving a draft, the code was trying to copy media files that were already in drafts storage to new locations, causing copy errors. Changes: - Add extractLocalIdFromPath() to detect if a path is already in drafts - Track loadedMediaMap in ComposerState for identifying reusable media - Only delete old media that wasn't reused during re-save - Pass loadedMediaMap when saving to enable media reuse detection - Disable pointer events on draft media preview Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * add vertical option to prompt, change copy * fix import * fix import * Migrate drafts from local storage to server API Replace local-only draft storage with the new `app.bsky.draft.*` server API: - getDrafts, createDraft, updateDraft, deleteDraft endpoints Key changes: - Add api.ts with type converters (ComposerState <-> server Draft) - Update hooks.ts to use server API instead of local storage - Simplify storage.ts/storage.web.ts for local media caching only - Media stored locally via localRef pattern (filepath in server draft) - GIFs stored as external embeds with Tenor URL + dimensions - Hide drafts button when replying (reply drafts not supported) - Show "different device" note when media is missing locally Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * attempt to fix blob mangement * Migrate storage.ts from expo-file-system/legacy to expo-file-system Use the new object-based expo-file-system API (SDK 54+) with Directory and File classes instead of the legacy function-based API. The new API provides synchronous operations for file/directory existence checks, creation, copying, deletion, and listing. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add drafts-specific logger Add a Drafts context to the logger system for better log categorization and debugging of draft-related operations. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: use drafts-specific logger in hooks and storage Switch from the generic logger to the new drafts-specific logger for better log categorization. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: ensure media cache is populated before checking exists On iOS (and web), the media cache wasn't populated before the drafts query ran, causing drafts with local media to incorrectly show as "missing media" on app restart. The issue would resolve itself after closing and reopening the composer because by then the cache was ready. This fix adds ensureMediaCachePopulated() and awaits it in useDrafts before checking which media exists locally. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: complete Gif object reconstruction for draft rehydration Fix "Cannot read property 'url' of undefined" error when rehydrating drafts with GIFs. The Gif object was missing required properties like url, content_description, and media_formats.preview that are needed by useResolveGifQuery and other components. Also preserve alt text through serialization by storing it in URL query params alongside dimensions. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: load draft preview images and get dimensions Fix draft preview images not showing on web and add proper aspect ratio support: 1. Try to load all images regardless of the exists cache flag, which may be stale due to async cache population timing 2. Use Image.loadAsync() from expo-image to get image dimensions 3. Pass dimensions to viewImages for proper aspect ratio in previews Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: update save prompt copy when editing existing draft When editing an existing draft (vs creating a new one), use "Save changes" instead of "Save draft" in the save/discard prompts. This provides clearer context to the user about what action they're taking. Add isEditingDraft prop to DraftsButton and ComposerTopBar, and update both prompts (in DraftsButton and Composer) with conditional copy based on whether we're editing an existing draft. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * style: add bottom padding to drafts list Add pb_xl padding to the drafts list content container for better visual spacing at the bottom of the list. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: use typed error check for draft limit Replace manual error object inspection with the proper AppBskyDraftCreateDraft.DraftLimitReachedError type check for cleaner and more reliable error handling. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * make storage functions async to match web * log unknown errors * delete left-over file * move state to colo with composer * fix: handle invalid GIF dimensions gracefully Fix NaN aspectRatio when rehydrating GIFs from drafts by: 1. Adding validation in parseTenorGif to reject invalid dimensions (NaN, zero, or negative values) 2. Adding defensive checks in GifEmbed to fallback to 1:1 aspect ratio if dimensions are invalid 3. Adding defensive checks in composer ExternalEmbedGif to fallback to 16:9 if gif.media_formats.gif.dims is missing or invalid Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: prevent double query string in GIF draft hydration When loading a GIF from a draft, the URL was being corrupted with double query strings like: `?ww=498&hh=498?hh=498&ww=498` This happened because: 1. serializeGif() adds ?ww=X&hh=Y&alt=Z to the Tenor URL 2. parseGifFromUrl() returned the full URL including our params 3. resolveGif() in resolve.ts then appends MORE params via string concatenation, creating a second ? Fix: Strip our custom params (ww, hh, alt) from the URL in parseGifFromUrl() before returning it, so the reconstructed GIF has a clean base URL. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix draft button behaviour when publishing, tweak buttons * ensure media unavaiable message is contrasty enough * infinite query, rename file to queries * simplify threadgate/postgate handling * refactor: pass full draft data instead of re-fetching The useLoadDraft and useDeleteDraftMutation hooks were fetching drafts via getDrafts() to look up a draft by ID. This was problematic because getDrafts is paginated, so drafts not on the first page wouldn't be found. Changes: - Add full Draft object to DraftSummary type - useLoadDraft now takes Draft directly (only loads local media) - useDeleteDraftMutation now takes {draftId, draft} to avoid re-fetch - Update DraftItem and DraftsListDialog to pass full draft data Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix type errors * docs: add notes on platform files and paginated APIs - Platform-specific files (.web.ts, .native.ts) are resolved by the bundler automatically - just import normally, don't use require() - Paginated APIs should use useInfiniteQuery, not useQuery Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * More CLAUDE.md updates * Delete PLAN.md * Use minimal media mode for draft display - REVERT IF NEEDED * Enable pagination * Add comment about headers * remove extraneous comments * Prevent runaway pagination * fix detection rebase change * use border_transparent * Replace idb with idb-keyval for draft media storage Simplifies web IndexedDB storage by using idb-keyval instead of the full idb library. This reduces bundle size and aligns with the pattern used in src/storage/archive/db/index.web.ts. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix native draft media filename encoding The previous approach replaced both / and : with _, but the reverse transformation couldn't distinguish between them. This caused cache misses for paths containing both characters. Use encodeURIComponent/decodeURIComponent for a proper reversible encoding. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * convert useLoadDraft() hook to regular async function Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * update atproto api * clean up orphaned media * restore videos * save/restore captions * restore postgates * Copy updates from Darrin * Ope fix missed vertical props * get image aspect ratio when restoring * get videos working on native * get video restoration working on native * sanitize handles properly in draftitem * fix yarn.lock * Swap console logs --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: Eric Bailey <git@esb.lol>
17 KiB
CLAUDE.md - Bluesky Social App Development Guide
This document provides guidance for working effectively in the Bluesky Social app codebase.
Project Overview
Bluesky Social is a cross-platform social media application built with React Native and Expo. It runs on iOS, Android, and Web, connecting to the AT Protocol (atproto) decentralized social network.
Tech Stack:
- React Native 0.81 with Expo 54
- TypeScript
- React Navigation for routing
- TanStack Query (React Query) for data fetching
- Lingui for internationalization
- Custom design system called ALF (Application Layout Framework)
Essential Commands
# Development
yarn start # Start Expo dev server
yarn web # Start web version
yarn android # Run on Android
yarn ios # Run on iOS
# Testing & Quality
yarn test # Run Jest tests
yarn lint # Run ESLint
yarn typecheck # Run TypeScript type checking
# Internationalization
yarn intl:extract # Extract translation strings (you don't typically need to run this manually, we have CI for it)
yarn intl:compile # Compile translations for runtime
# Build
yarn build-web # Build web version
yarn prebuild # Generate native projects
Project Structure
src/
├── alf/ # Design system (ALF) - themes, atoms, tokens
├── components/ # Shared UI components (Button, Dialog, Menu, etc.)
├── screens/ # Full-page screen components (newer pattern)
├── view/
│ ├── screens/ # Full-page screens (legacy location)
│ ├── com/ # Reusable view components
│ └── shell/ # App shell (navigation bars, tabs)
├── state/
│ ├── queries/ # TanStack Query hooks
│ ├── preferences/ # User preferences (React Context)
│ ├── session/ # Authentication state
│ └── persisted/ # Persistent storage layer
├── lib/ # Utilities, constants, helpers
├── locale/ # i18n configuration and language files
└── Navigation.tsx # Main navigation configuration
Styling System (ALF)
ALF is the custom design system. It uses Tailwind-inspired naming with underscores instead of hyphens.
Basic Usage
import {atoms as a, useTheme} from '#/alf'
function MyComponent() {
const t = useTheme()
return (
<View style={[a.flex_row, a.gap_md, a.p_lg, t.atoms.bg]}>
<Text style={[a.text_md, a.font_bold, t.atoms.text]}>
Hello
</Text>
</View>
)
}
Key Concepts
Static Atoms - Theme-independent styles imported from atoms:
import {atoms as a} from '#/alf'
// a.flex_row, a.p_md, a.gap_sm, a.rounded_md, a.text_lg, etc.
Theme Atoms - Theme-dependent colors from useTheme():
const t = useTheme()
// t.atoms.bg, t.atoms.text, t.atoms.border_contrast_low, etc.
// t.palette.primary_500, t.palette.negative_400, etc.
Platform Utilities - For platform-specific styles:
import {web, native, ios, android, platform} from '#/alf'
const styles = [
a.p_md,
web({cursor: 'pointer'}),
native({paddingBottom: 20}),
platform({ios: {...}, android: {...}, web: {...}}),
]
Breakpoints - Responsive design:
import {useBreakpoints} from '#/alf'
const {gtPhone, gtMobile, gtTablet} = useBreakpoints()
if (gtMobile) {
// Tablet or desktop layout
}
Naming Conventions
- Spacing:
2xs,xs,sm,md,lg,xl,2xl(t-shirt sizes) - Text:
text_xs,text_sm,text_md,text_lg,text_xl - Gaps/Padding:
gap_sm,p_md,px_lg,py_xl - Flex:
flex_row,flex_1,align_center,justify_between - Borders:
border,border_t,rounded_md,rounded_full
Component Patterns
Dialog Component
Dialogs use a bottom sheet on native and a modal on web. Use useDialogControl() hook to manage state.
import * as Dialog from '#/components/Dialog'
function MyFeature() {
const control = Dialog.useDialogControl()
return (
<>
<Button label="Open" onPress={control.open}>
<ButtonText>Open Dialog</ButtonText>
</Button>
<Dialog.Outer control={control}>
{/* Typically the inner part is in its own component */}
<Dialog.Handle /> {/* Native-only drag handle */}
<Dialog.ScrollableInner label={_(msg`My Dialog`)}>
<Dialog.Header>
<Dialog.HeaderText>Title</Dialog.HeaderText>
</Dialog.Header>
<Text>Dialog content here</Text>
<Button label="Done" onPress={() => control.close()}>
<ButtonText>Done</ButtonText>
</Button>
<Dialog.Close /> {/* Web-only X button in top left */}
</Dialog.ScrollableInner>
</Dialog.Outer>
</>
)
}
Menu Component
Menus render as a dropdown on web and a bottom sheet dialog on native.
import * as Menu from '#/components/Menu'
function MyMenu() {
return (
<Menu.Root>
<Menu.Trigger label="Open menu">
{({props}) => (
<Button {...props} label="Menu">
<ButtonIcon icon={DotsHorizontal} />
</Button>
)}
</Menu.Trigger>
<Menu.Outer>
<Menu.Group>
<Menu.Item label="Edit" onPress={handleEdit}>
<Menu.ItemIcon icon={Pencil} />
<Menu.ItemText>Edit</Menu.ItemText>
</Menu.Item>
<Menu.Item label="Delete" onPress={handleDelete}>
<Menu.ItemIcon icon={Trash} />
<Menu.ItemText>Delete</Menu.ItemText>
</Menu.Item>
</Menu.Group>
</Menu.Outer>
</Menu.Root>
)
}
Button Component
import {Button, ButtonText, ButtonIcon} from '#/components/Button'
// Solid primary button (most common)
<Button label="Save" onPress={handleSave} color="primary" size="large">
<ButtonText>Save</ButtonText>
</Button>
// With icon
<Button label="Share" onPress={handleShare} color="secondary" size="small">
<ButtonIcon icon={Share} />
<ButtonText>Share</ButtonText>
</Button>
// Icon-only button
<Button label="Close" onPress={handleClose} color="secondary" size="small" shape="round">
<ButtonIcon icon={XIcon} />
</Button>
// Ghost variant (deprecated - use color prop)
<Button label="Cancel" variant="ghost" color="secondary" size="small">
<ButtonText>Cancel</ButtonText>
</Button>
Button Props:
color:'primary'|'secondary'|'negative'|'primary_subtle'|'negative_subtle'|'secondary_inverted'size:'tiny'|'small'|'large'shape:'default'(pill) |'round'|'square'|'rectangular'variant:'solid'|'outline'|'ghost'(deprecated, usecolor)
Typography
import {Text, H1, H2, P} from '#/components/Typography'
<H1 style={[a.text_xl, a.font_bold]}>Heading</H1>
<P>Paragraph text with default styling.</P>
<Text style={[a.text_sm, t.atoms.text_contrast_medium]}>Custom text</Text>
// For text with emoji, add the emoji prop
<Text emoji>Hello! 👋</Text>
TextField
import * as TextField from '#/components/forms/TextField'
<TextField.LabelText>Email</TextField.LabelText>
<TextField.Root>
<TextField.Icon icon={AtSign} />
<TextField.Input
label="Email address"
placeholder="you@example.com"
defaultValue={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
/>
</TextField.Root>
Internationalization (i18n)
All user-facing strings must be wrapped for translation using Lingui.
import {msg, Trans, plural} from '@lingui/macro'
import {useLingui} from '@lingui/react'
function MyComponent() {
const {_} = useLingui()
// Simple strings - use msg() with _() function
const title = _(msg`Settings`)
const errorMessage = _(msg`Something went wrong`)
// Strings with variables
const greeting = _(msg`Hello, ${name}!`)
// Pluralization
const countLabel = _(plural(count, {
one: '# item',
other: '# items',
}))
// JSX content - use Trans component
return (
<Text>
<Trans>Welcome to <Text style={a.font_bold}>Bluesky</Text></Trans>
</Text>
)
}
Commands:
yarn intl:extract # Extract new strings to locale files
yarn intl:compile # Compile for runtime (required after changes)
State Management
TanStack Query (Data Fetching)
// src/state/queries/profile.ts
import {useQuery, useMutation, useQueryClient} from '@tanstack/react-query'
// Query key pattern
const RQKEY_ROOT = 'profile'
export const RQKEY = (did: string) => [RQKEY_ROOT, did]
// Query hook
export function useProfileQuery({did}: {did: string}) {
const agent = useAgent()
return useQuery({
queryKey: RQKEY(did),
queryFn: async () => {
const res = await agent.getProfile({actor: did})
return res.data
},
staleTime: STALE.MINUTES.FIVE,
enabled: !!did,
})
}
// Mutation hook
export function useUpdateProfile() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (data) => {
// Update logic
},
onSuccess: (_, variables) => {
queryClient.invalidateQueries({queryKey: RQKEY(variables.did)})
},
onError: (error) => {
if (isNetworkError(error)) {
// don't log, but inform user
} else if (error instanceof AppBskyExampleProcedure.ExampleError) {
// XRPC APIs often have typed errors, allows nicer handling
} else {
// Log unexpected errors to Sentry
logger.error('Error updating profile', {safeMessage: error})
}
}
})
}
Stale Time Constants (from src/state/queries/index.ts):
STALE.SECONDS.FIFTEEN // 15 seconds
STALE.MINUTES.ONE // 1 minute
STALE.MINUTES.FIVE // 5 minutes
STALE.HOURS.ONE // 1 hour
STALE.INFINITY // Never stale
Paginated APIs: Many atproto APIs return paginated results with a cursor. Use useInfiniteQuery for these:
export function useDraftsQuery() {
const agent = useAgent()
return useInfiniteQuery({
queryKey: ['drafts'],
queryFn: async ({pageParam}) => {
const res = await agent.app.bsky.draft.getDrafts({cursor: pageParam})
return res.data
},
initialPageParam: undefined as string | undefined,
getNextPageParam: page => page.cursor,
})
}
To get all items from pages: data?.pages.flatMap(page => page.items) ?? []
Preferences (React Context)
// Simple boolean preference pattern
import {useAutoplayDisabled, useSetAutoplayDisabled} from '#/state/preferences'
function SettingsScreen() {
const autoplayDisabled = useAutoplayDisabled()
const setAutoplayDisabled = useSetAutoplayDisabled()
return (
<Toggle
value={autoplayDisabled}
onValueChange={setAutoplayDisabled}
/>
)
}
Session State
import {useSession, useAgent} from '#/state/session'
function MyComponent() {
const {hasSession, currentAccount} = useSession()
const agent = useAgent()
if (!hasSession) {
return <LoginPrompt />
}
// Use agent for API calls
const response = await agent.getProfile({actor: currentAccount.did})
}
Navigation
Navigation uses React Navigation with type-safe route parameters.
// Screen component
import {type NativeStackScreenProps} from '@react-navigation/native-stack'
import {type CommonNavigatorParams} from '#/lib/routes/types'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'Profile'>
export function ProfileScreen({route, navigation}: Props) {
const {name} = route.params // Type-safe params
return (
<Layout.Screen>
{/* Screen content */}
</Layout.Screen>
)
}
// Programmatic navigation
import {useNavigation} from '@react-navigation/native'
const navigation = useNavigation()
navigation.navigate('Profile', {name: 'alice.bsky.social'})
// Or use the navigate helper
import {navigate} from '#/Navigation'
navigate('Profile', {name: 'alice.bsky.social'})
Platform-Specific Code
Use file extensions for platform-specific implementations:
Component.tsx # Shared/default
Component.web.tsx # Web-only
Component.native.tsx # iOS + Android
Component.ios.tsx # iOS-only
Component.android.tsx # Android-only
Example from Dialog:
src/components/Dialog/index.tsx- Native (uses BottomSheet)src/components/Dialog/index.web.tsx- Web (uses modal with Radix primitives)
Important: The bundler automatically resolves platform-specific files. Just import normally:
// CORRECT - bundler picks storage.ts or storage.web.ts automatically
import * as storage from '#/state/drafts/storage'
// WRONG - don't use require() or conditional imports for platform files
const storage = IS_NATIVE
? require('#/state/drafts/storage')
: require('#/state/drafts/storage.web')
Platform detection (for runtime logic, not imports):
import {IS_WEB, IS_NATIVE, IS_IOS, IS_ANDROID} from '#/env'
if (IS_NATIVE) {
// Native-specific logic
}
Import Aliases
Always use the #/ alias for absolute imports:
// Good
import {useSession} from '#/state/session'
import {atoms as a, useTheme} from '#/alf'
import {Button} from '#/components/Button'
// Avoid
import {useSession} from '../../../state/session'
Footguns
Common pitfalls to avoid in this codebase:
Dialog Close Callback (Critical)
Always use control.close(() => ...) when performing actions after closing a dialog. The callback ensures the action runs after the dialog's close animation completes. Failing to do this causes race conditions with React state updates.
// WRONG - causes bugs with state updates, navigation, opening other dialogs
const onConfirm = () => {
control.close()
navigation.navigate('Home') // May race with dialog animation
}
// WRONG - same problem
const onConfirm = () => {
control.close()
otherDialogControl.open() // Will likely fail or cause visual glitches
}
// CORRECT - action runs after dialog fully closes
const onConfirm = () => {
control.close(() => {
navigation.navigate('Home')
})
}
// CORRECT - opening another dialog after close
const onConfirm = () => {
control.close(() => {
otherDialogControl.open()
})
}
// CORRECT - state updates after close
const onConfirm = () => {
control.close(() => {
setSomeState(newValue)
onCallback?.()
})
}
This applies to:
- Navigation (
navigation.navigate(),navigation.push()) - Opening other dialogs or menus
- State updates that affect UI (
setState,queryClient.invalidateQueries) - Callbacks passed from parent components
The Menu component on iOS specifically uses this pattern - see src/components/Menu/index.tsx:151.
Controlled vs Uncontrolled Inputs
Prefer defaultValue over value for TextInput on the old architecture:
// Preferred - uncontrolled
<TextField.Input
defaultValue={initialEmail}
onChangeText={setEmail}
/>
// Avoid when possible - controlled (can cause performance issues)
<TextField.Input
value={email}
onChangeText={setEmail}
/>
Platform-Specific Behavior
Some components behave differently across platforms:
Dialog.Handle- Only renders on native (drag handle for bottom sheet)Dialog.Close- Only renders on web (X button)Menu.Divider- Only renders on webMenu.ContainerItem- Only works on native
Always test on multiple platforms when using these components.
React Compiler is Enabled
This codebase uses React Compiler, so don't proactively add useMemo or useCallback. The compiler handles memoization automatically.
// UNNECESSARY - React Compiler handles this
const handlePress = useCallback(() => {
doSomething()
}, [doSomething])
// JUST WRITE THIS
const handlePress = () => {
doSomething()
}
Only use useMemo/useCallback when you have a specific reason, such as:
- The value is immediately used in an effect's dependency array
- You're passing a callback to a non-React library that needs referential stability
Best Practices
-
Accessibility: Always provide
labelprop for interactive elements, useaccessibilityHintwhere helpful -
Translations: Wrap ALL user-facing strings with
msg()or<Trans> -
Styling: Combine static atoms with theme atoms, use platform utilities for platform-specific styles
-
State: Use TanStack Query for server state, React Context for UI preferences
-
Components: Check if a component exists in
#/components/before creating new ones -
Types: Define explicit types for props, use
NativeStackScreenPropsfor screens -
Testing: Components should have
testIDprops for E2E testing
Key Files Reference
| Purpose | Location |
|---|---|
| Theme definitions | src/alf/themes.ts |
| Design tokens | src/alf/tokens.ts |
| Static atoms | src/alf/atoms.ts (extends @bsky.app/alf) |
| Navigation config | src/Navigation.tsx |
| Route definitions | src/routes.ts |
| Route types | src/lib/routes/types.ts |
| Query hooks | src/state/queries/*.ts |
| Session state | src/state/session/index.tsx |
| i18n setup | src/locale/i18n.ts |