forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 💫
1# CLAUDE.md - Bluesky Social App Development Guide
2
3This document provides guidance for working effectively in the Bluesky Social app codebase.
4
5## Project Overview
6
7Bluesky 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.
8
9**Tech Stack:**
10- React Native 0.81 with Expo 54
11- TypeScript
12- React Navigation for routing
13- TanStack Query (React Query) for data fetching
14- Lingui for internationalization
15- Custom design system called ALF (Application Layout Framework)
16
17## Essential Commands
18
19```bash
20# Development
21yarn start # Start Expo dev server
22yarn web # Start web version
23yarn android # Run on Android
24yarn ios # Run on iOS
25
26# Testing & Quality
27# IMPORTANT: Always use these yarn scripts, never call the underlying tools directly
28yarn test # Run Jest tests
29yarn lint # Run ESLint
30yarn typecheck # Run TypeScript type checking
31
32# Internationalization
33# DO NOT run these commands - extraction and compilation are handled by CI
34yarn intl:extract # Extract translation strings (nightly CI job)
35yarn intl:compile # Compile translations for runtime (nightly CI job)
36
37# Build
38yarn build-web # Build web version
39yarn prebuild # Generate native projects
40```
41
42## Project Structure
43
44```
45src/
46├── alf/ # Design system (ALF) - themes, atoms, tokens
47├── components/ # Shared UI components (Button, Dialog, Menu, etc.)
48├── screens/ # Full-page screen components (newer pattern)
49├── view/
50│ ├── screens/ # Full-page screens (legacy location)
51│ ├── com/ # Reusable view components
52│ └── shell/ # App shell (navigation bars, tabs)
53├── state/
54│ ├── queries/ # TanStack Query hooks
55│ ├── preferences/ # User preferences (React Context)
56│ ├── session/ # Authentication state
57│ └── persisted/ # Persistent storage layer
58├── lib/ # Utilities, constants, helpers
59├── locale/ # i18n configuration and language files
60└── Navigation.tsx # Main navigation configuration
61```
62
63## Styling System (ALF)
64
65ALF is the custom design system. It uses Tailwind-inspired naming with underscores instead of hyphens.
66
67### Basic Usage
68
69```tsx
70import {atoms as a, useTheme} from '#/alf'
71
72function MyComponent() {
73 const t = useTheme()
74
75 return (
76 <View style={[a.flex_row, a.gap_md, a.p_lg, t.atoms.bg]}>
77 <Text style={[a.text_md, a.font_bold, t.atoms.text]}>
78 Hello
79 </Text>
80 </View>
81 )
82}
83```
84
85### Key Concepts
86
87**Static Atoms** - Theme-independent styles imported from `atoms`:
88```tsx
89import {atoms as a} from '#/alf'
90// a.flex_row, a.p_md, a.gap_sm, a.rounded_md, a.text_lg, etc.
91```
92
93**Theme Atoms** - Theme-dependent colors from `useTheme()`:
94```tsx
95const t = useTheme()
96// t.atoms.bg, t.atoms.text, t.atoms.border_contrast_low, etc.
97// t.palette.primary_500, t.palette.negative_400, etc.
98```
99
100**Platform Utilities** - For platform-specific styles:
101```tsx
102import {web, native, ios, android, platform} from '#/alf'
103
104const styles = [
105 a.p_md,
106 web({cursor: 'pointer'}),
107 native({paddingBottom: 20}),
108 platform({ios: {...}, android: {...}, web: {...}}),
109]
110```
111
112**Breakpoints** - Responsive design:
113```tsx
114import {useBreakpoints} from '#/alf'
115
116const {gtPhone, gtMobile, gtTablet} = useBreakpoints()
117if (gtMobile) {
118 // Tablet or desktop layout
119}
120```
121
122### Naming Conventions
123
124- Spacing: `2xs`, `xs`, `sm`, `md`, `lg`, `xl`, `2xl` (t-shirt sizes)
125- Text: `text_xs`, `text_sm`, `text_md`, `text_lg`, `text_xl`
126- Gaps/Padding: `gap_sm`, `p_md`, `px_lg`, `py_xl`
127- Flex: `flex_row`, `flex_1`, `align_center`, `justify_between`
128- Borders: `border`, `border_t`, `rounded_md`, `rounded_full`
129
130## Component Patterns
131
132### Dialog Component
133
134Dialogs use a bottom sheet on native and a modal on web. Use `useDialogControl()` hook to manage state.
135
136```tsx
137import * as Dialog from '#/components/Dialog'
138
139function MyFeature() {
140 const control = Dialog.useDialogControl()
141
142 return (
143 <>
144 <Button label="Open" onPress={control.open}>
145 <ButtonText>Open Dialog</ButtonText>
146 </Button>
147
148 <Dialog.Outer control={control}>
149 {/* Typically the inner part is in its own component */}
150 <Dialog.Handle /> {/* Native-only drag handle */}
151 <Dialog.ScrollableInner label={_(msg`My Dialog`)}>
152 <Dialog.Header>
153 <Dialog.HeaderText>Title</Dialog.HeaderText>
154 </Dialog.Header>
155
156 <Text>Dialog content here</Text>
157
158 <Button label="Done" onPress={() => control.close()}>
159 <ButtonText>Done</ButtonText>
160 </Button>
161 <Dialog.Close /> {/* Web-only X button in top left */}
162 </Dialog.ScrollableInner>
163 </Dialog.Outer>
164 </>
165 )
166}
167```
168
169### Menu Component
170
171Menus render as a dropdown on web and a bottom sheet dialog on native.
172
173```tsx
174import * as Menu from '#/components/Menu'
175
176function MyMenu() {
177 return (
178 <Menu.Root>
179 <Menu.Trigger label="Open menu">
180 {({props}) => (
181 <Button {...props} label="Menu">
182 <ButtonIcon icon={DotsHorizontal} />
183 </Button>
184 )}
185 </Menu.Trigger>
186
187 <Menu.Outer>
188 <Menu.Group>
189 <Menu.Item label="Edit" onPress={handleEdit}>
190 <Menu.ItemIcon icon={Pencil} />
191 <Menu.ItemText>Edit</Menu.ItemText>
192 </Menu.Item>
193 <Menu.Item label="Delete" onPress={handleDelete}>
194 <Menu.ItemIcon icon={Trash} />
195 <Menu.ItemText>Delete</Menu.ItemText>
196 </Menu.Item>
197 </Menu.Group>
198 </Menu.Outer>
199 </Menu.Root>
200 )
201}
202```
203
204### Button Component
205
206```tsx
207import {Button, ButtonText, ButtonIcon} from '#/components/Button'
208
209// Solid primary button (most common)
210<Button label="Save" onPress={handleSave} color="primary" size="large">
211 <ButtonText>Save</ButtonText>
212</Button>
213
214// With icon
215<Button label="Share" onPress={handleShare} color="secondary" size="small">
216 <ButtonIcon icon={Share} />
217 <ButtonText>Share</ButtonText>
218</Button>
219
220// Icon-only button
221<Button label="Close" onPress={handleClose} color="secondary" size="small" shape="round">
222 <ButtonIcon icon={XIcon} />
223</Button>
224
225// Ghost variant (deprecated - use color prop)
226<Button label="Cancel" variant="ghost" color="secondary" size="small">
227 <ButtonText>Cancel</ButtonText>
228</Button>
229```
230
231**Button Props:**
232- `color`: `'primary'` | `'secondary'` | `'negative'` | `'primary_subtle'` | `'negative_subtle'` | `'secondary_inverted'`
233- `size`: `'tiny'` | `'small'` | `'large'`
234- `shape`: `'default'` (pill) | `'round'` | `'square'` | `'rectangular'`
235- `variant`: `'solid'` | `'outline'` | `'ghost'` (deprecated, use `color`)
236
237### Typography
238
239```tsx
240import {Text, H1, H2, P} from '#/components/Typography'
241
242<H1 style={[a.text_xl, a.font_bold]}>Heading</H1>
243<P>Paragraph text with default styling.</P>
244<Text style={[a.text_sm, t.atoms.text_contrast_medium]}>Custom text</Text>
245
246// For text with emoji, add the emoji prop
247<Text emoji>Hello! 👋</Text>
248```
249
250### TextField
251
252```tsx
253import * as TextField from '#/components/forms/TextField'
254
255<TextField.LabelText>Email</TextField.LabelText>
256<TextField.Root>
257 <TextField.Icon icon={AtSign} />
258 <TextField.Input
259 label="Email address"
260 placeholder="you@example.com"
261 defaultValue={email}
262 onChangeText={setEmail}
263 keyboardType="email-address"
264 autoCapitalize="none"
265 />
266</TextField.Root>
267```
268
269## Internationalization (i18n)
270
271All user-facing strings must be wrapped for translation using Lingui.
272
273```tsx
274import {msg, Trans, plural} from '@lingui/macro'
275import {useLingui} from '@lingui/react'
276
277function MyComponent() {
278 const {_} = useLingui()
279
280 // Simple strings - use msg() with _() function
281 const title = _(msg`Settings`)
282 const errorMessage = _(msg`Something went wrong`)
283
284 // Strings with variables
285 const greeting = _(msg`Hello, ${name}!`)
286
287 // Pluralization
288 const countLabel = _(plural(count, {
289 one: '# item',
290 other: '# items',
291 }))
292
293 // JSX content - use Trans component
294 return (
295 <Text>
296 <Trans>Welcome to <Text style={a.font_bold}>Bluesky</Text></Trans>
297 </Text>
298 )
299}
300```
301
302**Commands:**
303```bash
304# DO NOT run these commands - extraction and compilation are handled by a nightly CI job
305yarn intl:extract # Extract new strings to locale files
306yarn intl:compile # Compile translations for runtime
307```
308
309## State Management
310
311### TanStack Query (Data Fetching)
312
313```tsx
314// src/state/queries/profile.ts
315import {useQuery, useMutation, useQueryClient} from '@tanstack/react-query'
316
317// Query key pattern
318const RQKEY_ROOT = 'profile'
319export const RQKEY = (did: string) => [RQKEY_ROOT, did]
320
321// Query hook
322export function useProfileQuery({did}: {did: string}) {
323 const agent = useAgent()
324
325 return useQuery({
326 queryKey: RQKEY(did),
327 queryFn: async () => {
328 const res = await agent.getProfile({actor: did})
329 return res.data
330 },
331 staleTime: STALE.MINUTES.FIVE,
332 enabled: !!did,
333 })
334}
335
336// Mutation hook
337export function useUpdateProfile() {
338 const queryClient = useQueryClient()
339
340 return useMutation({
341 mutationFn: async (data) => {
342 // Update logic
343 },
344 onSuccess: (_, variables) => {
345 queryClient.invalidateQueries({queryKey: RQKEY(variables.did)})
346 },
347 onError: (error) => {
348 if (isNetworkError(error)) {
349 // don't log, but inform user
350 } else if (error instanceof AppBskyExampleProcedure.ExampleError) {
351 // XRPC APIs often have typed errors, allows nicer handling
352 } else {
353 // Log unexpected errors to Sentry
354 logger.error('Error updating profile', {safeMessage: error})
355 }
356 }
357 })
358}
359```
360
361**Stale Time Constants** (from `src/state/queries/index.ts`):
362```tsx
363STALE.SECONDS.FIFTEEN // 15 seconds
364STALE.MINUTES.ONE // 1 minute
365STALE.MINUTES.FIVE // 5 minutes
366STALE.HOURS.ONE // 1 hour
367STALE.INFINITY // Never stale
368```
369
370**Paginated APIs:** Many atproto APIs return paginated results with a `cursor`. Use `useInfiniteQuery` for these:
371
372```tsx
373export function useDraftsQuery() {
374 const agent = useAgent()
375
376 return useInfiniteQuery({
377 queryKey: ['drafts'],
378 queryFn: async ({pageParam}) => {
379 const res = await agent.app.bsky.draft.getDrafts({cursor: pageParam})
380 return res.data
381 },
382 initialPageParam: undefined as string | undefined,
383 getNextPageParam: page => page.cursor,
384 })
385}
386```
387
388To get all items from pages: `data?.pages.flatMap(page => page.items) ?? []`
389
390### Preferences (React Context)
391
392```tsx
393// Simple boolean preference pattern
394import {useAutoplayDisabled, useSetAutoplayDisabled} from '#/state/preferences'
395
396function SettingsScreen() {
397 const autoplayDisabled = useAutoplayDisabled()
398 const setAutoplayDisabled = useSetAutoplayDisabled()
399
400 return (
401 <Toggle
402 value={autoplayDisabled}
403 onValueChange={setAutoplayDisabled}
404 />
405 )
406}
407```
408
409### Session State
410
411```tsx
412import {useSession, useAgent} from '#/state/session'
413
414function MyComponent() {
415 const {hasSession, currentAccount} = useSession()
416 const agent = useAgent()
417
418 if (!hasSession) {
419 return <LoginPrompt />
420 }
421
422 // Use agent for API calls
423 const response = await agent.getProfile({actor: currentAccount.did})
424}
425```
426
427## Navigation
428
429Navigation uses React Navigation with type-safe route parameters.
430
431```tsx
432// Screen component
433import {type NativeStackScreenProps} from '@react-navigation/native-stack'
434import {type CommonNavigatorParams} from '#/lib/routes/types'
435
436type Props = NativeStackScreenProps<CommonNavigatorParams, 'Profile'>
437
438export function ProfileScreen({route, navigation}: Props) {
439 const {name} = route.params // Type-safe params
440
441 return (
442 <Layout.Screen>
443 {/* Screen content */}
444 </Layout.Screen>
445 )
446}
447
448// Programmatic navigation
449import {useNavigation} from '@react-navigation/native'
450
451const navigation = useNavigation()
452navigation.navigate('Profile', {name: 'alice.bsky.social'})
453
454// Or use the navigate helper
455import {navigate} from '#/Navigation'
456navigate('Profile', {name: 'alice.bsky.social'})
457```
458
459## Platform-Specific Code
460
461Use file extensions for platform-specific implementations:
462
463```
464Component.tsx # Shared/default
465Component.web.tsx # Web-only
466Component.native.tsx # iOS + Android
467Component.ios.tsx # iOS-only
468Component.android.tsx # Android-only
469```
470
471Example from Dialog:
472- `src/components/Dialog/index.tsx` - Native (uses BottomSheet)
473- `src/components/Dialog/index.web.tsx` - Web (uses modal with Radix primitives)
474
475**Important:** The bundler automatically resolves platform-specific files. Just import normally:
476
477```tsx
478// CORRECT - bundler picks storage.ts or storage.web.ts automatically
479import * as storage from '#/state/drafts/storage'
480
481// WRONG - don't use require() or conditional imports for platform files
482const storage = IS_NATIVE
483 ? require('#/state/drafts/storage')
484 : require('#/state/drafts/storage.web')
485```
486
487Platform detection (for runtime logic, not imports):
488```tsx
489import {IS_WEB, IS_NATIVE, IS_IOS, IS_ANDROID} from '#/env'
490
491if (IS_NATIVE) {
492 // Native-specific logic
493}
494```
495
496## Import Aliases
497
498Always use the `#/` alias for absolute imports:
499
500```tsx
501// Good
502import {useSession} from '#/state/session'
503import {atoms as a, useTheme} from '#/alf'
504import {Button} from '#/components/Button'
505
506// Avoid
507import {useSession} from '../../../state/session'
508```
509
510## Footguns
511
512Common pitfalls to avoid in this codebase:
513
514### Dialog Close Callback (Critical)
515
516**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.
517
518```tsx
519// WRONG - causes bugs with state updates, navigation, opening other dialogs
520const onConfirm = () => {
521 control.close()
522 navigation.navigate('Home') // May race with dialog animation
523}
524
525// WRONG - same problem
526const onConfirm = () => {
527 control.close()
528 otherDialogControl.open() // Will likely fail or cause visual glitches
529}
530
531// CORRECT - action runs after dialog fully closes
532const onConfirm = () => {
533 control.close(() => {
534 navigation.navigate('Home')
535 })
536}
537
538// CORRECT - opening another dialog after close
539const onConfirm = () => {
540 control.close(() => {
541 otherDialogControl.open()
542 })
543}
544
545// CORRECT - state updates after close
546const onConfirm = () => {
547 control.close(() => {
548 setSomeState(newValue)
549 onCallback?.()
550 })
551}
552```
553
554This applies to:
555- Navigation (`navigation.navigate()`, `navigation.push()`)
556- Opening other dialogs or menus
557- State updates that affect UI (`setState`, `queryClient.invalidateQueries`)
558- Callbacks passed from parent components
559
560The Menu component on iOS specifically uses this pattern - see `src/components/Menu/index.tsx:151`.
561
562### Controlled vs Uncontrolled Inputs
563
564Prefer `defaultValue` over `value` for TextInput on the old architecture:
565
566```tsx
567// Preferred - uncontrolled
568<TextField.Input
569 defaultValue={initialEmail}
570 onChangeText={setEmail}
571/>
572
573// Avoid when possible - controlled (can cause performance issues)
574<TextField.Input
575 value={email}
576 onChangeText={setEmail}
577/>
578```
579
580### Platform-Specific Behavior
581
582Some components behave differently across platforms:
583- `Dialog.Handle` - Only renders on native (drag handle for bottom sheet)
584- `Dialog.Close` - Only renders on web (X button)
585- `Menu.Divider` - Only renders on web
586- `Menu.ContainerItem` - Only works on native
587
588Always test on multiple platforms when using these components.
589
590### React Compiler is Enabled
591
592This codebase uses React Compiler, so **don't proactively add `useMemo` or `useCallback`**. The compiler handles memoization automatically.
593
594```tsx
595// UNNECESSARY - React Compiler handles this
596const handlePress = useCallback(() => {
597 doSomething()
598}, [doSomething])
599
600// JUST WRITE THIS
601const handlePress = () => {
602 doSomething()
603}
604```
605
606Only use `useMemo`/`useCallback` when you have a specific reason, such as:
607- The value is immediately used in an effect's dependency array
608- You're passing a callback to a non-React library that needs referential stability
609
610## Best Practices
611
6121. **Accessibility**: Always provide `label` prop for interactive elements, use `accessibilityHint` where helpful
613
6142. **Translations**: Wrap ALL user-facing strings with `msg()` or `<Trans>`
615
6163. **Styling**: Combine static atoms with theme atoms, use platform utilities for platform-specific styles
617
6184. **State**: Use TanStack Query for server state, React Context for UI preferences
619
6205. **Components**: Check if a component exists in `#/components/` before creating new ones
621
6226. **Types**: Define explicit types for props, use `NativeStackScreenProps` for screens
623
6247. **Testing**: Components should have `testID` props for E2E testing
625
626## Key Files Reference
627
628| Purpose | Location |
629|---------|----------|
630| Theme definitions | `src/alf/themes.ts` |
631| Design tokens | `src/alf/tokens.ts` |
632| Static atoms | `src/alf/atoms.ts` (extends `@bsky.app/alf`) |
633| Navigation config | `src/Navigation.tsx` |
634| Route definitions | `src/routes.ts` |
635| Route types | `src/lib/routes/types.ts` |
636| Query hooks | `src/state/queries/*.ts` |
637| Session state | `src/state/session/index.tsx` |
638| i18n setup | `src/locale/i18n.ts` |