App.tsx
import { StatusBar } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { Badge, Block, DEFAULT_THEME, Icon, PlocksProvider, SafeArea, Text } from '@plocks/ui';
import { C } from './theme';
import { SECTIONS } from './data';
import { StoreProvider, useStore, type Route, type Tab } from './store';
import { useWide } from './components';
import { Home } from './screens/Home';
import { Categories } from './screens/Categories';
import { Cities } from './screens/Cities';
import { Results } from './screens/Results';
import { ListingView } from './screens/ListingView';
import { Messages } from './screens/Messages';
import { Saved } from './screens/Saved';
import { Post } from './screens/Post';
/** Purple primary ramp so built-in controls (FileInput, focus rings, Select) match the brand. */
const THEME = {
colorScheme: 'light' as const,
primaryColor: C.purple,
colors: {
...DEFAULT_THEME.colors,
primary: ['#F6F1FB', '#EEE8F5', '#DCCDEB', '#C2A8DC', '#8E68B6', C.purple, '#4F2479', '#43206A', '#381A59', '#2C1446'],
},
};
const TABS: { key: Tab; label: string; icon: string }[] = [
{ key: 'browse', label: 'browse', icon: 'search' },
{ key: 'saved', label: 'saved', icon: 'star' },
{ key: 'post', label: 'post', icon: 'plus' },
{ key: 'messages', label: 'messages', icon: 'message' },
];
function RouteView({ route }: { route: Route }) {
switch (route.name) {
case 'home':
return <Home />;
case 'categories':
return <Categories section={route.section} />;
case 'cities':
return <Cities />;
case 'results':
return <Results initial={route.filter} />;
case 'listing':
return <ListingView id={route.id} />;
case 'threads':
return <Messages />;
case 'thread':
return <Messages openId={route.id} />;
case 'saved':
return <Saved />;
case 'post':
return <Post />;
}
}
function routeKey(route: Route) {
switch (route.name) {
case 'listing':
case 'thread':
return `${route.name}:${route.id}`;
case 'categories':
return `categories:${route.section ?? ''}`;
case 'results':
return `results:${JSON.stringify(route.filter)}`;
default:
return route.name;
}
}
function TabButton({ item, vertical }: { item: (typeof TABS)[number]; vertical?: boolean }) {
const store = useStore();
const active = store.tab === item.key;
const count = item.key === 'messages' ? store.unread : 0;
return (
<Block
onPress={() => store.goTab(item.key)}
accessibilityRole="tab"
accessibilityState={{ selected: active }}
accessibilityLabel={count ? `${item.label}, ${count} unread` : item.label}
flex={vertical ? undefined : 1}
direction={vertical ? 'row' : 'column'}
align="center"
gap={vertical ? 10 : 2}
py={vertical ? 9 : 7}
px={vertical ? 12 : 0}
radius={vertical ? 6 : 0}
bg={vertical && active ? C.tint : undefined}
pressedStyle={{ opacity: 0.6 }}
>
<Block gap={0} position="relative">
<Icon name={item.icon} variant={active ? 'filled' : 'outlined'} color={active ? C.purple : C.muted} size={vertical ? 19 : 22} />
{count > 0 && !vertical && (
<Block gap={0} position="absolute" top={-5} right={-10}>
<Badge size="xs" variant="filled" color={C.red}>
{count}
</Badge>
</Block>
)}
</Block>
<Text c={active ? C.purple : C.muted} fw={active ? 'bold' : 'semibold'} size={vertical ? 14 : 11} flex={vertical ? 1 : undefined}>
{item.label}
</Text>
{count > 0 && vertical && (
<Badge size="xs" variant="filled" color={C.red}>
{count}
</Badge>
)}
</Block>
);
}
function Sidebar() {
const store = useStore();
return (
<Block w={220} gap={4} p={16} borderRightWidth={1} borderRightColor={C.line} bg={C.paler}>
<Text c={C.purple} fw="bold" size={26} lts={-0.6} mb={2} onPress={() => store.goTab('browse', true)}>
townlist
</Text>
<Text c={C.link} size={12} mb={14} onPress={() => store.openIn('browse', { name: 'cities' })}>
{store.city.name}
{store.radius ? ` +${store.radius}mi` : ''} · change
</Text>
{TABS.map((item) => (
<TabButton key={item.key} item={item} vertical />
))}
<Block gap={0} h={1} bg={C.line} my={14} />
<Text c={C.muted} fw="bold" size={11} lts={0.8} mb={4}>
CATEGORIES
</Text>
{SECTIONS.map((section) => (
<Text
key={section.id}
c={C.link}
size={14}
lh={24}
onPress={() => store.openIn('browse', { name: 'categories', section: section.id })}
>
{section.label}
</Text>
))}
<Block gap={0} flex={1} />
<Text c={C.faint} size={11} lh={16}>
a fictional classifieds demo built with plocks. nothing leaves this device.
</Text>
</Block>
);
}
function Shell() {
const store = useStore();
const wide = useWide();
return (
<SafeArea gap={0} flex={1} bg={wide ? C.pale : C.white}>
<StatusBar barStyle="dark-content" />
<Block gap={0} flex={1} direction={wide ? 'row' : 'column'} w="100%" maw={1320} alignSelf="center" bg={C.white}>
{wide && <Sidebar />}
<Block gap={0} flex={1} miw={0}>
<RouteView key={`${store.tab}:${routeKey(store.route)}`} route={store.route} />
</Block>
{!wide && (
<Block gap={0} direction="row" borderTopWidth={1} borderTopColor={C.line} bg={C.white} accessibilityRole="tablist">
{TABS.map((item) => (
<TabButton key={item.key} item={item} />
))}
</Block>
)}
</Block>
</SafeArea>
);
}
export default function App() {
return (
<SafeAreaProvider>
<PlocksProvider theme={THEME}>
<StoreProvider>
<Shell />
</StoreProvider>
</PlocksProvider>
</SafeAreaProvider>
);
}
components.tsx
/** Shared Townlist building blocks. */
import type { ReactNode } from 'react';
import { useWindowDimensions } from 'react-native';
import { Badge, Block, Icon, IconButton, Image, ScrollArea, Text } from '@plocks/ui';
import { C, WIDE } from './theme';
import { ageText, cityById, photoSource, priceText, sectionById, type Listing } from './data';
import { useStore } from './store';
export const useWide = () => useWindowDimensions().width >= WIDE;
export function TopBar({
title,
subtitle,
onBack,
right,
}: {
title: ReactNode;
subtitle?: ReactNode;
onBack?: () => void;
right?: ReactNode;
}) {
return (
<Block
gap={6}
direction="row"
align="center"
mih={54}
px={onBack ? 6 : 16}
pr={10}
bg={C.white}
borderBottomWidth={1}
borderBottomColor={C.line}
>
{onBack && (
<IconButton icon="chevron-left" variant="ghost" iconColor={C.purple} accessibilityLabel="Back" onPress={onBack} />
)}
<Block flex={1} miw={0} gap={0}>
{typeof title === 'string' ? (
<Text c={C.ink} fw="bold" size={17} numberOfLines={1}>
{title}
</Text>
) : (
title
)}
{!!subtitle && (
<Text c={C.muted} size={12} numberOfLines={1}>
{subtitle}
</Text>
)}
</Block>
{right}
</Block>
);
}
/** A scrolling page with a top bar and a centered content column. */
export function Screen({
title,
subtitle,
right,
children,
maw = 880,
back,
footer,
}: {
title: ReactNode;
subtitle?: ReactNode;
right?: ReactNode;
children: ReactNode;
maw?: number;
back?: boolean;
footer?: ReactNode;
}) {
const store = useStore();
const wide = useWide();
return (
<Block gap={0} flex={1} bg={C.white}>
<TopBar title={title} subtitle={subtitle} right={right} onBack={back && store.canGoBack ? store.back : undefined} />
<ScrollArea flex={1} keyboardShouldPersistTaps="handled" contentProps={{ align: 'center', px: wide ? 24 : 14, pt: 14, pb: 40 }}>
<Block gap={0} w="100%" maw={maw}>
{children}
</Block>
</ScrollArea>
{footer}
</Block>
);
}
export function SectionLabel({ children, right, mt = 18 }: { children: ReactNode; right?: ReactNode; mt?: number }) {
return (
<Block gap={0} direction="row" align="flex-end" justify="space-between" mt={mt} mb={6}>
<Text c={C.muted} fw="bold" size={11} lts={0.8} tt="uppercase">
{children}
</Text>
{right}
</Block>
);
}
export function Thumb({ listing, w, h, radius = 4 }: { listing: Listing; w: number | string; h: number; radius?: number }) {
const first = listing.photos[0];
if (first) return <Image src={photoSource(first)} w={w as number} h={h} radius={radius} resizeMode="cover" alt="" />;
return (
<Block gap={4} w={w as number} h={h} radius={radius} bg={C.pale} align="center" justify="center" borderWidth={1} borderColor={C.line}>
<Icon name={sectionById(listing.section).icon} color={C.faint} size={Math.min(28, h / 3)} />
{h > 70 && (
<Text c={C.faint} size={10}>
no image
</Text>
)}
</Block>
);
}
export function PriceTag({ listing, size = 13 }: { listing: Listing; size?: number }) {
const text = priceText(listing);
if (!text) return null;
return (
<Block gap={0} px={6} py={1} radius={3} bg={listing.price === 0 ? C.greenPale : C.pale} alignSelf="flex-start">
<Text c={listing.price === 0 ? C.green : C.ink} fw="bold" size={size}>
{text}
</Text>
</Block>
);
}
export function FavoriteButton({ id, size = 20 }: { id: string; size?: number }) {
const store = useStore();
const on = store.favorites.includes(id);
return (
<IconButton
icon="star"
iconVariant={on ? 'filled' : 'outlined'}
iconColor={on ? '#D49A00' : C.faint}
iconSize={size}
variant="ghost"
size="sm"
accessibilityLabel={on ? 'Remove from favorites' : 'Add to favorites'}
onPress={() => store.toggleFavorite(id)}
/>
);
}
/** Dense list row, like the classic "thumb" results view. */
export function ListingRow({ listing, onPress }: { listing: Listing; onPress: () => void }) {
const store = useStore();
const wide = useWide();
const city = cityById(listing.cityId);
const away = listing.cityId !== store.cityId;
const size = wide ? 92 : 78;
return (
<Block
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={`View ${listing.title}`}
direction="row"
gap={12}
py={10}
borderBottomWidth={1}
borderBottomColor={C.line}
pressedStyle={{ opacity: 0.7 }}
>
<Thumb listing={listing} w={size} h={size} />
<Block flex={1} miw={0} gap={4}>
<Text c={C.link} fw="semibold" size={15} lh={20} numberOfLines={2}>
{listing.title}
</Text>
<Block gap={6} direction="row" align="center" wrap>
<PriceTag listing={listing} />
{listing.price === null && !!listing.attrs[0] && (
<Text c={C.body} size={12} numberOfLines={1}>
{listing.attrs[0].value}
</Text>
)}
</Block>
<Text c={C.muted} size={12} numberOfLines={1}>
{listing.hood}
{away ? ` · ${city.name}` : ''} · {ageText(listing.postedAt)}
{listing.mine ? ' · your post' : ''}
</Text>
</Block>
<Block gap={0} alignSelf="flex-start">
<FavoriteButton id={listing.id} />
</Block>
</Block>
);
}
/** Gallery tile for grid views. */
export function ListingTile({ listing, w, onPress }: { listing: Listing; w: number; onPress: () => void }) {
return (
<Block
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={`View ${listing.title}`}
w={w}
gap={0}
radius={6}
overflow="hidden"
borderWidth={1}
borderColor={C.line}
bg={C.white}
pressedStyle={{ opacity: 0.7 }}
>
<Thumb listing={listing} w="100%" h={Math.round(w * 0.72)} radius={0} />
<Block gap={3} p={8}>
<Block gap={0} direction="row" align="center" justify="space-between" mih={22}>
<PriceTag listing={listing} size={12} />
<Text c={C.faint} size={11}>
{ageText(listing.postedAt)}
</Text>
</Block>
<Text c={C.link} fw="semibold" size={13} lh={17} numberOfLines={2}>
{listing.title}
</Text>
<Text c={C.muted} size={11} numberOfLines={1}>
{listing.hood}
</Text>
</Block>
</Block>
);
}
/** A drawn, approximate-location map tile (no map service needed). */
export function MapBlock({ hood, cityId, h = 170 }: { hood: string; cityId: string; h?: number }) {
const city = cityById(cityId);
const seed = [...hood].reduce((sum, ch) => sum + ch.charCodeAt(0), 0);
const pinX = 30 + (seed % 40);
const pinY = 30 + ((seed * 7) % 35);
return (
<Block gap={0} h={h} radius={6} overflow="hidden" bg={C.map} borderWidth={1} borderColor={C.line} position="relative">
<Block gap={0} position="absolute" left="-10%" top="62%" w="70%" h="60%" radius={200} bg={C.mapWater} />
<Block gap={0} position="absolute" left="68%" top="8%" w="22%" h="34%" radius={10} bg={C.mapPark} />
{[18, 46, 78].map((top) => (
<Block key={`h${top}`} gap={0} position="absolute" left={0} right={0} top={`${top}%`} h={top === 46 ? 7 : 4} bg={C.mapRoad} />
))}
{[22, 52, 84].map((left) => (
<Block key={`v${left}`} gap={0} position="absolute" top={0} bottom={0} left={`${left}%`} w={left === 52 ? 7 : 4} bg={C.mapRoad} />
))}
<Block gap={0} position="absolute" left={`${pinX}%`} top={`${pinY}%`} translateX={-43} translateY={-43} w={86} h={86} radius={43} bg="rgba(91,42,140,0.14)" borderWidth={1} borderColor="rgba(91,42,140,0.35)" align="center" justify="center">
<Block gap={0} w={20} h={20} radius={10} bg={C.purple} borderWidth={3} borderColor={C.white} shadow="sm" />
</Block>
<Block gap={0} position="absolute" left={8} bottom={8} px={8} py={4} radius={4} bg="rgba(255,255,255,0.92)">
<Text c={C.ink} fw="semibold" size={12}>
{hood}, {city.name}
</Text>
<Text c={C.muted} size={10}>
approximate location
</Text>
</Block>
</Block>
);
}
export function EmptyNote({ icon, title, children }: { icon: string; title: string; children?: ReactNode }) {
return (
<Block gap={8} align="center" py={44} px={20}>
<Block gap={0} w={52} h={52} radius={26} bg={C.pale} align="center" justify="center">
<Icon name={icon} color={C.purple} size={24} />
</Block>
<Text c={C.ink} fw="semibold" size={15} ta="center">
{title}
</Text>
{!!children && (
<Text c={C.muted} size={13} ta="center" lh={19}>
{children}
</Text>
)}
</Block>
);
}
export function SectionBadge({ listing }: { listing: Listing }) {
return (
<Badge size="xs" variant="light" color={C.purple}>
{sectionById(listing.section).label}
</Badge>
);
}
data.ts
/** Fictional sample data for Townlist: areas, categories, listings, and message threads. */
import type { ImageSourcePropType } from 'react-native';
// ---------------------------------------------------------------- photos
export const PHOTOS = {
bicycle: require('./assets/listings/bicycle.webp'),
chairRoom: require('./assets/listings/chair-room.webp'),
livingRoom: require('./assets/listings/living-room.webp'),
apartment: require('./assets/listings/apartment.webp'),
balcony: require('./assets/listings/balcony.webp'),
desk: require('./assets/listings/desk.webp'),
studio: require('./assets/listings/studio.webp'),
cafe: require('./assets/listings/cafe.webp'),
} as const;
export type PhotoKey = keyof typeof PHOTOS;
export const PHOTO_KEYS = Object.keys(PHOTOS) as PhotoKey[];
export const PHOTO_LABELS: Record<PhotoKey, string> = {
bicycle: 'Bicycle',
chairRoom: 'Reading nook',
livingRoom: 'Living room',
apartment: 'Apartment',
balcony: 'Balcony',
desk: 'Desk',
studio: 'Studio',
cafe: 'Café',
};
/** A listing photo: a bundled asset key or an image URI picked by the user. */
export type Photo = { id: string; src: PhotoKey | string; caption?: string };
export const photoSource = (photo: Photo): ImageSourcePropType | string =>
photo.src in PHOTOS ? PHOTOS[photo.src as PhotoKey] : photo.src;
// ---------------------------------------------------------------- areas
export type Region = { id: string; label: string };
export type City = { id: string; name: string; region: string; x: number; y: number; hoods: string[] };
export const REGIONS: Region[] = [
{ id: 'northwest', label: 'Northwest' },
{ id: 'west', label: 'West Coast' },
{ id: 'mountain', label: 'Mountain' },
{ id: 'midwest', label: 'Midwest' },
{ id: 'northeast', label: 'Northeast' },
{ id: 'south', label: 'South' },
];
/** Positions are in miles on a flat map, used to compute "nearby" distances. */
export const CITIES: City[] = [
{ id: 'alder-bay', name: 'alder bay', region: 'northwest', x: 0, y: 0, hoods: ['downtown', 'northside', 'midtown', 'west end', 'east village', 'riverside', 'harbor district', 'university hill'] },
{ id: 'millbrook', name: 'millbrook', region: 'northwest', x: 9, y: 8, hoods: ['old town', 'mill district', 'brookside'] },
{ id: 'cedar-point', name: 'cedar point', region: 'northwest', x: -14, y: 16, hoods: ['the point', 'lakeview', 'cedar heights'] },
{ id: 'fernwood', name: 'fernwood', region: 'northwest', x: 22, y: -19, hoods: ['fern hollow', 'station square', 'south fernwood'] },
{ id: 'granite-falls', name: 'granite falls', region: 'northwest', x: 46, y: 31, hoods: ['falls center', 'quarry hill'] },
{ id: 'port-juniper', name: 'port juniper', region: 'northwest', x: -58, y: 44, hoods: ['the docks', 'juniper park', 'eastport'] },
{ id: 'kestrel-island', name: 'kestrel island', region: 'northwest', x: -92, y: -12, hoods: ['ferry landing', 'north shore'] },
{ id: 'solana-vista', name: 'solana vista', region: 'west', x: 140, y: 690, hoods: ['mission flats', 'vista heights', 'seawall'] },
{ id: 'mesa-linda', name: 'mesa linda', region: 'west', x: 210, y: 760, hoods: ['arroyo', 'old mesa'] },
{ id: 'oak-hollow', name: 'oak hollow', region: 'west', x: 95, y: 540, hoods: ['hollow center', 'vineyard row'] },
{ id: 'bayview-heights', name: 'bayview heights', region: 'west', x: 60, y: 610, hoods: ['the heights', 'pier side'] },
{ id: 'ridgeway', name: 'ridgeway', region: 'mountain', x: 640, y: 420, hoods: ['upper ridge', 'canyon road'] },
{ id: 'silver-fork', name: 'silver fork', region: 'mountain', x: 720, y: 360, hoods: ['mine row', 'riverbend'] },
{ id: 'pinecrest', name: 'pinecrest', region: 'mountain', x: 590, y: 520, hoods: ['pine center', 'trailhead'] },
{ id: 'lakeport', name: 'lakeport', region: 'midwest', x: 1520, y: 300, hoods: ['lakefront', 'warehouse district', 'west lakeport'] },
{ id: 'prairie-junction', name: 'prairie junction', region: 'midwest', x: 1380, y: 420, hoods: ['the junction', 'grain row'] },
{ id: 'cobalt-creek', name: 'cobalt creek', region: 'midwest', x: 1460, y: 510, hoods: ['creekside', 'market square'] },
{ id: 'harborview', name: 'harborview', region: 'northeast', x: 2350, y: 210, hoods: ['wharf', 'beacon hill', 'south harbor'] },
{ id: 'elm-hollow', name: 'elm hollow', region: 'northeast', x: 2290, y: 260, hoods: ['the green', 'elm row'] },
{ id: 'stonebridge', name: 'stonebridge', region: 'northeast', x: 2240, y: 330, hoods: ['bridge street', 'mill pond'] },
{ id: 'magnolia-springs', name: 'magnolia springs', region: 'south', x: 1850, y: 980, hoods: ['the springs', 'old square'] },
{ id: 'bayou-cross', name: 'bayou cross', region: 'south', x: 1600, y: 1100, hoods: ['crossroads', 'bayou side'] },
{ id: 'red-clay', name: 'red clay', region: 'south', x: 1980, y: 900, hoods: ['clay hills', 'depot district'] },
];
export const HOME_CITY = 'alder-bay';
export const cityById = (id: string) => CITIES.find((city) => city.id === id) ?? CITIES[0];
export const distance = (a: City, b: City) => Math.round(Math.hypot(a.x - b.x, a.y - b.y));
// ---------------------------------------------------------------- categories
export type SectionId = 'sale' | 'housing' | 'jobs' | 'services' | 'community' | 'gigs';
export type Sub = { id: string; label: string };
export type Section = { id: SectionId; label: string; icon: string; blurb: string; subs: Sub[] };
const subs = (labels: string[]): Sub[] => labels.map((label) => ({ id: label.replace(/[^a-z0-9]+/g, '-'), label }));
export const SECTIONS: Section[] = [
{
id: 'sale',
label: 'for sale',
icon: 'shop',
blurb: 'furniture, bikes, electronics',
subs: subs(['antiques', 'appliances', 'arts+crafts', 'baby+kid', 'bikes', 'books', 'cars+trucks', 'cell phones', 'clothes+acc', 'computers', 'electronics', 'farm+garden', 'free stuff', 'furniture', 'general', 'household', 'musical instruments', 'photo+video', 'sporting', 'tools', 'toys+games']),
},
{
id: 'housing',
label: 'housing',
icon: 'home',
blurb: 'apartments, rooms, sublets',
subs: subs(['apts/housing', 'rooms/shared', 'sublets/temporary', 'housing wanted', 'housing swap', 'vacation rentals', 'parking/storage', 'office/commercial', 'real estate for sale']),
},
{
id: 'jobs',
label: 'jobs',
icon: 'package',
blurb: 'full time, part time, local',
subs: subs(['admin/office', 'art/media/design', 'customer service', 'education', 'food/bev/hosp', 'general labor', 'healthcare', 'retail/wholesale', 'sales', 'skilled trade', 'software/qa', 'transport']),
},
{
id: 'services',
label: 'services',
icon: 'tuning',
blurb: 'repairs, lessons, moving',
subs: subs(['automotive', 'beauty', 'computer', 'creative', 'cycle', 'event', 'household', 'labor/move', 'lessons', 'pet', 'skilled trade', 'write/ed/translate']),
},
{
id: 'community',
label: 'community',
icon: 'user',
blurb: 'events, groups, lost+found',
subs: subs(['activities', 'artists', 'childcare', 'classes', 'events', 'general', 'groups', 'lost+found', 'musicians', 'pets', 'rideshare', 'volunteers']),
},
{
id: 'gigs',
label: 'gigs',
icon: 'bolt',
blurb: 'short jobs, odd jobs',
subs: subs(['computer', 'creative', 'crew', 'domestic', 'event', 'labor', 'talent', 'writing']),
},
];
export const sectionById = (id: SectionId) => SECTIONS.find((section) => section.id === id) ?? SECTIONS[0];
export const subLabel = (section: SectionId, sub: string) =>
sectionById(section).subs.find((item) => item.id === sub)?.label ?? sub;
export const sub = (label: string) => label.replace(/[^a-z0-9]+/g, '-');
// ---------------------------------------------------------------- post types
export type PostType = { id: string; label: string; hint: string; section: SectionId };
export const POST_TYPES: PostType[] = [
{ id: 'owner', label: 'for sale by owner', hint: "I'm selling something I own", section: 'sale' },
{ id: 'dealer', label: 'for sale by dealer', hint: "I'm a business selling goods", section: 'sale' },
{ id: 'wanted', label: 'wanted by owner', hint: "I'm looking to buy something", section: 'sale' },
{ id: 'housing', label: 'housing offered', hint: 'I have a place to rent, sublet, or share', section: 'housing' },
{ id: 'housing-wanted', label: 'housing wanted', hint: "I'm looking for a place", section: 'housing' },
{ id: 'job', label: 'job offered', hint: "I'm hiring for a position", section: 'jobs' },
{ id: 'gig', label: 'gig offered', hint: "I'm hiring for a short-term or odd job", section: 'gigs' },
{ id: 'service', label: 'service offered', hint: "I'm offering a service", section: 'services' },
{ id: 'community', label: 'community', hint: 'groups, lost+found, rideshare, and more', section: 'community' },
{ id: 'event', label: 'event / class', hint: "I'm promoting an event or class", section: 'community' },
];
export const postTypeById = (id: string) => POST_TYPES.find((type) => type.id === id) ?? POST_TYPES[0];
// ---------------------------------------------------------------- listings
export type Attr = { label: string; value: string };
export type Listing = {
id: string;
title: string;
/** null when the post has no single price (jobs, events, wanted ads). */
price: number | null;
/** Shown after the price, such as "/mo" or "/hr". */
per?: string;
section: SectionId;
sub: string;
postType: string;
cityId: string;
hood: string;
postedAt: number;
updatedAt?: number;
body: string;
photos: Photo[];
attrs: Attr[];
seller: string;
mine?: boolean;
};
const NOW = Date.now();
const MIN = 60_000;
const ago = (minutes: number) => NOW - minutes * MIN;
const pics = (id: string, ...keys: PhotoKey[]): Photo[] => keys.map((key, index) => ({ id: `${id}-${index}`, src: key }));
export const LISTINGS: Listing[] = [
{
id: '7801', title: 'Commuter bike, 54cm, new tires', price: 220, section: 'sale', sub: sub('bikes'), postType: 'owner',
cityId: 'alder-bay', hood: 'downtown', postedAt: ago(38), seller: 'Alex',
photos: pics('7801', 'bicycle'),
attrs: [{ label: 'condition', value: 'excellent' }, { label: 'bicycle type', value: 'hybrid/comfort' }, { label: 'frame size', value: '54 cm' }, { label: 'make / manufacturer', value: 'Larkspur Cycles' }, { label: 'model name / number', value: 'Metro 7' }, { label: 'wheel size', value: '700C' }],
body: 'Reliable city bike I rode to work for two years. New tires and brake pads last month, shifts cleanly through all 7 gears. Comfortable upright seat, rear rack included.\n\nFits riders about 5\'6" to 5\'11". Pickup near the downtown library. Cash or app payment.',
},
{
id: '7802', title: 'Mid century lounge chair, fresh upholstery', price: 145, section: 'sale', sub: sub('furniture'), postType: 'owner',
cityId: 'alder-bay', hood: 'northside', postedAt: ago(95), updatedAt: ago(20), seller: 'Morgan',
photos: pics('7802', 'chairRoom', 'livingRoom'),
attrs: [{ label: 'condition', value: 'good' }, { label: 'make / manufacturer', value: 'unknown' }, { label: 'size / dimensions', value: '30 x 32 x 31 in' }, { label: 'color', value: 'walnut / mustard' }],
body: 'Solid wood lounge chair, reupholstered last year in a mustard wool blend. A few small marks on the arms, otherwise lovely and very comfortable for reading.\n\nI\'m on the second floor, you\'ll need to carry it down. No holds without a deposit.',
},
{
id: '7803', title: 'Sunny 1BR near the park, in-unit laundry', price: 1350, per: '/mo', section: 'housing', sub: sub('apts/housing'), postType: 'housing',
cityId: 'alder-bay', hood: 'midtown', postedAt: ago(140), seller: 'Dana',
photos: pics('7803', 'apartment', 'balcony', 'livingRoom'),
attrs: [{ label: 'bedrooms', value: '1BR / 1Ba' }, { label: 'size', value: '640 ft²' }, { label: 'available', value: 'nov 15' }, { label: 'laundry', value: 'w/d in unit' }, { label: 'parking', value: 'street parking' }, { label: 'pets', value: 'cats are OK - purrr' }],
body: 'Bright corner one bedroom on the third floor with a small balcony facing the park. Hardwood floors, updated kitchen, washer and dryer in the unit.\n\nOne year lease, first month and deposit to move in. Water and trash included. Showings this weekend, message to pick a time.',
},
{
id: '7804', title: '35mm film camera with two lenses', price: 310, section: 'sale', sub: sub('photo+video'), postType: 'owner',
cityId: 'alder-bay', hood: 'west end', postedAt: ago(60 * 20), seller: 'Jamie',
photos: pics('7804', 'studio'),
attrs: [{ label: 'condition', value: 'like new' }, { label: 'make / manufacturer', value: 'Orrin Optics' }, { label: 'model name / number', value: 'OM-35 SLR' }],
body: 'Well cared for 35mm SLR. Light meter works, shutter speeds sound right. Includes a 50mm f/1.8, a 28mm wide lens, strap, and a padded case.\n\nHappy to meet at a camera shop so you can test it.',
},
{
id: '7805', title: 'Writing desk with two drawers', price: 85, section: 'sale', sub: sub('furniture'), postType: 'owner',
cityId: 'alder-bay', hood: 'east village', postedAt: ago(60 * 26), seller: 'Riley',
photos: pics('7805', 'desk', 'studio'),
attrs: [{ label: 'condition', value: 'good' }, { label: 'size / dimensions', value: '42 x 22 x 30 in' }, { label: 'material', value: 'solid pine' }],
body: 'Compact desk that fits a small bedroom office. Drawers slide smoothly. Light scratches on the top that you could sand out.',
},
{
id: '7806', title: 'Part time café team member, mornings', price: null, section: 'jobs', sub: sub('food/bev/hosp'), postType: 'job',
cityId: 'alder-bay', hood: 'downtown', postedAt: ago(60 * 30), seller: 'Little Corner Café',
photos: pics('7806', 'cafe'),
attrs: [{ label: 'compensation', value: '$18/hr plus tips' }, { label: 'employment type', value: 'part-time' }, { label: 'job title', value: 'barista / counter' }],
body: 'Neighborhood café looking for a friendly teammate for weekday mornings, 6:30 to 11:30. Experience with espresso is a plus but we will train the right person.\n\nReply with a few lines about yourself and your availability.',
},
{
id: '7807', title: 'Large monstera with ceramic pot', price: 45, section: 'sale', sub: sub('farm+garden'), postType: 'owner',
cityId: 'alder-bay', hood: 'northside', postedAt: ago(60 * 44), seller: 'Taylor',
photos: pics('7807', 'balcony'),
attrs: [{ label: 'condition', value: 'excellent' }, { label: 'size / dimensions', value: 'about 4 ft tall' }],
body: 'Healthy monstera with lots of new growth, moving and can\'t take it. Comes in the cream ceramic pot. Bring a car with room.',
},
{
id: '7808', title: 'Private room in friendly shared house', price: 790, per: '/mo', section: 'housing', sub: sub('rooms/shared'), postType: 'housing',
cityId: 'alder-bay', hood: 'riverside', postedAt: ago(60 * 50), seller: 'Casey',
photos: pics('7808', 'livingRoom', 'apartment'),
attrs: [{ label: 'bedrooms', value: '1 room / shared bath' }, { label: 'available', value: 'dec 1' }, { label: 'laundry', value: 'w/d in bldg' }, { label: 'housemates', value: '3' }],
body: 'Furnished private room in a bright four bedroom house near the river trail. Utilities and internet included. We cook together sometimes and keep the shared spaces tidy.\n\nLooking for someone respectful who works or studies nearby.',
},
{
id: '7809', title: 'Bike tune ups and flat repair, mobile', price: 35, section: 'services', sub: sub('cycle'), postType: 'service',
cityId: 'alder-bay', hood: 'midtown', postedAt: ago(60 * 70), seller: 'Sam\'s Spokes',
photos: pics('7809', 'bicycle'),
attrs: [{ label: 'service type', value: 'cycle' }, { label: 'rate', value: 'tune up from $35' }],
body: 'I come to you. Basic tune up (brakes, gears, chain, tire pressure) from $35. Flat repair $15 plus tube. Evenings and weekends.',
},
{
id: '7810', title: 'Weekend neighborhood book swap', price: null, section: 'community', sub: sub('events'), postType: 'event',
cityId: 'alder-bay', hood: 'riverside', postedAt: ago(60 * 75), seller: 'Riverside Reading Circle',
photos: pics('7810', 'chairRoom'),
attrs: [{ label: 'event date', value: 'saturday, 10am to noon' }, { label: 'cost', value: 'free' }],
body: 'Bring a book, take a book, meet your neighbors. Coffee and cookies at the community table next to the boathouse. Kids\' books especially welcome.',
},
{
id: '7811', title: 'Portable bluetooth speaker', price: 38, section: 'sale', sub: sub('electronics'), postType: 'owner',
cityId: 'alder-bay', hood: 'downtown', postedAt: ago(60 * 98), seller: 'Chris',
photos: [],
attrs: [{ label: 'condition', value: 'good' }, { label: 'make / manufacturer', value: 'Tidewave' }, { label: 'model name / number', value: 'Pulse Mini' }],
body: 'Compact speaker, about 10 hours of battery. Includes charging cable. Small scuff on the bottom.',
},
{
id: '7812', title: 'Patient math tutoring, grades 6-12', price: 30, per: '/hr', section: 'services', sub: sub('lessons'), postType: 'service',
cityId: 'alder-bay', hood: 'university hill', postedAt: ago(60 * 100), seller: 'Pat',
photos: [],
attrs: [{ label: 'service type', value: 'lessons & tutoring' }, { label: 'rate', value: '$30/hr' }],
body: 'Former teacher offering patient, encouraging tutoring for middle and high school math through precalculus. In person at the library or online.',
},
{
id: '7813', title: 'Free: moving boxes and packing paper', price: 0, section: 'sale', sub: sub('free stuff'), postType: 'owner',
cityId: 'alder-bay', hood: 'harbor district', postedAt: ago(12), seller: 'Jordan',
photos: [],
attrs: [{ label: 'condition', value: 'good' }],
body: 'About 30 boxes in mixed sizes plus a big bag of packing paper. On the porch, take what you need. I\'ll delete the post when they\'re gone.',
},
{
id: '7814', title: 'Studio sublet, january to march', price: 1050, per: '/mo', section: 'housing', sub: sub('sublets/temporary'), postType: 'housing',
cityId: 'alder-bay', hood: 'west end', postedAt: ago(60 * 5), seller: 'Noa',
photos: pics('7814', 'studio', 'desk'),
attrs: [{ label: 'bedrooms', value: 'studio / 1Ba' }, { label: 'size', value: '420 ft²' }, { label: 'available', value: 'jan 2' }, { label: 'furnished', value: 'yes' }],
body: 'Fully furnished studio while I\'m away for work. Fast internet, a real desk, and a quiet street. Utilities included. Short interview over video.',
},
{
id: '7815', title: 'Graphic designer for a menu refresh', price: null, section: 'gigs', sub: sub('creative'), postType: 'gig',
cityId: 'alder-bay', hood: 'east village', postedAt: ago(60 * 7), seller: 'Harbor Noodle Co.',
photos: [],
attrs: [{ label: 'compensation', value: '$400 flat' }, { label: 'gig type', value: 'paid' }],
body: 'Small restaurant needs a cleaner, more readable menu (two pages, print and web). Please include a link to past work. Two week timeline.',
},
{
id: '7816', title: 'Help moving a couch up two flights', price: null, section: 'gigs', sub: sub('labor'), postType: 'gig',
cityId: 'alder-bay', hood: 'midtown', postedAt: ago(60 * 3), seller: 'Elliot',
photos: [],
attrs: [{ label: 'compensation', value: '$60 for about an hour' }, { label: 'gig type', value: 'paid' }],
body: 'Need two strong people Sunday morning to bring a couch up to a third floor walkup. Should take under an hour.',
},
{
id: '7817', title: 'Found: grey cat with a blue collar', price: null, section: 'community', sub: sub('lost+found'), postType: 'community',
cityId: 'alder-bay', hood: 'northside', postedAt: ago(60 * 9), seller: 'Neighbor on Fir St',
photos: [],
attrs: [],
body: 'Friendly grey cat with a blue collar (no tag) hanging around Fir and 9th since Tuesday. Describe a distinguishing mark and I\'ll send a photo.',
},
{
id: '7818', title: 'Front desk coordinator, dental office', price: null, section: 'jobs', sub: sub('admin/office'), postType: 'job',
cityId: 'alder-bay', hood: 'harbor district', postedAt: ago(60 * 52), seller: 'Harborside Dental',
photos: [],
attrs: [{ label: 'compensation', value: '$22 to $25/hr' }, { label: 'employment type', value: 'full-time' }, { label: 'benefits', value: 'health, dental, PTO' }],
body: 'Busy family practice hiring a friendly, organized front desk coordinator. Scheduling, check-in, and phones. Monday to Thursday.',
},
{
id: '7819', title: 'Upright piano, you move', price: 0, section: 'sale', sub: sub('musical instruments'), postType: 'owner',
cityId: 'alder-bay', hood: 'university hill', postedAt: ago(60 * 120), seller: 'Robin',
photos: [],
attrs: [{ label: 'condition', value: 'fair' }, { label: 'make / manufacturer', value: 'Hallett & Sons' }],
body: 'Free upright piano, needs tuning. Ground floor, two steps to the driveway. You must bring movers.',
},
{
id: '7820', title: 'Mesh office chair, adjustable arms', price: 60, section: 'sale', sub: sub('furniture'), postType: 'dealer',
cityId: 'alder-bay', hood: 'downtown', postedAt: ago(60 * 140), seller: 'Second Shift Office Supply',
photos: pics('7820', 'desk'),
attrs: [{ label: 'condition', value: 'excellent' }, { label: 'make / manufacturer', value: 'Fulcrum' }, { label: 'model name / number', value: 'Task 200' }, { label: 'quantity', value: '12 available' }],
body: 'Refurbished office chairs from a downtown office move. Adjustable height, arms, and tilt. Showroom open weekdays 10 to 5.',
},
// nearby areas
{
id: '7821', title: 'Two bedroom townhouse with garage', price: 1780, per: '/mo', section: 'housing', sub: sub('apts/housing'), postType: 'housing',
cityId: 'millbrook', hood: 'old town', postedAt: ago(60 * 4), seller: 'Brookside Property Co.',
photos: pics('7821', 'livingRoom', 'balcony'),
attrs: [{ label: 'bedrooms', value: '2BR / 1.5Ba' }, { label: 'size', value: '1,050 ft²' }, { label: 'available', value: 'now' }, { label: 'parking', value: 'attached garage' }, { label: 'pets', value: 'dogs are OK - wooof' }],
body: 'End unit townhouse with an attached garage and small yard. Dishwasher, gas range, washer/dryer hookups. Walk to the old town shops.',
},
{
id: '7822', title: 'Kids balance bike', price: 25, section: 'sale', sub: sub('baby+kid'), postType: 'owner',
cityId: 'millbrook', hood: 'brookside', postedAt: ago(60 * 15), seller: 'Lee',
photos: pics('7822', 'bicycle'),
attrs: [{ label: 'condition', value: 'good' }, { label: 'size / dimensions', value: '12 in wheels' }],
body: 'Outgrown balance bike. Adjustable seat. Some stickers on the frame.',
},
{
id: '7823', title: 'Cozy cabin weekend rental by the lake', price: 140, per: '/night', section: 'housing', sub: sub('vacation rentals'), postType: 'housing',
cityId: 'cedar-point', hood: 'lakeview', postedAt: ago(60 * 33), seller: 'Marisol',
photos: pics('7823', 'balcony', 'chairRoom'),
attrs: [{ label: 'bedrooms', value: '2BR / 1Ba' }, { label: 'sleeps', value: '4' }],
body: 'Quiet cabin with a deck facing the water. Two night minimum. Kayaks available. No parties.',
},
{
id: '7824', title: 'Line cook, evenings', price: null, section: 'jobs', sub: sub('food/bev/hosp'), postType: 'job',
cityId: 'cedar-point', hood: 'the point', postedAt: ago(60 * 61), seller: 'Point Tavern',
photos: pics('7824', 'cafe'),
attrs: [{ label: 'compensation', value: '$21/hr + shared tips' }, { label: 'employment type', value: 'full-time' }],
body: 'Scratch kitchen hiring an evening line cook. One year of experience preferred. Family meal every shift.',
},
{
id: '7825', title: 'Handyman: shelves, doors, small repairs', price: 55, per: '/hr', section: 'services', sub: sub('skilled trade'), postType: 'service',
cityId: 'fernwood', hood: 'station square', postedAt: ago(60 * 80), seller: 'Fernwood Fixit',
photos: [],
attrs: [{ label: 'service type', value: 'skilled trade' }, { label: 'rate', value: '$55/hr, 1 hr minimum' }, { label: 'license', value: 'insured' }],
body: 'Hanging shelves and TVs, sticky doors, drywall patches, furniture assembly. Reliable and tidy. Free estimates.',
},
{
id: '7826', title: 'Community garden plots open for spring', price: null, section: 'community', sub: sub('groups'), postType: 'community',
cityId: 'millbrook', hood: 'mill district', postedAt: ago(60 * 90), seller: 'Mill District Gardeners',
photos: pics('7826', 'balcony'),
attrs: [{ label: 'cost', value: '$20/season' }],
body: 'We have six 10x10 plots open at the mill district garden. Water and tools included. Join our info session next Thursday.',
},
{
id: '7827', title: 'Vintage record player, works great', price: 120, section: 'sale', sub: sub('electronics'), postType: 'owner',
cityId: 'granite-falls', hood: 'falls center', postedAt: ago(60 * 110), seller: 'Quinn',
photos: [],
attrs: [{ label: 'condition', value: 'good' }, { label: 'make / manufacturer', value: 'Soundcraft Home' }],
body: 'Belt drive turntable with built-in speakers. New belt and needle. Plays 33 and 45.',
},
// farther away
{
id: '7828', title: 'Surfboard, 8 ft funboard', price: 260, section: 'sale', sub: sub('sporting'), postType: 'owner',
cityId: 'solana-vista', hood: 'seawall', postedAt: ago(60 * 6), seller: 'Kai',
photos: [],
attrs: [{ label: 'condition', value: 'good' }, { label: 'size / dimensions', value: "8'0\"" }],
body: 'Great beginner board, a couple of repaired dings. Fins and leash included.',
},
{
id: '7829', title: 'Loft apartment in the warehouse district', price: 1600, per: '/mo', section: 'housing', sub: sub('apts/housing'), postType: 'housing',
cityId: 'lakeport', hood: 'warehouse district', postedAt: ago(60 * 18), seller: 'Lakeport Lofts',
photos: pics('7829', 'studio', 'apartment'),
attrs: [{ label: 'bedrooms', value: '1BR / 1Ba' }, { label: 'size', value: '900 ft²' }, { label: 'available', value: 'dec 1' }],
body: 'Open loft with 14 ft ceilings and big windows. Brick walls, concrete floors, rooftop deck.',
},
// your own posts
{
id: '7830', title: 'Oak bookshelf, five shelves', price: 70, section: 'sale', sub: sub('furniture'), postType: 'owner',
cityId: 'alder-bay', hood: 'east village', postedAt: ago(60 * 28), seller: 'You', mine: true,
photos: pics('7830', 'livingRoom'),
attrs: [{ label: 'condition', value: 'good' }, { label: 'size / dimensions', value: '36 x 12 x 72 in' }],
body: 'Sturdy oak bookshelf. Comes apart into two pieces for moving. Smoke free home.',
},
{
id: '7831', title: 'Sit-on-top kayak with paddle', price: 300, section: 'sale', sub: sub('sporting'), postType: 'owner',
cityId: 'alder-bay', hood: 'east village', postedAt: ago(60 * 46), seller: 'You', mine: true,
photos: [],
attrs: [{ label: 'condition', value: 'excellent' }, { label: 'size / dimensions', value: '10 ft' }],
body: 'Stable recreational kayak, used a handful of times on the bay. Paddle and dry bag included.',
},
];
// ---------------------------------------------------------------- messages
export type Message = { id: string; from: 'me' | 'them'; text: string; at: number };
export type Thread = {
id: string;
listingId: string;
/** The other person in the conversation. */
name: string;
role: 'buying' | 'selling';
unread: number;
messages: Message[];
};
const msgs = (id: string, items: [Message['from'], string, number][]): Message[] =>
items.map(([from, text, minutesAgo], index) => ({ id: `${id}-${index}`, from, text, at: ago(minutesAgo) }));
export const THREADS: Thread[] = [
{
id: 't1', listingId: '7802', name: 'Morgan', role: 'buying', unread: 1,
messages: msgs('t1', [
['me', 'Hi! Is the lounge chair still available?', 80],
['them', 'Yes it is. Are you able to pick up this week?', 62],
['me', 'I could come Saturday morning. Would you take $125?', 55],
['them', 'I can do $135 if you can get it down the stairs yourself. Saturday at 10 works.', 18],
]),
},
{
id: 't2', listingId: '7830', name: 'Priya', role: 'selling', unread: 2,
messages: msgs('t2', [
['them', 'Hello, how deep are the shelves? Trying to fit oversized art books.', 300],
['me', 'Hi Priya, they are 11.5 inches deep inside.', 260],
['them', 'Perfect. Could I see it tomorrow after 5?', 40],
['them', 'Also, does it come apart? I have a hatchback.', 39],
]),
},
{
id: 't3', listingId: '7803', name: 'Dana', role: 'buying', unread: 0,
messages: msgs('t3', [
['me', 'Hi Dana, I\'m interested in the 1BR. Are you showing it this weekend?', 60 * 26],
['them', 'Hi! Showings are Saturday 1 to 3 and Sunday 11 to 1. Which works?', 60 * 24],
['me', 'Sunday at 11:30 please. Is a cat OK?', 60 * 23],
['them', 'Cats are fine with a $200 pet deposit. See you Sunday, unit 3C, buzz the front door.', 60 * 22],
['me', 'Great, see you then.', 60 * 22 - 5],
]),
},
{
id: 't4', listingId: '7831', name: 'Wes', role: 'selling', unread: 0,
messages: msgs('t4', [
['them', 'would u take 150 for the kayak', 60 * 40],
['me', 'Thanks for the offer, but I\'m firm at $300. It includes the paddle and dry bag.', 60 * 39],
['them', 'ok 200 cash today?', 60 * 39 - 10],
['me', 'I\'ll pass for now, but I\'ll let you know if it doesn\'t sell.', 60 * 38],
]),
},
{
id: 't5', listingId: '7806', name: 'Little Corner Café', role: 'buying', unread: 0,
messages: msgs('t5', [
['me', 'Hi, I have two years of barista experience and I\'m free weekday mornings. Happy to send a resume.', 60 * 28],
['them', 'Thanks for reaching out! Could you come by Thursday at 2 for a quick chat and a trial shot?', 60 * 27],
['me', 'Thursday at 2 works. See you then!', 60 * 27 - 15],
]),
},
{
id: 't6', listingId: '7809', name: "Sam's Spokes", role: 'buying', unread: 0,
messages: msgs('t6', [
['me', 'Do you have time for a tune up on Wednesday evening? Downtown.', 60 * 70],
['them', 'Wednesday after 6 works. Send me the cross streets and I\'ll text when I\'m close.', 60 * 69],
]),
},
];
// ---------------------------------------------------------------- formatting
export const money = (value: number) => (value === 0 ? 'free' : '$' + value.toLocaleString('en-US'));
export const priceText = (listing: Pick<Listing, 'price' | 'per'>) =>
listing.price === null ? '' : money(listing.price) + (listing.price > 0 && listing.per ? listing.per : '');
export function ageText(at: number, now = Date.now()) {
const minutes = Math.max(0, Math.round((now - at) / MIN));
if (minutes < 1) return 'just now';
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.round(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.round(hours / 24);
return days === 1 ? '1 day ago' : `${days} days ago`;
}
const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
export function dateText(at: number) {
const date = new Date(at);
const hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${MONTHS[date.getMonth()]} ${date.getDate()}, ${hours % 12 || 12}:${minutes}${hours < 12 ? 'am' : 'pm'}`;
}
export function clockText(at: number, now = Date.now()) {
const date = new Date(at);
const sameDay = new Date(now).toDateString() === date.toDateString();
if (sameDay) {
const hours = date.getHours();
return `${hours % 12 || 12}:${String(date.getMinutes()).padStart(2, '0')} ${hours < 12 ? 'am' : 'pm'}`;
}
return `${MONTHS[date.getMonth()]} ${date.getDate()}`;
}
index.ts
import { registerRootComponent } from 'expo';
import App from './App';
registerRootComponent(App);
screens/Categories.tsx
import type { ReactNode } from 'react';
import { Block, Icon, Text } from '@plocks/ui';
import { C } from '../theme';
import { SECTIONS, sectionById, type SectionId } from '../data';
import { useStore } from '../store';
import { Screen, SectionLabel } from '../components';
import { CityButton, useCounts } from './Home';
function Row({
label,
hint,
count,
icon,
strong,
onPress,
}: {
label: string;
hint?: string;
count: number;
icon?: ReactNode;
strong?: boolean;
onPress: () => void;
}) {
return (
<Block
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={`${label}, ${count} posts`}
direction="row"
align="center"
gap={12}
py={hint ? 11 : 12}
px={4}
borderBottomWidth={1}
borderBottomColor={C.line}
pressedStyle={{ opacity: 0.6 }}
>
{icon}
<Block flex={1} miw={0} gap={1}>
<Text c={count || strong ? C.link : C.visited} fw={strong ? 'bold' : 'semibold'} size={15}>
{label}
</Text>
{!!hint && (
<Text c={C.muted} size={12} numberOfLines={1}>
{hint}
</Text>
)}
</Block>
<Text c={count ? C.muted : C.faint} size={12}>
{count}
</Text>
<Icon name="chevron-right" color={C.faint} size={16} />
</Block>
);
}
export function Categories({ section }: { section?: SectionId }) {
const store = useStore();
const counts = useCounts();
if (section) {
const current = sectionById(section);
return (
<Screen back title={current.label} subtitle={`${store.city.name} · ${counts[section] ?? 0} posts`} right={<CityButton />} maw={680}>
<Row
strong
label={`all ${current.label}`}
count={counts[section] ?? 0}
onPress={() => store.push({ name: 'results', filter: { query: '', section } })}
/>
<SectionLabel>subcategories</SectionLabel>
<Block gap={0} borderTopWidth={1} borderTopColor={C.line}>
{current.subs.map((item) => (
<Row
key={item.id}
label={item.label}
count={counts[`${section}/${item.id}`] ?? 0}
onPress={() => store.push({ name: 'results', filter: { query: '', section, sub: item.id } })}
/>
))}
</Block>
</Screen>
);
}
return (
<Screen back title="categories" subtitle={store.city.name} right={<CityButton />} maw={680}>
<Block gap={0} borderTopWidth={1} borderTopColor={C.line}>
{SECTIONS.map((item) => (
<Row
key={item.id}
label={item.label}
hint={item.blurb}
count={counts[item.id] ?? 0}
icon={
<Block gap={0} w={36} h={36} radius={18} bg={C.tint} align="center" justify="center">
<Icon name={item.icon} color={C.purple} size={18} />
</Block>
}
onPress={() => store.push({ name: 'categories', section: item.id })}
/>
))}
</Block>
</Screen>
);
}
screens/Cities.tsx
import { useMemo, useState } from 'react';
import { Block, Icon, Input, Slider, Text } from '@plocks/ui';
import { C } from '../theme';
import { CITIES, REGIONS, distance, type City } from '../data';
import { useStore } from '../store';
import { Screen, SectionLabel } from '../components';
const RADII = [0, 5, 10, 25, 50, 100];
export function Cities() {
const store = useStore();
const [query, setQuery] = useState('');
const q = query.trim().toLowerCase();
const matches = (city: City) => !q || city.name.includes(q) || city.hoods.some((hood) => hood.includes(q));
const nearby = useMemo(
() =>
CITIES.filter((city) => city.id !== store.cityId)
.map((city) => ({ city, miles: distance(store.city, city) }))
.filter((item) => item.miles <= 120)
.sort((a, b) => a.miles - b.miles),
[store.city, store.cityId],
);
const counts = useMemo(() => {
const result: Record<string, number> = {};
for (const item of store.listings) result[item.cityId] = (result[item.cityId] ?? 0) + 1;
return result;
}, [store.listings]);
const radiusIndex = Math.max(0, RADII.indexOf(store.radius));
const inRadius = nearby.filter((item) => item.miles <= store.radius);
const choose = (city: City) => {
store.setCityId(city.id);
store.back();
};
const cityRow = (city: City, miles?: number) => {
const current = city.id === store.cityId;
return (
<Block
key={city.id}
onPress={() => choose(city)}
accessibilityRole="button"
accessibilityLabel={`Choose ${city.name}`}
direction="row"
align="center"
gap={10}
py={10}
px={4}
borderBottomWidth={1}
borderBottomColor={C.line}
pressedStyle={{ opacity: 0.6 }}
>
<Block flex={1} miw={0} gap={1}>
<Text c={current ? C.ink : C.link} fw={current ? 'bold' : 'semibold'} size={15}>
{city.name}
</Text>
<Text c={C.muted} size={11} numberOfLines={1}>
{city.hoods.slice(0, 3).join(', ')}
{city.hoods.length > 3 ? '…' : ''}
</Text>
</Block>
{miles !== undefined && (
<Text c={C.muted} size={12}>
{miles} mi
</Text>
)}
<Text c={C.faint} size={11} miw={44} ta="right">
{counts[city.id] ?? 0} posts
</Text>
{current && <Icon name="check" color={C.purple} size={17} />}
</Block>
);
};
return (
<Screen back title="choose area" subtitle={`currently ${store.city.name}`} maw={680}>
<Input
variant="outline"
value={query}
onChangeText={setQuery}
placeholder="search cities and neighborhoods"
startSection={<Icon name="search" color={C.muted} size={17} />}
clearable
mb={0}
radius={6}
inputColor={C.ink}
accessibilityLabel="Search cities"
/>
{!q && (
<>
<SectionLabel>search radius</SectionLabel>
<Block gap={10} p={14} radius={6} bg={C.paler} borderWidth={1} borderColor={C.line}>
<Block gap={0} direction="row" align="center" justify="space-between">
<Text c={C.ink} fw="semibold" size={14}>
{store.radius === 0 ? `${store.city.name} only` : `within ${store.radius} miles of ${store.city.name}`}
</Text>
<Text c={C.muted} size={12}>
{inRadius.length ? `+${inRadius.length} area${inRadius.length === 1 ? '' : 's'}` : ''}
</Text>
</Block>
<Slider
accessibilityLabel="Search radius"
value={radiusIndex}
min={0}
max={RADII.length - 1}
step={1}
restrictToTicks
ticks={RADII.map((miles, index) => ({ value: index, label: miles === 0 ? 'city' : `${miles}` }))}
showTicks
valueLabel={(index) => (RADII[index] === 0 ? 'city only' : `${RADII[index]} mi`)}
color={C.purple}
onChange={(index) => store.setRadius(RADII[Math.round(index)] ?? 0)}
mb={14}
/>
{inRadius.length > 0 && (
<Text c={C.muted} size={12}>
includes {inRadius.map((item) => item.city.name).join(', ')}
</Text>
)}
</Block>
<SectionLabel>nearby areas</SectionLabel>
<Block gap={0} borderTopWidth={1} borderTopColor={C.line}>
{nearby.map((item) => cityRow(item.city, item.miles))}
</Block>
</>
)}
{REGIONS.map((region) => {
const list = CITIES.filter((city) => city.region === region.id && matches(city));
if (!list.length) return null;
return (
<Block key={region.id} gap={0}>
<SectionLabel>{region.label}</SectionLabel>
<Block gap={0} borderTopWidth={1} borderTopColor={C.line}>
{list.map((city) => cityRow(city, region.id === store.city.region ? distance(store.city, city) : undefined))}
</Block>
</Block>
);
})}
{q && !CITIES.some(matches) && (
<Text c={C.muted} ta="center" py={30}>
No areas match “{query}”.
</Text>
)}
</Screen>
);
}
screens/Home.tsx
import { useMemo, useState } from 'react';
import { Block, Button, Icon, Input, Text } from '@plocks/ui';
import { C } from '../theme';
import { SECTIONS, type Section } from '../data';
import { useStore } from '../store';
import { ListingRow, ListingTile, Screen, SectionLabel, useWide } from '../components';
/** Count of listings per "section/sub" key in the current area. */
export function useCounts() {
const store = useStore();
return useMemo(() => {
const counts: Record<string, number> = {};
for (const item of store.search({ query: '' })) {
counts[item.section] = (counts[item.section] ?? 0) + 1;
counts[`${item.section}/${item.sub}`] = (counts[`${item.section}/${item.sub}`] ?? 0) + 1;
}
return counts;
}, [store]);
}
export function CityButton() {
const store = useStore();
return (
<Block
onPress={() => store.push({ name: 'cities' })}
accessibilityRole="button"
accessibilityLabel={`Change area, currently ${store.city.name}`}
direction="row"
align="center"
gap={4}
px={10}
py={6}
radius={16}
bg={C.tint}
pressedStyle={{ opacity: 0.7 }}
>
<Icon name="map-pin" color={C.purple} size={15} />
<Text c={C.purple} fw="semibold" size={13} numberOfLines={1}>
{store.city.name}
{store.radius > 0 ? ` +${store.radius}mi` : ''}
</Text>
<Icon name="chevron-down" color={C.purple} size={14} />
</Block>
);
}
export function SearchBar({ initial = '', onSubmit }: { initial?: string; onSubmit: (query: string) => void }) {
const [query, setQuery] = useState(initial);
return (
<Block gap={8} direction="row" align="center">
<Input
variant="outline"
value={query}
onChangeText={setQuery}
onEnter={() => onSubmit(query)}
placeholder="search townlist"
returnKeyType="search"
startSection={<Icon name="search" color={C.muted} size={17} />}
clearable
mb={0}
flex={1}
radius={6}
inputColor={C.ink}
/>
<Button title="go" color={C.purple} onPress={() => onSubmit(query)} radius={6} />
</Block>
);
}
function SectionColumn({ section, counts }: { section: Section; counts: Record<string, number> }) {
const store = useStore();
return (
<Block gap={1}>
<Text
c={C.purple}
fw="bold"
size={15}
mb={4}
onPress={() => store.push({ name: 'results', filter: { query: '', section: section.id } })}
>
{section.label}
<Text c={C.faint} size={12} fw="normal">
{' '}
{counts[section.id] ?? 0}
</Text>
</Text>
{section.subs.map((item) => (
<Text
key={item.id}
c={counts[`${section.id}/${item.id}`] ? C.link : C.visited}
size={13}
lh={20}
onPress={() => store.push({ name: 'results', filter: { query: '', section: section.id, sub: item.id } })}
>
{item.label}
</Text>
))}
</Block>
);
}
export function Home() {
const store = useStore();
const wide = useWide();
const counts = useCounts();
const fresh = store.search({ query: '' }).slice(0, wide ? 6 : 8);
const open = (id: string) => store.push({ name: 'listing', id });
return (
<Screen
title={
wide ? (
`${store.city.name} classifieds`
) : (
<Text c={C.purple} fw="bold" size={22} lts={-0.5}>
townlist
</Text>
)
}
right={<CityButton />}
maw={1060}
>
<SearchBar onSubmit={(query) => store.push({ name: 'results', filter: { query } })} />
<Block gap={8} direction="row" mt={10} wrap>
<Button
size="sm"
variant="light"
color={C.purple}
title="post to classifieds"
startSection={<Icon name="plus" size={15} color={C.purple} />}
onPress={() => store.goTab('post', true)}
/>
<Button
size="sm"
variant="subtle"
color={C.purple}
title="all categories"
startSection={<Icon name="grid" size={15} color={C.purple} />}
onPress={() => store.push({ name: 'categories' })}
/>
</Block>
{wide ? (
<Block gap={28} direction="row" mt={20}>
<Block flex={1} gap={0}>
<SectionLabel mt={0}>categories in {store.city.name}</SectionLabel>
<Block gap={0} direction="row" wrap borderTopWidth={1} borderTopColor={C.line} pt={12}>
{SECTIONS.map((section) => (
<Block key={section.id} gap={0} w="33.33%" pr={14} pb={20}>
<SectionColumn section={section} counts={counts} />
</Block>
))}
</Block>
</Block>
<Block w={340} gap={0}>
<SectionLabel mt={0} right={<Text c={C.link} size={12} onPress={() => store.push({ name: 'results', filter: { query: '' } })}>see all</Text>}>
new today
</SectionLabel>
<Block gap={12} direction="row" wrap pt={12} borderTopWidth={1} borderTopColor={C.line}>
{fresh.map((item) => (
<ListingTile key={item.id} listing={item} w={164} onPress={() => open(item.id)} />
))}
</Block>
</Block>
</Block>
) : (
<>
<SectionLabel right={<Text c={C.link} size={12} onPress={() => store.push({ name: 'categories' })}>browse all</Text>}>
categories
</SectionLabel>
<Block gap={0} direction="row" wrap borderWidth={1} borderColor={C.line} radius={6} overflow="hidden">
{SECTIONS.map((section, index) => (
<Block
key={section.id}
w="50%"
gap={8}
direction="row"
align="center"
p={12}
bg={C.white}
borderRightWidth={index % 2 === 0 ? 1 : 0}
borderBottomWidth={index < SECTIONS.length - 2 ? 1 : 0}
borderColor={C.line}
borderRightColor={C.line}
borderBottomColor={C.line}
onPress={() => store.push({ name: 'categories', section: section.id })}
accessibilityRole="button"
accessibilityLabel={`Browse ${section.label}`}
pressedStyle={{ opacity: 0.6 }}
>
<Block gap={0} w={34} h={34} radius={17} bg={C.tint} align="center" justify="center">
<Icon name={section.icon} color={C.purple} size={17} />
</Block>
<Block flex={1} miw={0} gap={0}>
<Text c={C.ink} fw="semibold" size={14}>
{section.label}
</Text>
<Text c={C.muted} size={11} numberOfLines={1}>
{counts[section.id] ?? 0} posts
</Text>
</Block>
</Block>
))}
</Block>
<SectionLabel right={<Text c={C.link} size={12} onPress={() => store.push({ name: 'results', filter: { query: '' } })}>see all</Text>}>
newest in {store.city.name}
</SectionLabel>
<Block gap={0} borderTopWidth={1} borderTopColor={C.line}>
{fresh.map((item) => (
<ListingRow key={item.id} listing={item} onPress={() => open(item.id)} />
))}
</Block>
</>
)}
</Screen>
);
}
screens/ListingView.tsx
import { useState, type ReactNode } from 'react';
import * as Clipboard from 'expo-clipboard';
import {
Block,
Button,
Chip,
Dialog,
Icon,
IconButton,
Image,
Lightbox,
Menu,
MenuDivider,
MenuDropdown,
MenuItem,
TextArea,
Text,
useToast,
} from '@plocks/ui';
import type { LightboxItem } from '@plocks/ui';
import { C } from '../theme';
import {
ageText,
cityById,
dateText,
photoSource,
postTypeById,
priceText,
sectionById,
subLabel,
type Listing,
} from '../data';
import { useStore } from '../store';
import { EmptyNote, MapBlock, Screen, useWide } from '../components';
const QUICK = ['Hi, is this still available?', 'When could I come see it?', 'Would you consider a lower price?'];
const FLAGS = ['prohibited', 'spam / overpost', 'miscategorized', 'scam or fraud'];
function Gallery({ listing, h }: { listing: Listing; h: number }) {
const [index, setIndex] = useState(0);
const [lightbox, setLightbox] = useState<number | null>(null);
const photos = listing.photos;
if (!photos.length) {
return (
<Block gap={6} h={Math.round(h * 0.55)} radius={6} bg={C.pale} align="center" justify="center" borderWidth={1} borderColor={C.line}>
<Icon name="image-off" color={C.faint} size={30} />
<Text c={C.faint} size={12}>
no images
</Text>
</Block>
);
}
const items: LightboxItem[] = photos.map((photo, i) => ({
id: photo.id,
uri: photoSource(photo),
title: `${listing.title} (${i + 1} of ${photos.length})`,
}));
const current = Math.min(index, photos.length - 1);
return (
<Block gap={8}>
<Block gap={0} position="relative" radius={6} overflow="hidden" bg={C.ink}>
<Block gap={0} onPress={() => setLightbox(current)} accessibilityRole="button" accessibilityLabel="Open full screen photos">
<Image src={photoSource(photos[current])} w="100%" h={h} resizeMode="cover" alt={`${listing.title}, photo ${current + 1}`} />
</Block>
{photos.length > 1 && (
<>
<Block gap={0} position="absolute" left={8} top={h / 2 - 20}>
<IconButton icon="chevron-left" variant="filled" color="rgba(0,0,0,0.5)" iconColor={C.white} accessibilityLabel="Previous photo" onPress={() => setIndex((current - 1 + photos.length) % photos.length)} />
</Block>
<Block gap={0} position="absolute" right={8} top={h / 2 - 20}>
<IconButton icon="chevron-right" variant="filled" color="rgba(0,0,0,0.5)" iconColor={C.white} accessibilityLabel="Next photo" onPress={() => setIndex((current + 1) % photos.length)} />
</Block>
</>
)}
<Block gap={0} position="absolute" right={8} bottom={8} px={8} py={3} radius={10} bg="rgba(0,0,0,0.6)">
<Text c={C.white} size={11} fw="semibold">
{current + 1} / {photos.length}
</Text>
</Block>
</Block>
{photos.length > 1 && (
<Block gap={6} direction="row" wrap>
{photos.map((photo, i) => (
<Block
key={photo.id}
gap={0}
onPress={() => setIndex(i)}
accessibilityRole="button"
accessibilityLabel={`Show photo ${i + 1}`}
radius={4}
overflow="hidden"
borderWidth={2}
borderColor={i === current ? C.purple : 'transparent'}
>
<Image src={photoSource(photo)} w={62} h={50} resizeMode="cover" alt="" opacity={i === current ? 1 : 0.75} />
</Block>
))}
</Block>
)}
<Lightbox
opened={lightbox !== null}
images={items}
initialIndex={lightbox ?? 0}
onClose={() => setLightbox(null)}
showDownloadButton={false}
accessibilityLabel={`${listing.title} photos`}
/>
</Block>
);
}
function Action({ icon, label, active, onPress }: { icon: ReactNode; label: string; active?: boolean; onPress?: () => void }) {
return (
<Block
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={label}
gap={3}
align="center"
px={8}
py={6}
miw={54}
radius={6}
bg={active ? C.tint : undefined}
pressedStyle={{ opacity: 0.6 }}
>
{icon}
<Text c={active ? C.purple : C.body} size={11} fw="semibold">
{label}
</Text>
</Block>
);
}
function Attributes({ listing }: { listing: Listing }) {
const type = postTypeById(listing.postType);
return (
<Block gap={0} radius={6} borderWidth={1} borderColor={C.line} bg={C.paler}>
<Block gap={2} p={12} borderBottomWidth={1} borderBottomColor={C.line}>
<Text c={C.muted} size={11}>
{type.label}
</Text>
<Text c={C.ink} fw="bold" size={14}>
{subLabel(listing.section, listing.sub)}
</Text>
</Block>
{listing.attrs.length > 0 && (
<Block gap={6} p={12}>
{listing.attrs.map((attr) => (
<Text key={attr.label} c={C.muted} size={13} lh={18}>
{attr.label}:{' '}
<Text c={C.ink} fw="bold" size={13}>
{attr.value}
</Text>
</Text>
))}
</Block>
)}
</Block>
);
}
export function ListingBody({ listing, preview, onReply }: { listing: Listing; preview?: boolean; onReply?: () => void }) {
const store = useStore();
const toast = useToast();
const wide = useWide();
const favorite = store.favorites.includes(listing.id);
const hidden = store.hidden.includes(listing.id);
const flagged = store.flagged.includes(listing.id);
const city = cityById(listing.cityId);
const price = priceText(listing);
const section = sectionById(listing.section);
const share = async () => {
const url = `https://townlist.example/${city.id}/${listing.section}/${listing.id}`;
try {
await Clipboard.setStringAsync(url);
toast.show({ title: 'Link copied', message: url, autoHide: 2400 });
} catch {
toast.show({ title: 'Share link', message: url, autoHide: 2400 });
}
};
const actions = (
<Block gap={4} direction="row" align="center" wrap>
{!listing.mine && !preview && (
<Button title="reply" color={C.purple} startSection={<Icon name="message" color={C.white} size={16} />} onPress={onReply} radius={6} mr={6} />
)}
<Action
label={favorite ? 'favorited' : 'favorite'}
active={favorite}
icon={<Icon name="star" variant={favorite ? 'filled' : 'outlined'} color={favorite ? '#D49A00' : C.body} size={18} />}
onPress={preview ? undefined : () => store.toggleFavorite(listing.id)}
/>
<Action
label={hidden ? 'unhide' : 'hide'}
active={hidden}
icon={hidden ? <Icon name="eye" color={C.purple} size={18} /> : <Icon name="eye-off" color={C.body} size={18} />}
onPress={
preview
? undefined
: () => {
store.toggleHidden(listing.id);
toast.show({ title: hidden ? 'Post unhidden' : 'Post hidden', message: hidden ? undefined : 'It won’t show in your results.', autoHide: 2000 });
}
}
/>
{preview ? (
<Action label="flag" icon={<Icon name="flag" color={C.body} size={18} />} />
) : (
<Menu position="bottom-end">
<Action label={flagged ? 'flagged' : 'flag'} active={flagged} icon={<Icon name="flag" variant={flagged ? 'filled' : 'outlined'} color={flagged ? C.red : C.body} size={18} />} />
<MenuDropdown>
{FLAGS.map((reason) => (
<MenuItem
key={reason}
onPress={() => {
store.flag(listing.id);
toast.show({ title: 'Thanks for flagging', message: `Reported as ${reason}.`, autoHide: 2200 });
}}
>
{reason}
</MenuItem>
))}
<MenuDivider />
<MenuItem disabled>best of townlist (soon)</MenuItem>
</MenuDropdown>
</Menu>
)}
<Action label="share" icon={<Icon name="share" color={C.body} size={18} />} onPress={preview ? undefined : share} />
</Block>
);
const heading = (
<Block gap={6}>
<Text c={C.ink} fw="bold" size={wide ? 24 : 20} lh={wide ? 30 : 26}>
{listing.title}
{price ? (
<Text c={listing.price === 0 ? C.green : C.ink} fw="bold" size={wide ? 24 : 20}>
{' '}
– {price}
</Text>
) : null}
<Text c={C.muted} fw="normal" size={wide ? 18 : 16}>
{' '}
({listing.hood})
</Text>
</Text>
<Block gap={6} direction="row" align="center" wrap>
<Icon name="clock" color={C.muted} size={13} />
<Text c={C.muted} size={12}>
posted {ageText(listing.postedAt)}
{listing.updatedAt ? ` · updated ${ageText(listing.updatedAt)}` : ''}
</Text>
<Text c={C.faint} size={12}>
·
</Text>
<Icon name="map-pin" color={C.muted} size={13} />
<Text c={C.muted} size={12}>
{listing.hood}, {city.name}
</Text>
</Block>
</Block>
);
const body = (
<Block gap={12}>
{listing.body.split('\n\n').map((paragraph, index) => (
<Text key={index} c={C.body} size={15} lh={23}>
{paragraph}
</Text>
))}
<Block gap={4} mt={4} p={10} radius={4} bg={C.pale}>
<Text c={C.muted} size={12}>
• do NOT contact me with unsolicited services or offers
</Text>
{listing.section === 'sale' && (
<Text c={C.muted} size={12}>
• meet in a public place and inspect before paying
</Text>
)}
</Block>
</Block>
);
const meta = (
<Block gap={3} pt={10} borderTopWidth={1} borderTopColor={C.line}>
<Text c={C.faint} size={11}>
post id: {listing.id}
</Text>
<Text c={C.faint} size={11}>
posted: {dateText(listing.postedAt)}
</Text>
{listing.updatedAt && (
<Text c={C.faint} size={11}>
updated: {dateText(listing.updatedAt)}
</Text>
)}
<Text c={C.faint} size={11}>
posted by: {listing.seller}
</Text>
</Block>
);
return (
<Block gap={14}>
{hidden && !preview && (
<Block gap={8} direction="row" align="center" p={10} radius={6} bg={C.amberPale}>
<Icon name="eye-off" color={C.amber} size={16} />
<Text c={C.amber} size={13} flex={1}>
You hid this post. It won’t appear in results.
</Text>
<Text c={C.purple} size={13} fw="semibold" onPress={() => store.toggleHidden(listing.id)}>
unhide
</Text>
</Block>
)}
<Block gap={6} direction="row" align="center" wrap>
<Text c={C.link} size={12}>
{city.name}
</Text>
<Text c={C.faint} size={12}>›</Text>
<Text c={C.link} size={12}>
{section.label}
</Text>
<Text c={C.faint} size={12}>›</Text>
<Text c={C.link} size={12}>
{subLabel(listing.section, listing.sub)}
</Text>
<Text c={C.faint} size={12}>
- {postTypeById(listing.postType).label.replace(/^for sale /, '')}
</Text>
</Block>
{heading}
{actions}
{wide ? (
<Block gap={24} direction="row" align="flex-start">
<Block flex={1} miw={0} gap={18}>
<Gallery listing={listing} h={400} />
{body}
</Block>
<Block w={290} gap={14}>
<Attributes listing={listing} />
<MapBlock hood={listing.hood} cityId={listing.cityId} h={190} />
{meta}
</Block>
</Block>
) : (
<>
<Gallery listing={listing} h={260} />
<Attributes listing={listing} />
{body}
<MapBlock hood={listing.hood} cityId={listing.cityId} />
{meta}
</>
)}
</Block>
);
}
export function ListingView({ id }: { id: string }) {
const store = useStore();
const toast = useToast();
const listing = store.listingById(id);
const [replying, setReplying] = useState(false);
const [text, setText] = useState('');
const [showEmail, setShowEmail] = useState(false);
if (!listing) {
return (
<Screen back title="post">
<EmptyNote icon="search" title="This posting has been deleted by its author." />
</Screen>
);
}
const send = () => {
if (!text.trim()) return;
const threadId = store.reply(listing, text.trim());
setText('');
setReplying(false);
toast.show({ title: 'Message sent', message: `${listing.seller} will reply in messages.`, autoHide: 2200 });
store.openIn('messages', { name: 'thread', id: threadId });
};
return (
<Screen
back
title={subLabel(listing.section, listing.sub)}
subtitle={`${sectionById(listing.section).label} · ${cityById(listing.cityId).name}`}
right={
listing.mine ? (
<Button
size="xs"
variant="outline"
color={C.red}
title="delete"
onPress={() => {
store.removePost(listing.id);
store.back();
toast.show({ title: 'Post deleted', autoHide: 2000 });
}}
/>
) : undefined
}
maw={1000}
>
<ListingBody listing={listing} onReply={() => setReplying(true)} />
<Dialog opened={replying} onClose={() => setReplying(false)} title={`reply to ${listing.seller}`} w={460}>
<Block gap={12}>
<Text c={C.muted} size={12}>
re: {listing.title}
</Text>
<Block gap={6} direction="row" wrap>
{QUICK.map((item) => (
<Chip key={item} size="xs" variant="outline" color={C.purple} onPress={() => setText(item)}>
{item}
</Chip>
))}
</Block>
<TextArea
variant="outline"
value={text}
onChangeText={setText}
placeholder="Write a message…"
rows={4}
radius={6}
mb={0}
accessibilityLabel="Message"
/>
<Button title="send message" color={C.purple} disabled={!text.trim()} onPress={send} radius={6} />
<Block gap={6} p={10} radius={6} bg={C.pale}>
<Text c={C.ink} fw="semibold" size={13}>
other ways to reply
</Text>
{showEmail ? (
<Text c={C.link} size={13} selectable>
{listing.id}-{listing.seller.toLowerCase().replace(/[^a-z]/g, '')}@relay.townlist.example
</Text>
) : (
<Text c={C.link} size={13} onPress={() => setShowEmail(true)}>
show anonymous relay email
</Text>
)}
<Text c={C.muted} size={11}>
Demo only: nothing leaves this device.
</Text>
</Block>
</Block>
</Dialog>
</Screen>
);
}
screens/Messages.tsx
import { useEffect, useRef, useState } from 'react';
import type { ScrollView } from 'react-native';
import { Avatar, Badge, Block, Icon, IconButton, Input, ScrollArea, SegmentedControl, Text } from '@plocks/ui';
import { C } from '../theme';
import { clockText, dateText, priceText, type Thread } from '../data';
import { useStore } from '../store';
import { EmptyNote, Thumb, TopBar, useWide } from '../components';
const AVATAR_COLORS = ['#5B2A8C', '#1F6B45', '#8A5A00', '#2F5D8C', '#A3283B', '#4C5A67'];
const avatarColor = (name: string) => AVATAR_COLORS[[...name].reduce((sum, ch) => sum + ch.charCodeAt(0), 0) % AVATAR_COLORS.length];
const initials = (name: string) =>
name
.split(/\s+/)
.slice(0, 2)
.map((word) => word[0]?.toUpperCase() ?? '')
.join('');
function ThreadRow({ thread, active, onPress }: { thread: Thread; active?: boolean; onPress: () => void }) {
const store = useStore();
const listing = store.listingById(thread.listingId);
const last = thread.messages[thread.messages.length - 1];
return (
<Block
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={`Conversation with ${thread.name}${thread.unread ? `, ${thread.unread} unread` : ''}`}
direction="row"
gap={12}
py={11}
px={12}
bg={active ? C.tint : thread.unread ? C.paler : C.white}
borderBottomWidth={1}
borderBottomColor={C.line}
pressedStyle={{ opacity: 0.7 }}
>
<Block gap={0} position="relative">
{listing ? <Thumb listing={listing} w={52} h={52} /> : <Block gap={0} w={52} h={52} radius={4} bg={C.pale} />}
<Block gap={0} position="absolute" right={-6} bottom={-6}>
<Avatar size={24} bg={avatarColor(thread.name)} textColor={C.white} fallback={initials(thread.name)} accessibilityLabel={thread.name} />
</Block>
</Block>
<Block flex={1} miw={0} gap={2}>
<Block gap={6} direction="row" align="center">
<Text c={C.ink} fw={thread.unread ? 'bold' : 'semibold'} size={14} numberOfLines={1} flex={1}>
{thread.name}
</Text>
<Text c={thread.unread ? C.purple : C.faint} size={11} fw={thread.unread ? 'bold' : 'normal'}>
{last ? clockText(last.at) : ''}
</Text>
</Block>
<Text c={C.link} size={12} numberOfLines={1}>
{listing?.title ?? 'deleted post'}
</Text>
<Block gap={6} direction="row" align="center">
<Text c={thread.unread ? C.ink : C.muted} size={13} numberOfLines={1} flex={1}>
{last?.from === 'me' ? 'You: ' : ''}
{last?.text}
</Text>
{thread.unread > 0 && (
<Badge size="xs" variant="filled" color={C.purple}>
{thread.unread}
</Badge>
)}
</Block>
</Block>
</Block>
);
}
export function ThreadView({ id, embedded }: { id: string; embedded?: boolean }) {
const store = useStore();
const thread = store.threads.find((item) => item.id === id);
const listing = thread ? store.listingById(thread.listingId) : undefined;
const [text, setText] = useState('');
const scroll = useRef<ScrollView>(null);
const count = thread?.messages.length ?? 0;
const unread = thread?.unread ?? 0;
const { markRead } = store;
useEffect(() => {
if (unread) markRead(id);
}, [id, unread, markRead]);
useEffect(() => {
const timer = setTimeout(() => scroll.current?.scrollToEnd({ animated: false }), 30);
return () => clearTimeout(timer);
}, [count, id]);
if (!thread) return <EmptyNote icon="message" title="Conversation not found" />;
const send = () => {
if (!text.trim()) return;
store.send(thread.id, text.trim());
setText('');
};
return (
<Block gap={0} flex={1} bg={C.white}>
<TopBar
onBack={!embedded && store.canGoBack ? store.back : undefined}
title={thread.name}
subtitle={thread.role === 'selling' ? 'interested in your post' : 'seller'}
/>
{listing && (
<Block
onPress={() => store.push({ name: 'listing', id: listing.id })}
accessibilityRole="button"
accessibilityLabel={`Open ${listing.title}`}
direction="row"
align="center"
gap={10}
px={14}
py={8}
bg={C.paler}
borderBottomWidth={1}
borderBottomColor={C.line}
pressedStyle={{ opacity: 0.7 }}
>
<Thumb listing={listing} w={40} h={40} />
<Block flex={1} miw={0} gap={0}>
<Text c={C.link} fw="semibold" size={13} numberOfLines={1}>
{listing.title}
</Text>
<Text c={C.muted} size={12}>
{priceText(listing) || listing.attrs[0]?.value} · {listing.hood}
</Text>
</Block>
<Badge size="xs" variant="light" color={thread.role === 'selling' ? C.green : C.purple}>
{thread.role}
</Badge>
<Icon name="chevron-right" color={C.faint} size={16} />
</Block>
)}
<ScrollArea ref={scroll} flex={1} bg={C.white} contentProps={{ p: 14, gap: 6 }}>
{thread.messages.map((message, index) => {
const mine = message.from === 'me';
const prev = thread.messages[index - 1];
const gap = !prev || message.at - prev.at > 45 * 60_000;
return (
<Block key={message.id} gap={4}>
{gap && (
<Text c={C.faint} size={11} ta="center" mt={index ? 10 : 0} mb={2}>
{dateText(message.at)}
</Text>
)}
<Block gap={0} direction="row" justify={mine ? 'flex-end' : 'flex-start'}>
<Block
gap={0}
maw="78%"
px={12}
py={8}
radius={14}
bg={mine ? C.bubbleMe : C.bubbleThem}
borderTopRightRadius={mine ? 4 : 14}
borderTopLeftRadius={mine ? 14 : 4}
>
<Text c={mine ? C.white : C.ink} size={14} lh={20}>
{message.text}
</Text>
</Block>
</Block>
</Block>
);
})}
</ScrollArea>
<Block gap={8} direction="row" align="center" p={10} borderTopWidth={1} borderTopColor={C.line} bg={C.white}>
<Input
variant="outline"
value={text}
onChangeText={setText}
onEnter={send}
placeholder={`Message ${thread.name}`}
mb={0}
flex={1}
radius={20}
inputColor={C.ink}
accessibilityLabel="Message"
/>
<IconButton icon="send" variant="filled" color={C.purple} iconColor={C.white} accessibilityLabel="Send" disabled={!text.trim()} onPress={send} />
</Block>
</Block>
);
}
export function Messages({ openId }: { openId?: string }) {
const store = useStore();
const wide = useWide();
const [filter, setFilter] = useState<'all' | 'buying' | 'selling'>('all');
const [selected, setSelected] = useState<string | undefined>(openId ?? (wide ? store.threads[0]?.id : undefined));
const threads = [...store.threads]
.filter((item) => filter === 'all' || item.role === filter)
.sort((a, b) => (b.messages[b.messages.length - 1]?.at ?? 0) - (a.messages[a.messages.length - 1]?.at ?? 0));
if (!wide && openId) return <ThreadView id={openId} />;
const list = (
<Block gap={0} flex={1} bg={C.white}>
<TopBar
title="messages"
subtitle={store.unread ? `${store.unread} unread` : `${store.threads.length} conversations`}
/>
<Block gap={0} p={10} borderBottomWidth={1} borderBottomColor={C.line}>
<SegmentedControl
fullWidth
size="sm"
color={C.purple}
value={filter}
onChange={(value) => setFilter(value as typeof filter)}
data={[
{ value: 'all', label: 'all' },
{ value: 'buying', label: 'buying' },
{ value: 'selling', label: 'selling' },
]}
accessibilityLabel="Filter conversations"
/>
</Block>
<ScrollArea flex={1}>
{threads.length === 0 ? (
<EmptyNote icon="message" title="No conversations">
Reply to a post to start one.
</EmptyNote>
) : (
threads.map((thread) => (
<ThreadRow
key={thread.id}
thread={thread}
active={wide && selected === thread.id}
onPress={() => (wide ? setSelected(thread.id) : store.push({ name: 'thread', id: thread.id }))}
/>
))
)}
<Block gap={4} direction="row" align="center" justify="center" p={16}>
<Icon name="lock" color={C.faint} size={12} />
<Text c={C.faint} size={11}>
replies go through an anonymous relay
</Text>
</Block>
</ScrollArea>
</Block>
);
if (!wide) return list;
return (
<Block gap={0} flex={1} direction="row">
<Block gap={0} w={360} borderRightWidth={1} borderRightColor={C.line}>
{list}
</Block>
<Block gap={0} flex={1}>
{selected ? <ThreadView key={selected} id={selected} embedded /> : <EmptyNote icon="message" title="Pick a conversation" />}
</Block>
</Block>
);
}
screens/Post.tsx
import { useMemo, useState, type ReactNode } from 'react';
import { useWindowDimensions } from 'react-native';
import {
Badge,
Block,
Button,
Checkbox,
Chip,
FileInput,
Icon,
IconButton,
Image,
Input,
Select,
Stepper,
Text,
TextArea,
useToast,
} from '@plocks/ui';
import type { FileInputFile } from '@plocks/ui';
import { C } from '../theme';
import {
CITIES,
PHOTO_KEYS,
PHOTO_LABELS,
PHOTOS,
POST_TYPES,
REGIONS,
cityById,
photoSource,
postTypeById,
sectionById,
subLabel,
type Attr,
type Listing,
type Photo,
type SectionId,
} from '../data';
import { useStore } from '../store';
import { MapBlock, Screen, SectionLabel, useWide } from '../components';
import { ListingBody } from './ListingView';
const STEPS = ['type', 'category', 'area', 'details', 'images', 'review'];
const MAX_PHOTOS = 12;
type Field = { key: string; label: string; options?: string[]; placeholder?: string; required?: boolean; numeric?: boolean };
type Toggle = { key: string; label: string };
type Spec = { price?: { label: string; per?: string; required: boolean }; fields: Field[]; toggles: Toggle[] };
const CONDITIONS = ['new', 'like new', 'excellent', 'good', 'fair', 'salvage'];
/** Category-specific form fields, like the real posting form. */
function specFor(typeId: string, section: SectionId, sub: string): Spec {
switch (section) {
case 'sale': {
const wanted = typeId === 'wanted';
const free = sub === 'free-stuff';
const fields: Field[] = [
{ key: 'condition', label: 'condition', options: CONDITIONS, required: !wanted },
{ key: 'make', label: 'make / manufacturer', placeholder: 'e.g. Larkspur' },
{ key: 'model', label: 'model name / number', placeholder: 'e.g. Metro 7' },
{ key: 'size', label: 'size / dimensions', placeholder: 'e.g. 30 x 32 in' },
];
if (sub === 'bikes') {
fields.push(
{ key: 'bicycle type', label: 'bicycle type', options: ['road', 'mountain', 'hybrid/comfort', 'cargo', 'kids', 'electric', 'other'] },
{ key: 'frame size', label: 'frame size', placeholder: 'e.g. 54 cm' },
);
}
if (sub === 'cars-trucks') {
fields.push(
{ key: 'model year', label: 'model year', placeholder: 'e.g. 2016', numeric: true, required: true },
{ key: 'odometer', label: 'odometer', placeholder: 'miles', numeric: true, required: true },
);
}
return {
price: free ? undefined : { label: wanted ? 'max price' : 'price', required: !wanted },
fields,
toggles: [
{ key: 'cash only', label: 'cash only' },
{ key: 'delivery available', label: 'delivery available' },
...(typeId === 'dealer' ? [{ key: 'warranty', label: 'includes warranty' }] : []),
],
};
}
case 'housing': {
const wanted = typeId === 'housing-wanted' || sub === 'housing-wanted';
const per = sub === 'vacation-rentals' ? '/night' : sub === 'real-estate-for-sale' ? undefined : '/mo';
return {
price: { label: wanted ? 'max budget' : sub === 'real-estate-for-sale' ? 'asking price' : 'rent', per, required: !wanted },
fields: [
{ key: 'bedrooms', label: 'bedrooms', options: ['studio', '1BR', '2BR', '3BR', '4BR+', 'room'], required: true },
{ key: 'bathrooms', label: 'bathrooms', options: ['shared', '1', '1.5', '2', '2.5', '3+'] },
{ key: 'size', label: 'size (ft²)', placeholder: 'e.g. 640', numeric: true },
{ key: 'available', label: 'available on', placeholder: 'e.g. dec 1' },
{ key: 'laundry', label: 'laundry', options: ['w/d in unit', 'w/d hookups', 'laundry in bldg', 'laundry on site', 'no laundry on site'] },
{ key: 'parking', label: 'parking', options: ['attached garage', 'detached garage', 'carport', 'off-street parking', 'street parking', 'no parking'] },
],
toggles: [
{ key: 'cats are OK', label: 'cats are OK - purrr' },
{ key: 'dogs are OK', label: 'dogs are OK - wooof' },
{ key: 'furnished', label: 'furnished' },
{ key: 'no smoking', label: 'no smoking' },
],
};
}
case 'jobs':
return {
fields: [
{ key: 'compensation', label: 'compensation', placeholder: 'e.g. $18/hr plus tips', required: true },
{ key: 'employment type', label: 'employment type', options: ['full-time', 'part-time', 'contract', 'employee’s choice'], required: true },
{ key: 'job title', label: 'job title', placeholder: 'e.g. barista' },
{ key: 'company', label: 'company name', placeholder: 'optional' },
],
toggles: [
{ key: 'remote', label: 'remote OK' },
{ key: 'internship', label: 'internship' },
{ key: 'non-profit', label: 'non-profit organization' },
],
};
case 'gigs':
return {
fields: [
{ key: 'gig type', label: 'pay', options: ['paid', 'unpaid'], required: true },
{ key: 'compensation', label: 'compensation', placeholder: 'e.g. $60 for an hour' },
],
toggles: [{ key: 'same day', label: 'needed today' }],
};
case 'services':
return {
price: { label: 'starting rate', per: '/hr', required: false },
fields: [
{ key: 'rate', label: 'rate details', placeholder: 'e.g. tune up from $35' },
{ key: 'service area', label: 'service area', placeholder: 'e.g. all of alder bay' },
],
toggles: [
{ key: 'licensed', label: 'licensed' },
{ key: 'insured', label: 'insured' },
],
};
default:
return {
fields:
typeId === 'event'
? [
{ key: 'event date', label: 'event date and time', placeholder: 'e.g. saturday, 10am to noon', required: true },
{ key: 'cost', label: 'cost', placeholder: 'e.g. free' },
]
: [],
toggles: typeId === 'event' ? [{ key: 'kid friendly', label: 'kid friendly' }] : [],
};
}
}
type Draft = {
type?: string;
sub?: string;
cityId: string;
hood?: string;
postal: string;
title: string;
price: string;
body: string;
fields: Record<string, string>;
toggles: Record<string, boolean>;
photos: Photo[];
showPhone: boolean;
};
function Choice({
label,
hint,
selected,
onPress,
right,
}: {
label: string;
hint?: string;
selected: boolean;
onPress: () => void;
right?: ReactNode;
}) {
return (
<Block
onPress={onPress}
accessibilityRole="radio"
accessibilityState={{ checked: selected }}
accessibilityLabel={label}
direction="row"
align="center"
gap={12}
py={10}
px={12}
bg={selected ? C.tint : C.white}
borderBottomWidth={1}
borderBottomColor={C.line}
pressedStyle={{ opacity: 0.7 }}
>
<Block gap={0} w={18} h={18} radius={9} borderWidth={selected ? 5 : 1.5} borderColor={selected ? C.purple : C.lineStrong} bg={C.white} />
<Block flex={1} miw={0} gap={1}>
<Text c={selected ? C.purple : C.link} fw="semibold" size={15}>
{label}
</Text>
{!!hint && (
<Text c={C.muted} size={12}>
{hint}
</Text>
)}
</Block>
{right}
</Block>
);
}
function Label({ children, required }: { children: ReactNode; required?: boolean }) {
return (
<Text c={C.ink} fw="semibold" size={13} lh={18} mb={4}>
{children}
{required ? (
<Text c={C.red} size={13} lh={18}>
{' '}*
</Text>
) : null}
</Text>
);
}
function newDraft(cityId: string): Draft {
return { cityId, postal: '', title: '', price: '', body: '', fields: {}, toggles: {}, photos: [], showPhone: false };
}
export function Post() {
const store = useStore();
const toast = useToast();
const wide = useWide();
const { width } = useWindowDimensions();
const tileW = wide ? 168 : Math.max(104, Math.floor((Math.min(width, 760) - 28 - 20) / 3));
const [step, setStep] = useState(0);
const [draft, setDraft] = useState<Draft>(() => newDraft(store.cityId));
const [published, setPublished] = useState<string | null>(null);
/** Picked files by photo id, so FileInput can be driven from the photo list. */
const [files, setFiles] = useState<Record<string, FileInputFile>>({});
const set = (patch: Partial<Draft>) => setDraft((old) => ({ ...old, ...patch }));
const type = draft.type ? postTypeById(draft.type) : undefined;
const section = type ? sectionById(type.section) : undefined;
const city = cityById(draft.cityId);
const spec = useMemo(() => (type && draft.sub ? specFor(type.id, type.section, draft.sub) : undefined), [type, draft.sub]);
const missing: string[] = [];
if (step >= 3 && spec) {
if (!draft.title.trim()) missing.push('posting title');
if (spec.price?.required && !draft.price.trim()) missing.push(spec.price.label);
if (draft.body.trim().length < 10) missing.push('description');
for (const field of spec.fields) if (field.required && !draft.fields[field.key]?.trim()) missing.push(field.label);
}
const canContinue = [!!type, !!draft.sub, !!draft.hood, missing.length === 0, true, true][step];
const listing: Listing | undefined =
type && draft.sub && spec
? {
id: published ?? 'preview',
title: draft.title.trim() || 'your posting title',
price: draft.price.trim() ? Number(draft.price) : type.section === 'sale' && draft.sub === 'free-stuff' ? 0 : null,
per: spec.price?.per,
section: type.section,
sub: draft.sub,
postType: type.id,
cityId: draft.cityId,
hood: draft.hood ?? city.hoods[0],
postedAt: Date.now(),
body: draft.body.trim() || 'Your description will appear here.',
photos: draft.photos,
attrs: [
...spec.fields
.filter((field) => draft.fields[field.key]?.trim())
.map((field): Attr => ({ label: field.key, value: draft.fields[field.key].trim() })),
...spec.toggles.filter((toggle) => draft.toggles[toggle.key]).map((toggle): Attr => ({ label: toggle.label, value: 'yes' })),
],
seller: 'You',
mine: true,
}
: undefined;
const addPhotos = (photos: Photo[]) => {
setDraft((old) => {
const room = MAX_PHOTOS - old.photos.length;
if (photos.length > room) toast.show({ title: `Up to ${MAX_PHOTOS} images`, message: 'Remove one to add more.', autoHide: 2200 });
return { ...old, photos: [...old.photos, ...photos.slice(0, Math.max(0, room))] };
});
};
const fileValue = draft.photos.filter((photo) => files[photo.id]).map((photo) => files[photo.id]);
const sampleCount = draft.photos.length - fileValue.length;
const onFiles = (next: FileInputFile[]) => {
const known = new Set(draft.photos.map((photo) => photo.id));
const added = next.filter((file) => !known.has(file.id) && !file.error && (file.previewUrl || file.uri));
const bad = next.filter((file) => file.error && !files[file.id]);
if (bad.length) toast.show({ title: 'Some files were skipped', message: bad[0].error, autoHide: 2600 });
setFiles((old) => ({ ...old, ...Object.fromEntries(next.map((file) => [file.id, file])) }));
const kept = new Set(next.map((file) => file.id));
const dropped = fileValue.filter((file) => !kept.has(file.id)).map((file) => file.id);
if (dropped.length) setDraft((old) => ({ ...old, photos: old.photos.filter((photo) => !dropped.includes(photo.id)) }));
if (added.length) addPhotos(added.map((file) => ({ id: file.id, src: (file.previewUrl || file.uri) as string, caption: file.name })));
};
const move = (index: number, delta: number) =>
setDraft((old) => {
const photos = [...old.photos];
const target = index + delta;
if (target < 0 || target >= photos.length) return old;
[photos[index], photos[target]] = [photos[target], photos[index]];
return { ...old, photos };
});
const remove = (id: string) => setDraft((old) => ({ ...old, photos: old.photos.filter((photo) => photo.id !== id) }));
const publish = () => {
if (!listing) return;
const id = String(8000 + Math.floor(Math.random() * 1900));
store.publish({ ...listing, id, postedAt: Date.now() });
setPublished(id);
};
const reset = () => {
setFiles({});
setDraft(newDraft(store.cityId));
setStep(0);
setPublished(null);
};
if (published) {
return (
<Screen title="posting published" maw={620}>
<Block gap={12} align="center" py={36}>
<Block gap={0} w={64} h={64} radius={32} bg={C.greenPale} align="center" justify="center">
<Icon name="check" color={C.green} size={32} />
</Block>
<Text c={C.ink} fw="bold" size={20} ta="center">
Your posting is live
</Text>
<Text c={C.muted} size={14} ta="center" lh={20}>
“{listing?.title}” is now in {subLabel(listing!.section, listing!.sub)} for {city.name}. Post id {published}.
</Text>
<Block gap={8} direction="row" mt={8} wrap justify="center">
<Button title="view posting" color={C.purple} onPress={() => store.openIn('browse', { name: 'listing', id: published })} />
<Button title="post another" variant="outline" color={C.purple} onPress={reset} />
</Block>
</Block>
</Screen>
);
}
const footer = (
<Block gap={10} direction="row" align="center" justify="center" px={14} py={10} borderTopWidth={1} borderTopColor={C.line} bg={C.white}>
<Block gap={10} direction="row" align="center" w="100%" maw={760}>
<Button title="back" variant="outline" color={C.purple} disabled={step === 0} onPress={() => setStep(step - 1)} />
<Text c={C.muted} size={12} flex={1} ta="center" numberOfLines={1}>
{step === 3 && missing.length ? `needed: ${missing.join(', ')}` : `step ${step + 1} of ${STEPS.length}`}
</Text>
{step < STEPS.length - 1 ? (
<Button title={step === 4 && !draft.photos.length ? 'skip images' : 'continue'} color={C.purple} disabled={!canContinue} onPress={() => setStep(step + 1)} />
) : (
<Button title="publish" color={C.green} startSection={<Icon name="check" color={C.white} size={16} />} onPress={publish} />
)}
</Block>
</Block>
);
const crumbs = [type?.label, draft.sub && type ? subLabel(type.section, draft.sub) : undefined, draft.hood ? `${draft.hood}, ${city.name}` : undefined].filter(Boolean);
return (
<Screen title="create a posting" subtitle={crumbs.length ? crumbs.join(' › ') : `posting to ${city.name}`} maw={760} footer={footer}>
<Block gap={0} py={6} mb={10}>
<Stepper
active={step}
onStepClick={(index) => index < step && setStep(index)}
compact={!wide}
size={wide ? 'sm' : 'xs'}
color={C.purple}
aria-label="Posting steps"
>
{STEPS.map((label) => (
<Stepper.Step key={label} label={label} />
))}
</Stepper>
</Block>
{step === 0 && (
<>
<Text c={C.ink} fw="bold" size={18}>
what type of posting is this?
</Text>
<Text c={C.muted} size={13} mb={10}>
choose the option that fits best
</Text>
<Block gap={0} borderWidth={1} borderColor={C.line} radius={6} overflow="hidden">
{POST_TYPES.map((item) => (
<Choice
key={item.id}
label={item.label}
hint={item.hint}
selected={draft.type === item.id}
onPress={() => set({ type: item.id, sub: item.section === type?.section ? draft.sub : undefined, fields: {}, toggles: {} })}
right={<Text c={C.faint} size={11}>{sectionById(item.section).label}</Text>}
/>
))}
</Block>
</>
)}
{step === 1 && section && (
<>
<Text c={C.ink} fw="bold" size={18}>
choose a category
</Text>
<Text c={C.muted} size={13} mb={10}>
{type?.label} · {section.label}
</Text>
<Block gap={0} direction="row" wrap borderWidth={1} borderColor={C.line} radius={6} overflow="hidden">
{section.subs.map((item) => (
<Block key={item.id} gap={0} w={wide ? '50%' : '100%'}>
<Choice
label={item.label}
selected={draft.sub === item.id}
onPress={() => set({ sub: item.id, fields: {}, toggles: {}, price: item.id === 'free-stuff' ? '' : draft.price })}
/>
</Block>
))}
</Block>
</>
)}
{step === 2 && (
<>
<Text c={C.ink} fw="bold" size={18}>
where is this located?
</Text>
<Text c={C.muted} size={13} mb={12}>
pick the area and neighborhood buyers will see
</Text>
<Label required>area</Label>
<Select
searchable
options={REGIONS.flatMap((region) =>
CITIES.filter((item) => item.region === region.id).map((item) => ({ label: item.name, value: item.id, description: region.label })),
)}
value={draft.cityId}
onChange={(value) => value && set({ cityId: value, hood: undefined })}
placeholder="choose an area"
searchPlaceholder="search areas"
mb={14}
radius={6}
accessibilityLabel="Area"
/>
<Label required>neighborhood</Label>
<Block gap={6} direction="row" wrap mb={14}>
{city.hoods.map((hood) => (
<Chip key={hood} size="sm" variant={draft.hood === hood ? 'filled' : 'outline'} color={C.purple} onPress={() => set({ hood })}>
{hood}
</Chip>
))}
</Block>
<Label>postal code</Label>
<Input
variant="outline"
value={draft.postal}
onChangeText={(postal) => set({ postal: postal.replace(/[^0-9]/g, '').slice(0, 5) })}
placeholder="optional"
keyboardType="number-pad"
mb={14}
w={160}
radius={6}
accessibilityLabel="Postal code"
/>
{draft.hood && <MapBlock hood={draft.hood} cityId={draft.cityId} h={150} />}
</>
)}
{step === 3 && spec && type && (
<Block gap={14}>
<Block gap={0}>
<Text c={C.ink} fw="bold" size={18}>
posting details
</Text>
<Text c={C.muted} size={13}>
{type.label} › {subLabel(type.section, draft.sub!)}
</Text>
</Block>
<Block gap={10} direction={wide ? 'row' : 'column'}>
<Block gap={0} flex={wide ? 1 : undefined}>
<Label required>posting title</Label>
<Input variant="outline" value={draft.title} onChangeText={(title) => set({ title })} placeholder="e.g. commuter bike, 54cm" maxLength={70} mb={0} radius={6} accessibilityLabel="Posting title" />
</Block>
{spec.price && (
<Block gap={0} w={wide ? 170 : undefined}>
<Label required={spec.price.required}>
{spec.price.label}
{spec.price.per ? ` (${spec.price.per.slice(1)})` : ''}
</Label>
<Input
variant="outline"
value={draft.price}
onChangeText={(price) => set({ price: price.replace(/[^0-9]/g, '') })}
placeholder="0"
keyboardType="number-pad"
startSection={<Text c={C.muted}>$</Text>}
mb={0}
radius={6}
accessibilityLabel={spec.price.label}
/>
</Block>
)}
</Block>
<Block gap={0}>
<Label required>description</Label>
<TextArea variant="outline" value={draft.body} onChangeText={(body) => set({ body })} placeholder="Describe what you're posting. Leave a blank line between paragraphs." rows={6} mb={0} radius={6} accessibilityLabel="Description" />
<Text c={C.faint} size={11} mt={4}>
{draft.body.length} characters
</Text>
</Block>
{spec.fields.length > 0 && (
<>
<SectionLabel mt={4}>{section?.label} details</SectionLabel>
<Block gap={0} direction="row" wrap justify="space-between">
{spec.fields.map((field) => (
<Block key={field.key} gap={0} w={wide ? '49%' : '100%'} pb={12}>
<Label required={field.required}>{field.label}</Label>
{field.options ? (
<Select
options={field.options.map((option) => ({ label: option, value: option }))}
value={draft.fields[field.key] ?? null}
onChange={(value) => set({ fields: { ...draft.fields, [field.key]: value ?? '' } })}
placeholder="-"
clearable={!field.required}
radius={6}
accessibilityLabel={field.label}
/>
) : (
<Input
variant="outline"
value={draft.fields[field.key] ?? ''}
onChangeText={(value) => set({ fields: { ...draft.fields, [field.key]: field.numeric ? value.replace(/[^0-9,]/g, '') : value } })}
placeholder={field.placeholder}
keyboardType={field.numeric ? 'number-pad' : 'default'}
mb={0}
radius={6}
accessibilityLabel={field.label}
/>
)}
</Block>
))}
</Block>
</>
)}
{spec.toggles.length > 0 && (
<Block gap={0} direction="row" wrap justify="space-between">
{spec.toggles.map((toggle) => (
<Block key={toggle.key} gap={0} w={wide ? '49%' : '100%'} pb={10}>
<Checkbox
label={toggle.label}
color={C.purple}
checked={!!draft.toggles[toggle.key]}
onChange={(checked) => set({ toggles: { ...draft.toggles, [toggle.key]: checked } })}
/>
</Block>
))}
</Block>
)}
<SectionLabel mt={4}>contact</SectionLabel>
<Block gap={8} p={12} radius={6} bg={C.paler} borderWidth={1} borderColor={C.line}>
<Text c={C.body} size={13}>
Replies come to your townlist messages through an anonymous relay email.
</Text>
<Checkbox label="also show my phone number" color={C.purple} checked={draft.showPhone} onChange={(showPhone) => set({ showPhone })} />
</Block>
</Block>
)}
{step === 4 && (
<Block gap={12}>
<Block gap={0}>
<Text c={C.ink} fw="bold" size={18}>
add images
</Text>
<Text c={C.muted} size={13}>
up to {MAX_PHOTOS} images · the first one is the cover photo
</Text>
</Block>
<FileInput
variant="dropzone"
accept={['image/*']}
multiple
maxFiles={MAX_PHOTOS - sampleCount}
value={fileValue}
maxSize={15 * 1024 * 1024}
showFileList={false}
imagePreview={{ enabled: true, maxWidth: 1200, maxHeight: 1200, quality: 0.82 }}
placeholder="drop images here"
onChange={onFiles}
disabled={draft.photos.length >= MAX_PHOTOS}
accessibilityLabel="Add images"
/>
<Block gap={6}>
<Text c={C.muted} size={12}>
no photos handy? add sample images:
</Text>
<Block gap={6} direction="row" wrap>
{PHOTO_KEYS.map((key) => (
<Block
key={key}
gap={0}
onPress={() => addPhotos([{ id: `${key}-${Date.now()}`, src: key, caption: PHOTO_LABELS[key] }])}
accessibilityRole="button"
accessibilityLabel={`Add sample photo: ${PHOTO_LABELS[key]}`}
radius={4}
overflow="hidden"
borderWidth={1}
borderColor={C.line}
pressedStyle={{ opacity: 0.6 }}
>
<Image src={PHOTOS[key]} w={wide ? 64 : 54} h={wide ? 48 : 42} resizeMode="cover" alt="" />
</Block>
))}
</Block>
</Block>
{draft.photos.length > 0 && (
<>
<SectionLabel right={<Text c={C.link} size={12} onPress={() => set({ photos: [] })}>remove all</Text>}>
{draft.photos.length} of {MAX_PHOTOS} images
</SectionLabel>
<Block gap={10} direction="row" wrap>
{draft.photos.map((photo, index) => (
<Block key={photo.id} gap={0} w={tileW} radius={6} overflow="hidden" borderWidth={index === 0 ? 2 : 1} borderColor={index === 0 ? C.purple : C.line} bg={C.white}>
<Block gap={0} position="relative">
<Image src={photoSource(photo)} w="100%" h={Math.round(tileW * 0.72)} resizeMode="cover" alt={photo.caption ?? `image ${index + 1}`} />
<Block gap={0} position="absolute" left={6} top={6}>
{index === 0 ? (
<Badge size="xs" variant="filled" color={C.purple}>
cover
</Badge>
) : (
<Badge size="xs" variant="filled" color={C.ink}>
{index + 1}
</Badge>
)}
</Block>
</Block>
<Block gap={0} direction="row" align="center" justify="space-between" px={2}>
<IconButton icon="arrow-left" size="sm" variant="ghost" iconColor={C.body} disabled={index === 0} accessibilityLabel={`Move image ${index + 1} earlier`} onPress={() => move(index, -1)} />
<IconButton icon="arrow-right" size="sm" variant="ghost" iconColor={C.body} disabled={index === draft.photos.length - 1} accessibilityLabel={`Move image ${index + 1} later`} onPress={() => move(index, 1)} />
<IconButton icon="trash" size="sm" variant="ghost" iconColor={C.red} accessibilityLabel={`Remove image ${index + 1}`} onPress={() => remove(photo.id)} />
</Block>
</Block>
))}
</Block>
</>
)}
</Block>
)}
{step === 5 && listing && (
<Block gap={12}>
<Block gap={8} direction="row" align="center" p={10} radius={6} bg={C.amberPale}>
<Icon name="eye" color={C.amber} size={16} />
<Text c={C.amber} size={13} flex={1}>
This is how your posting will look. Use back to edit.
</Text>
</Block>
<Block gap={0} p={wide ? 16 : 10} radius={8} borderWidth={1} borderColor={C.lineStrong} borderStyle="dashed">
<ListingBody listing={listing} preview />
</Block>
<Text c={C.muted} size={12}>
By publishing you agree to the townlist demo terms. Your posting stays on this device.
</Text>
</Block>
)}
</Screen>
);
}
screens/Results.tsx
import { useState } from 'react';
import { useWindowDimensions } from 'react-native';
import { Block, Chip, Icon, IconButton, Input, ScrollArea, SegmentedControl, Text, useToast } from '@plocks/ui';
import { C } from '../theme';
import { sectionById, subLabel } from '../data';
import { useStore, type Filter, type Sort } from '../store';
import { EmptyNote, ListingRow, ListingTile, Screen, useWide } from '../components';
import { CityButton, SearchBar } from './Home';
const SORTS: { value: Sort; label: string }[] = [
{ value: 'newest', label: 'newest' },
{ value: 'price-asc', label: 'price ↑' },
{ value: 'price-desc', label: 'price ↓' },
];
export function filterTitle(filter: Filter) {
if (filter.section && filter.sub) return subLabel(filter.section, filter.sub);
if (filter.section) return `all ${sectionById(filter.section).label}`;
return filter.query ? `“${filter.query}”` : 'all posts';
}
export function Results({ initial }: { initial: Filter }) {
const store = useStore();
const toast = useToast();
const wide = useWide();
const { width } = useWindowDimensions();
const [filter, setFilter] = useState<Filter>(initial);
const [view, setView] = useState<'list' | 'gallery'>('list');
const [showPrice, setShowPrice] = useState(!!(initial.min || initial.max));
const results = store.search(filter);
const set = (patch: Partial<Filter>) => setFilter((old) => ({ ...old, ...patch }));
const section = filter.section ? sectionById(filter.section) : undefined;
const columns = wide ? 4 : width >= 560 ? 3 : 2;
const contentW = Math.min(wide ? width - 220 - 48 : width - 28, 880);
const tileW = Math.floor((contentW - (columns - 1) * 10) / columns);
const open = (id: string) => store.push({ name: 'listing', id });
return (
<Screen
back
title={filterTitle(filter)}
subtitle={`${results.length} result${results.length === 1 ? '' : 's'} · ${store.city.name}${store.radius ? ` +${store.radius}mi` : ''}`}
right={
<Block gap={4} direction="row" align="center">
<IconButton
icon="bookmark"
variant="ghost"
iconColor={C.purple}
accessibilityLabel="Save this search"
onPress={() => {
store.saveSearch(filter);
toast.show({ title: 'Search saved', message: 'Find it under saved.', autoHide: 2200 });
}}
/>
{wide && <CityButton />}
</Block>
}
>
<Block gap={6} direction="row" align="center" mb={8} wrap>
<Text c={C.link} size={12} onPress={() => store.push({ name: 'cities' })}>
{store.city.name}
</Text>
{section && (
<>
<Text c={C.faint} size={12}>›</Text>
<Text c={C.link} size={12} onPress={() => set({ sub: undefined })}>
{section.label}
</Text>
</>
)}
{filter.sub && filter.section && (
<>
<Text c={C.faint} size={12}>›</Text>
<Text c={C.ink} size={12}>
{subLabel(filter.section, filter.sub)}
</Text>
</>
)}
</Block>
<SearchBar initial={filter.query} onSubmit={(query) => set({ query })} />
{section && (
<ScrollArea horizontal showsHorizontalScrollIndicator={false} mt={10} contentProps={{ gap: 6, direction: 'row' }}>
<Chip size="xs" variant={!filter.sub ? 'filled' : 'outline'} color={C.purple} onPress={() => set({ sub: undefined })}>
all
</Chip>
{section.subs.map((item) => (
<Chip
key={item.id}
size="xs"
variant={filter.sub === item.id ? 'filled' : 'outline'}
color={C.purple}
onPress={() => set({ sub: filter.sub === item.id ? undefined : item.id })}
>
{item.label}
</Chip>
))}
</ScrollArea>
)}
<Block gap={8} direction="row" align="center" justify="space-between" wrap mt={10} pb={10} borderBottomWidth={1} borderBottomColor={C.line}>
<Block gap={6} direction="row" wrap align="center">
<Chip size="xs" variant={filter.hasImage ? 'light' : 'outline'} color={C.purple} onPress={() => set({ hasImage: !filter.hasImage })} startSection={filter.hasImage ? <Icon name="check" size={12} color={C.purple} /> : undefined}>
has image
</Chip>
<Chip size="xs" variant={filter.today ? 'light' : 'outline'} color={C.purple} onPress={() => set({ today: !filter.today })} startSection={filter.today ? <Icon name="check" size={12} color={C.purple} /> : undefined}>
posted today
</Chip>
<Chip size="xs" variant={showPrice || filter.min || filter.max ? 'light' : 'outline'} color={C.purple} onPress={() => setShowPrice(!showPrice)} endSection={<Icon name={showPrice ? 'chevron-up' : 'chevron-down'} size={12} color={C.purple} />}>
{filter.min || filter.max ? `$${filter.min || 0}–${filter.max ? '$' + filter.max : 'any'}` : 'price'}
</Chip>
</Block>
<Block gap={8} direction="row" align="center">
<SegmentedControl
size="xs"
data={SORTS}
value={filter.sort ?? 'newest'}
onChange={(value) => set({ sort: value as Sort })}
color={C.purple}
accessibilityLabel="Sort results"
/>
<SegmentedControl
size="xs"
data={[
{ value: 'list', label: <Icon name="list" size={14} color={view === 'list' ? C.white : C.muted} /> },
{ value: 'gallery', label: <Icon name="grid" size={14} color={view === 'gallery' ? C.white : C.muted} /> },
]}
value={view}
onChange={(value) => setView(value as typeof view)}
color={C.purple}
accessibilityLabel="Results view"
/>
</Block>
</Block>
{showPrice && (
<Block gap={8} direction="row" align="center" py={10} borderBottomWidth={1} borderBottomColor={C.line}>
<Input variant="outline" size="sm" value={filter.min ?? ''} onChangeText={(min) => set({ min: min.replace(/[^0-9]/g, '') })} placeholder="min $" keyboardType="number-pad" mb={0} flex={1} radius={6} accessibilityLabel="Minimum price" />
<Text c={C.muted}>to</Text>
<Input variant="outline" size="sm" value={filter.max ?? ''} onChangeText={(max) => set({ max: max.replace(/[^0-9]/g, '') })} placeholder="max $" keyboardType="number-pad" mb={0} flex={1} radius={6} accessibilityLabel="Maximum price" />
<Text c={C.link} size={12} onPress={() => set({ min: undefined, max: undefined })}>
reset
</Text>
</Block>
)}
{results.length === 0 ? (
<EmptyNote icon="search" title="No posts found">
Try another search, a wider radius, or fewer filters.
{'\n'}
<Text c={C.link} size={13} onPress={() => store.push({ name: 'cities' })}>
change area or radius
</Text>
</EmptyNote>
) : view === 'list' ? (
results.map((item) => <ListingRow key={item.id} listing={item} onPress={() => open(item.id)} />)
) : (
<Block gap={10} direction="row" wrap pt={12}>
{results.map((item) => (
<ListingTile key={item.id} listing={item} w={tileW} onPress={() => open(item.id)} />
))}
</Block>
)}
{store.hidden.length > 0 && results.length > 0 && (
<Text c={C.faint} size={11} ta="center" mt={16}>
{store.hidden.length} hidden post{store.hidden.length === 1 ? '' : 's'} not shown
</Text>
)}
</Screen>
);
}
screens/Saved.tsx
import { useState } from 'react';
import { Block, Button, Icon, IconButton, SegmentedControl, Text } from '@plocks/ui';
import { C } from '../theme';
import { cityById, type Listing } from '../data';
import { useStore } from '../store';
import { EmptyNote, ListingRow, Screen } from '../components';
import { filterTitle } from './Results';
type View = 'favorites' | 'searches' | 'posts' | 'hidden';
export function Saved() {
const store = useStore();
const [view, setView] = useState<View>('favorites');
const pick = (ids: string[]) => ids.map(store.listingById).filter((item): item is Listing => !!item);
const favorites = pick(store.favorites);
const hidden = pick(store.hidden);
const open = (id: string) => store.push({ name: 'listing', id });
return (
<Screen title="saved" subtitle="favorites, searches, and your posts" maw={760}>
<SegmentedControl
fullWidth
size="sm"
color={C.purple}
value={view}
onChange={(value) => setView(value as View)}
data={[
{ value: 'favorites', label: `favorites ${favorites.length}` },
{ value: 'searches', label: `searches ${store.searches.length}` },
{ value: 'posts', label: `my posts ${store.posts.length}` },
{ value: 'hidden', label: `hidden ${hidden.length}` },
]}
accessibilityLabel="Saved items"
/>
<Block gap={0} mt={8}>
{view === 'favorites' &&
(favorites.length ? (
favorites.map((item) => <ListingRow key={item.id} listing={item} onPress={() => open(item.id)} />)
) : (
<EmptyNote icon="star" title="No favorites yet">
Tap the star on any post to keep it here.
</EmptyNote>
))}
{view === 'searches' &&
(store.searches.length ? (
store.searches.map((saved) => (
<Block
key={saved.id}
onPress={() => store.runSearch(saved)}
accessibilityRole="button"
accessibilityLabel={`Run search ${filterTitle(saved.filter)}`}
direction="row"
align="center"
gap={12}
py={12}
borderBottomWidth={1}
borderBottomColor={C.line}
pressedStyle={{ opacity: 0.6 }}
>
<Icon name="bookmark" color={C.purple} size={18} />
<Block flex={1} miw={0} gap={1}>
<Text c={C.link} fw="semibold" size={15}>
{filterTitle(saved.filter)}
{saved.filter.query && saved.filter.section ? ` · “${saved.filter.query}”` : ''}
</Text>
<Text c={C.muted} size={12}>
{cityById(saved.cityId).name}
{saved.radius ? ` +${saved.radius}mi` : ''}
{saved.filter.hasImage ? ' · has image' : ''}
{saved.filter.today ? ' · today' : ''}
</Text>
</Block>
<IconButton icon="trash" variant="ghost" iconColor={C.muted} accessibilityLabel="Delete saved search" onPress={() => store.removeSearch(saved.id)} />
</Block>
))
) : (
<EmptyNote icon="bookmark" title="No saved searches">
Use the bookmark on a results page to save a search.
</EmptyNote>
))}
{view === 'posts' && (
<>
{store.posts.map((item) => (
<ListingRow key={item.id} listing={item} onPress={() => open(item.id)} />
))}
<Block gap={0} align="center" mt={18}>
<Button title="create a new post" variant="light" color={C.purple} startSection={<Icon name="plus" size={15} color={C.purple} />} onPress={() => store.goTab('post', true)} />
</Block>
</>
)}
{view === 'hidden' &&
(hidden.length ? (
hidden.map((item) => <ListingRow key={item.id} listing={item} onPress={() => open(item.id)} />)
) : (
<EmptyNote icon="eye" title="No hidden posts">
Posts you hide are kept out of your results.
</EmptyNote>
))}
</Block>
</Screen>
);
}
store.tsx
/** App state for Townlist: navigation stacks, area, listings, favorites, and messages. */
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {
CITIES,
HOME_CITY,
LISTINGS,
THREADS,
cityById,
distance,
type Listing,
type SectionId,
type Thread,
} from './data';
export type Tab = 'browse' | 'saved' | 'post' | 'messages';
export type Sort = 'newest' | 'price-asc' | 'price-desc';
export type Filter = {
query: string;
section?: SectionId;
sub?: string;
hasImage?: boolean;
today?: boolean;
min?: string;
max?: string;
sort?: Sort;
};
export type Route =
| { name: 'home' }
| { name: 'categories'; section?: SectionId }
| { name: 'cities' }
| { name: 'results'; filter: Filter }
| { name: 'listing'; id: string }
| { name: 'threads' }
| { name: 'thread'; id: string }
| { name: 'saved' }
| { name: 'post' };
export type SavedSearch = { id: string; filter: Filter; cityId: string; radius: number };
const ROOTS: Record<Tab, Route> = {
browse: { name: 'home' },
saved: { name: 'saved' },
post: { name: 'post' },
messages: { name: 'threads' },
};
const STORAGE = 'plocks-townlist-example:v2';
const DAY = 24 * 60 * 60_000;
type Persisted = {
posts: Listing[];
favorites: string[];
hidden: string[];
threads: Thread[];
cityId: string;
radius: number;
searches: SavedSearch[];
};
function useTownlistState() {
const [tab, setTab] = useState<Tab>('browse');
const [stacks, setStacks] = useState<Record<Tab, Route[]>>({
browse: [ROOTS.browse],
saved: [ROOTS.saved],
post: [ROOTS.post],
messages: [ROOTS.messages],
});
const [posts, setPosts] = useState<Listing[]>(LISTINGS.filter((item) => item.mine));
const [favorites, setFavorites] = useState<string[]>(['7803', '7804']);
const [hidden, setHidden] = useState<string[]>([]);
const [flagged, setFlagged] = useState<string[]>([]);
const [threads, setThreads] = useState<Thread[]>(THREADS);
const [cityId, setCityId] = useState(HOME_CITY);
const [radius, setRadius] = useState(25);
const [searches, setSearches] = useState<SavedSearch[]>([]);
const [ready, setReady] = useState(false);
const replyTimers = useRef<ReturnType<typeof setTimeout>[]>([]);
useEffect(() => {
AsyncStorage.getItem(STORAGE)
.then((raw) => {
if (!raw) return;
const data = JSON.parse(raw) as Partial<Persisted>;
if (Array.isArray(data.posts)) setPosts(data.posts);
if (Array.isArray(data.favorites)) setFavorites(data.favorites);
if (Array.isArray(data.hidden)) setHidden(data.hidden);
if (Array.isArray(data.threads)) setThreads(data.threads);
if (Array.isArray(data.searches)) setSearches(data.searches);
if (typeof data.cityId === 'string' && CITIES.some((city) => city.id === data.cityId)) setCityId(data.cityId);
if (typeof data.radius === 'number') setRadius(data.radius);
})
.catch(() => {})
.finally(() => setReady(true));
const timers = replyTimers.current;
return () => timers.forEach(clearTimeout);
}, []);
useEffect(() => {
if (!ready) return;
const data: Persisted = { posts, favorites, hidden, threads, cityId, radius, searches };
AsyncStorage.setItem(STORAGE, JSON.stringify(data)).catch(() => {});
}, [ready, posts, favorites, hidden, threads, cityId, radius, searches]);
const listings = useMemo(() => [...posts, ...LISTINGS.filter((item) => !item.mine)], [posts]);
const listingById = useCallback((id: string) => listings.find((item) => item.id === id), [listings]);
const city = cityById(cityId);
/** Listings in the current area (city plus anything within the search radius). */
const inArea = useCallback(
(item: Listing) => item.cityId === cityId || distance(city, cityById(item.cityId)) <= radius,
[city, cityId, radius],
);
const search = useCallback(
(filter: Filter, options: { includeHidden?: boolean } = {}) => {
const words = filter.query.trim().toLowerCase().split(/\s+/).filter(Boolean);
const min = Number(filter.min);
const max = Number(filter.max);
const now = Date.now();
const found = listings.filter(
(item) =>
inArea(item) &&
(options.includeHidden || !hidden.includes(item.id)) &&
(!filter.section || item.section === filter.section) &&
(!filter.sub || item.sub === filter.sub) &&
(!filter.hasImage || item.photos.length > 0) &&
(!filter.today || now - item.postedAt < DAY) &&
(!filter.min || (item.price ?? 0) >= min) &&
(!filter.max || (item.price ?? 0) <= max) &&
words.every((word) => `${item.title} ${item.body} ${item.hood}`.toLowerCase().includes(word)),
);
const sort = filter.sort ?? 'newest';
return found.sort((a, b) =>
sort === 'newest' ? b.postedAt - a.postedAt : sort === 'price-asc' ? (a.price ?? 0) - (b.price ?? 0) : (b.price ?? 0) - (a.price ?? 0),
);
},
[listings, inArea, hidden],
);
const stack = stacks[tab];
const route = stack[stack.length - 1];
const push = useCallback(
(next: Route) => setStacks((old) => ({ ...old, [tab]: [...old[tab], next] })),
[tab],
);
const replace = useCallback(
(next: Route) => setStacks((old) => ({ ...old, [tab]: [...old[tab].slice(0, -1), next] })),
[tab],
);
const back = useCallback(
() => setStacks((old) => ({ ...old, [tab]: old[tab].length > 1 ? old[tab].slice(0, -1) : old[tab] })),
[tab],
);
const goTab = useCallback(
(next: Tab, reset = false) => {
if (next === tab || reset) setStacks((old) => ({ ...old, [next]: [ROOTS[next]] }));
setTab(next);
},
[tab],
);
/** Jump to a tab with a route on top of its root. */
const openIn = useCallback((next: Tab, target: Route) => {
setStacks((old) => ({ ...old, [next]: [ROOTS[next], target] }));
setTab(next);
}, []);
const toggle = (setter: typeof setFavorites) => (id: string) =>
setter((old) => (old.includes(id) ? old.filter((item) => item !== id) : [...old, id]));
function publish(listing: Listing) {
setPosts((old) => [listing, ...old]);
}
function removePost(id: string) {
setPosts((old) => old.filter((item) => item.id !== id));
}
/** Starts (or continues) a conversation about a listing; returns the thread id. */
function reply(listing: Listing, text: string) {
const existing = threads.find((item) => item.listingId === listing.id);
const id = existing?.id ?? `t-${Date.now()}`;
const message = { id: `${id}-${Date.now()}`, from: 'me' as const, text, at: Date.now() };
setThreads((old) =>
existing
? old.map((item) => (item.id === id ? { ...item, messages: [...item.messages, message] } : item))
: [{ id, listingId: listing.id, name: listing.seller, role: 'buying', unread: 0, messages: [message] }, ...old],
);
scheduleAutoReply(id, listing.seller);
return id;
}
function send(threadId: string, text: string) {
const message = { id: `${threadId}-${Date.now()}`, from: 'me' as const, text, at: Date.now() };
setThreads((old) => old.map((item) => (item.id === threadId ? { ...item, messages: [...item.messages, message] } : item)));
const thread = threads.find((item) => item.id === threadId);
if (thread) scheduleAutoReply(threadId, thread.name);
}
function scheduleAutoReply(threadId: string, name: string) {
const timer = setTimeout(() => {
setThreads((old) =>
old.map((item) =>
item.id === threadId
? {
...item,
unread: item.unread + 1,
messages: [
...item.messages,
{ id: `${threadId}-r${Date.now()}`, from: 'them', text: `Thanks for the message! This is a demo reply from ${name}.`, at: Date.now() },
],
}
: item,
),
);
}, 2200);
replyTimers.current.push(timer);
}
function markRead(threadId: string) {
setThreads((old) => old.map((item) => (item.id === threadId && item.unread ? { ...item, unread: 0 } : item)));
}
function saveSearch(filter: Filter) {
setSearches((old) => [{ id: `s-${Date.now()}`, filter, cityId, radius }, ...old]);
}
function removeSearch(id: string) {
setSearches((old) => old.filter((item) => item.id !== id));
}
function runSearch(saved: SavedSearch) {
setCityId(saved.cityId);
setRadius(saved.radius);
openIn('browse', { name: 'results', filter: saved.filter });
}
return {
tab,
route,
canGoBack: stack.length > 1,
push,
replace,
back,
goTab,
openIn,
listings,
posts,
listingById,
search,
inArea,
city,
cityId,
setCityId,
radius,
setRadius,
favorites,
toggleFavorite: toggle(setFavorites),
hidden,
toggleHidden: toggle(setHidden),
flagged,
flag: (id: string) => setFlagged((old) => (old.includes(id) ? old : [...old, id])),
publish,
removePost,
threads,
reply,
send,
markRead,
unread: threads.reduce((sum, item) => sum + item.unread, 0),
searches,
saveSearch,
removeSearch,
runSearch,
};
}
export type Store = ReturnType<typeof useTownlistState>;
const StoreContext = createContext<Store | null>(null);
export function StoreProvider({ children }: { children: ReactNode }) {
const store = useTownlistState();
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;
}
export function useStore() {
const store = useContext(StoreContext);
if (!store) throw new Error('useStore needs StoreProvider');
return store;
}
theme.ts
/** Townlist palette: utilitarian classifieds look with purple links. */
export const C = {
purple: '#5B2A8C',
purpleDark: '#43206A',
link: '#5B2A8C',
visited: '#7A4BA8',
ink: '#1F1D22',
body: '#33303A',
muted: '#6E6A75',
faint: '#9A96A0',
line: '#E3E0E7',
lineStrong: '#CFCAD6',
pale: '#F6F4F9',
paler: '#FBFAFD',
tint: '#EEE8F5',
white: '#FFFFFF',
green: '#1F6B45',
greenPale: '#E6F2EA',
amber: '#8A5A00',
amberPale: '#FBF1DC',
red: '#A3283B',
redPale: '#F9E6E9',
map: '#ECEFE6',
mapRoad: '#FFFFFF',
mapWater: '#D6E4EE',
mapPark: '#D9E8D2',
bubbleMe: '#5B2A8C',
bubbleThem: '#F0EEF3',
};
export const WIDE = 880;