Kin: personal relationships app — server (cadence/due/migrations) + Expo Android app
Some checks failed
Build & Release APK / build (push) Failing after 13s

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-09 00:49:45 -07:00
commit ac0b82e6a0
101 changed files with 11534 additions and 0 deletions

39
app/src/app/_layout.tsx Normal file
View File

@@ -0,0 +1,39 @@
import React, { useEffect } from "react";
import { AppState } from "react-native";
import { Stack } from "expo-router";
import { StatusBar } from "expo-status-bar";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { C } from "../lib/theme";
import { hydrate, refresh } from "../lib/store";
export default function RootLayout() {
useEffect(() => {
void hydrate();
const sub = AppState.addEventListener("change", (s) => {
if (s === "active") void refresh();
});
return () => sub.remove();
}, []);
return (
<GestureHandlerRootView style={{ flex: 1, backgroundColor: C.bg }}>
<StatusBar style="light" />
<Stack
screenOptions={{
headerStyle: { backgroundColor: C.bg },
headerTintColor: C.text,
headerTitleStyle: { fontWeight: "700" },
headerShadowVisible: false,
contentStyle: { backgroundColor: C.bg },
}}
>
<Stack.Screen name="index" options={{ title: "Kin" }} />
<Stack.Screen name="people" options={{ title: "People" }} />
<Stack.Screen name="person/[id]" options={{ title: "" }} />
<Stack.Screen name="log" options={{ title: "Log contact", presentation: "modal" }} />
<Stack.Screen name="edit" options={{ title: "Person", presentation: "modal" }} />
<Stack.Screen name="settings" options={{ title: "Settings", presentation: "modal" }} />
</Stack>
</GestureHandlerRootView>
);
}

107
app/src/app/edit.tsx Normal file
View File

@@ -0,0 +1,107 @@
import React, { useEffect, useState } from "react";
import { Alert, ScrollView, Text, View } from "react-native";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { C } from "../lib/theme";
import { api } from "../lib/api";
import { refresh } from "../lib/store";
import { Button, Chips, Field } from "../components/ui";
import { success } from "../lib/haptics";
import { CADENCES } from "../lib/types";
// Add (no id param) or edit (id param) a person.
export default function EditPerson() {
const { id } = useLocalSearchParams<{ id?: string }>();
const router = useRouter();
const editing = Boolean(id);
const [name, setName] = useState("");
const [phone, setPhone] = useState("");
const [email, setEmail] = useState("");
const [location, setLocation] = useState("");
const [tags, setTags] = useState("");
const [notes, setNotes] = useState("");
const [cadence, setCadence] = useState<(typeof CADENCES)[number]>(
CADENCES.find((c) => c.days === 30)!
);
const [loaded, setLoaded] = useState(!editing);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!id) return;
api.person(id).then((p) => {
setName(p.full_name);
setPhone(p.phone ?? "");
setEmail(p.email ?? "");
setLocation(p.location ?? "");
setTags(p.tags.join(", "));
setNotes(p.notes ?? "");
setCadence(CADENCES.find((c) => c.days === p.cadence_days) ?? CADENCES[CADENCES.length - 1]);
setLoaded(true);
});
}, [id]);
async function save() {
if (saving) return;
const full_name = name.trim();
if (!full_name) {
Alert.alert("Name is required");
return;
}
setSaving(true);
const body = {
full_name,
phone: phone.trim() || null,
email: email.trim() || null,
location: location.trim() || null,
tags,
notes: notes.trim() || null,
cadence_days: cadence.days,
};
try {
if (id) await api.updatePerson(id, body);
else await api.createPerson(body);
success();
void refresh();
router.back();
} catch (e) {
Alert.alert("Couldn't save", e instanceof Error ? e.message : "unknown error");
setSaving(false);
}
}
if (!loaded) {
return (
<View style={{ flex: 1, backgroundColor: C.bg, alignItems: "center", justifyContent: "center" }}>
<Text style={{ color: C.muted }}>Loading</Text>
</View>
);
}
return (
<>
<Stack.Screen options={{ title: editing ? "Edit person" : "Add person" }} />
<ScrollView
style={{ flex: 1, backgroundColor: C.bg }}
contentContainerStyle={{ padding: 16, paddingBottom: 60 }}
keyboardShouldPersistTaps="handled"
>
<Field label="Name" value={name} onChangeText={setName} placeholder="Full name" autoFocus={!editing} />
<Field label="Phone" value={phone} onChangeText={setPhone} placeholder="+61…" keyboardType="phone-pad" />
<Field label="Email" value={email} onChangeText={setEmail} placeholder="them@example.com" keyboardType="email-address" autoCapitalize="none" />
<Field label="Location" value={location} onChangeText={setLocation} placeholder="Sydney" />
<Field label="Tags" value={tags} onChangeText={setTags} placeholder="family, sf, climbing" autoCapitalize="none" />
<Field label="Notes" value={notes} onChangeText={setNotes} placeholder="How you met, what matters to them…" multiline />
<Text style={{ color: C.muted, fontSize: 13, marginBottom: 8 }}>Stay in touch</Text>
<Chips
options={CADENCES}
value={cadence}
onChange={setCadence}
getLabel={(c) => c.label}
getKey={(c) => String(c.days)}
/>
<View style={{ height: 20 }} />
<Button title={saving ? "Saving…" : editing ? "Save" : "Add person"} onPress={() => void save()} />
</ScrollView>
</>
);
}

136
app/src/app/index.tsx Normal file
View File

@@ -0,0 +1,136 @@
import React, { useMemo } from "react";
import {
Pressable,
RefreshControl,
SectionList,
StyleSheet,
Text,
View,
} from "react-native";
import { useRouter } from "expo-router";
import { C } from "../lib/theme";
import { useStore } from "../lib/useStore";
import { refresh } from "../lib/store";
import { PersonRow } from "../components/PersonRow";
import { Empty } from "../components/ui";
import type { DuePerson } from "../lib/types";
// Home: the relational-wealth dashboard. Who's overdue, who's coming up.
export default function Today() {
const { due, people, loading, error, lastSync } = useStore();
const router = useRouter();
const sections = useMemo(() => {
const d = due ?? [];
const overdue = d.filter((p) => p.status === "overdue");
const soon = d.filter((p) => p.status === "due_soon");
const ok = d.filter((p) => p.status === "ok");
const snoozed = d.filter((p) => p.status === "snoozed");
const out: { title: string; data: DuePerson[] }[] = [];
if (overdue.length) out.push({ title: "Reach out", data: overdue });
if (soon.length) out.push({ title: "Coming up", data: soon });
if (ok.length) out.push({ title: "On track", data: ok });
if (snoozed.length) out.push({ title: "Snoozed", data: snoozed });
return out;
}, [due]);
const noCadences = due != null && due.length === 0;
return (
<View style={{ flex: 1, backgroundColor: C.bg }}>
{error ? (
<Pressable onPress={() => router.push("/settings")} style={s.errorBar}>
<Text style={s.errorText}>{error} tap for Settings</Text>
</Pressable>
) : null}
<SectionList
sections={sections}
keyExtractor={(p) => p.id}
renderItem={({ item }) => <PersonRow person={item} due={item} />}
renderSectionHeader={({ section }) => (
<Text style={s.sectionHeader}>{section.title}</Text>
)}
refreshControl={
<RefreshControl
refreshing={loading}
onRefresh={() => void refresh()}
tintColor={C.muted}
/>
}
ListEmptyComponent={
noCadences ? (
<Empty
title={people?.length ? "No cadences set yet" : "Welcome to Kin"}
hint={
people?.length
? "Open People and give each person a cadence — how often you want to be in touch. They'll show up here when it's time."
: "Set your server token in Settings, then add the people who matter and how often you want to reach out."
}
/>
) : due == null ? (
<Empty title="Loading…" hint={error ?? undefined} />
) : null
}
contentContainerStyle={{ paddingBottom: 96 }}
/>
<View style={s.bottomBar}>
<Pressable onPress={() => router.push("/people")} style={s.bottomItem}>
<Text style={s.bottomText}>People</Text>
</Pressable>
<Pressable
onPress={() => router.push("/edit")}
style={[s.bottomItem, s.addBtn]}
>
<Text style={s.addText}></Text>
</Pressable>
<Pressable onPress={() => router.push("/settings")} style={s.bottomItem}>
<Text style={s.bottomText}>Settings</Text>
</Pressable>
</View>
{lastSync == null && !error ? null : null}
</View>
);
}
const s = StyleSheet.create({
sectionHeader: {
color: C.muted,
fontSize: 12,
fontWeight: "700",
textTransform: "uppercase",
letterSpacing: 1,
backgroundColor: C.bg,
paddingHorizontal: 16,
paddingTop: 18,
paddingBottom: 6,
},
errorBar: { backgroundColor: "#3A2224", paddingVertical: 8, paddingHorizontal: 16 },
errorText: { color: C.danger, fontSize: 13 },
bottomBar: {
position: "absolute",
bottom: 0,
left: 0,
right: 0,
flexDirection: "row",
alignItems: "center",
justifyContent: "space-around",
backgroundColor: C.surface,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: C.border,
paddingVertical: 10,
paddingBottom: 22,
},
bottomItem: { paddingHorizontal: 20, paddingVertical: 6 },
bottomText: { color: C.text, fontSize: 15, fontWeight: "600" },
addBtn: {
backgroundColor: C.accent,
borderRadius: 24,
width: 48,
height: 48,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: 0,
paddingVertical: 0,
},
addText: { color: "#1A0E10", fontSize: 24, fontWeight: "700", marginTop: -2 },
});

77
app/src/app/log.tsx Normal file
View File

@@ -0,0 +1,77 @@
import React, { useState } from "react";
import { Alert, ScrollView, StyleSheet, Text, View } from "react-native";
import { useLocalSearchParams, useRouter } from "expo-router";
import { C } from "../lib/theme";
import { api } from "../lib/api";
import { refresh } from "../lib/store";
import { Button, Chips, Field } from "../components/ui";
import { success } from "../lib/haptics";
import { INTERACTION_TYPES } from "../lib/types";
// Quick-log modal: two taps to record "I texted Alice today".
export default function LogInteraction() {
const { personId, name } = useLocalSearchParams<{ personId: string; name?: string }>();
const router = useRouter();
const [type, setType] = useState<string>("text");
const [when, setWhen] = useState<"today" | "yesterday">("today");
const [summary, setSummary] = useState("");
const [saving, setSaving] = useState(false);
async function save() {
if (!personId || saving) return;
setSaving(true);
try {
const occurred =
when === "today" ? undefined : new Date(Date.now() - 86400_000).toISOString();
await api.logInteraction(personId, {
type,
occurred_at: occurred,
summary: summary.trim() || undefined,
});
success();
void refresh();
router.back();
} catch (e) {
Alert.alert("Couldn't save", e instanceof Error ? e.message : "unknown error");
setSaving(false);
}
}
return (
<ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={s.body}>
{name ? <Text style={s.who}>{name}</Text> : null}
<Text style={s.label}>What was it?</Text>
<Chips
options={[...INTERACTION_TYPES]}
value={type}
onChange={setType}
getLabel={(t) => t}
getKey={(t) => t}
/>
<View style={{ height: 18 }} />
<Text style={s.label}>When?</Text>
<Chips
options={["today", "yesterday"] as const}
value={when}
onChange={(w) => setWhen(w)}
getLabel={(w) => w}
getKey={(w) => w}
/>
<View style={{ height: 18 }} />
<Field
label="Note (optional)"
value={summary}
onChangeText={setSummary}
placeholder="What did you talk about?"
multiline
/>
<Button title={saving ? "Saving…" : "Log it"} onPress={() => void save()} />
</ScrollView>
);
}
const s = StyleSheet.create({
body: { padding: 16, paddingBottom: 40 },
who: { color: C.text, fontSize: 20, fontWeight: "700", marginBottom: 16 },
label: { color: C.muted, fontSize: 13, marginBottom: 8 },
});

122
app/src/app/people.tsx Normal file
View File

@@ -0,0 +1,122 @@
import React, { useMemo, useState } from "react";
import {
FlatList,
Pressable,
RefreshControl,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
import { C } from "../lib/theme";
import { useStore } from "../lib/useStore";
import { refresh } from "../lib/store";
import { PersonRow } from "../components/PersonRow";
import { Empty } from "../components/ui";
import { tap } from "../lib/haptics";
// Full contact list. Search + tag filter are client-side — the whole network
// fits in memory many times over.
export default function People() {
const { people, loading } = useStore();
const [q, setQ] = useState("");
const [tag, setTag] = useState<string | null>(null);
const tags = useMemo(() => {
const counts = new Map<string, number>();
for (const p of people ?? [])
for (const t of p.tags) counts.set(t, (counts.get(t) ?? 0) + 1);
return [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([t]) => t);
}, [people]);
const filtered = useMemo(() => {
const needle = q.trim().toLowerCase();
return (people ?? []).filter((p) => {
if (tag && !p.tags.includes(tag)) return false;
if (!needle) return true;
return [p.full_name, p.email, p.phone, p.location]
.some((f) => f?.toLowerCase().includes(needle));
});
}, [people, q, tag]);
return (
<View style={{ flex: 1, backgroundColor: C.bg }}>
<TextInput
value={q}
onChangeText={setQ}
placeholder="Search people…"
placeholderTextColor={C.muted}
style={s.search}
autoCorrect={false}
/>
{tags.length ? (
<View style={s.tagRow}>
<FlatList
horizontal
data={tags}
keyExtractor={(t) => t}
showsHorizontalScrollIndicator={false}
contentContainerStyle={{ paddingHorizontal: 12, gap: 8 }}
renderItem={({ item }) => {
const active = item === tag;
return (
<Pressable
onPress={() => {
tap();
setTag(active ? null : item);
}}
style={[s.tagChip, active && { backgroundColor: C.accent, borderColor: C.accent }]}
>
<Text style={[s.tagChipText, active && { color: "#1A0E10", fontWeight: "700" }]}>
{item}
</Text>
</Pressable>
);
}}
/>
</View>
) : null}
<FlatList
data={filtered}
keyExtractor={(p) => p.id}
renderItem={({ item }) => <PersonRow person={item} />}
refreshControl={
<RefreshControl refreshing={loading} onRefresh={() => void refresh()} tintColor={C.muted} />
}
ListEmptyComponent={
<Empty
title={people == null ? "Loading…" : "Nobody here"}
hint={people == null ? undefined : "Add people from the home screen."}
/>
}
contentContainerStyle={{ paddingBottom: 40 }}
/>
</View>
);
}
const s = StyleSheet.create({
search: {
backgroundColor: C.surface,
borderWidth: 1,
borderColor: C.border,
borderRadius: 10,
marginHorizontal: 12,
marginTop: 10,
marginBottom: 8,
paddingHorizontal: 12,
paddingVertical: 9,
color: C.text,
fontSize: 15,
},
tagRow: { marginBottom: 6 },
tagChip: {
borderRadius: 14,
borderWidth: 1,
borderColor: C.border,
backgroundColor: C.surface,
paddingHorizontal: 11,
paddingVertical: 5,
},
tagChipText: { color: C.text, fontSize: 12 },
});

304
app/src/app/person/[id].tsx Normal file
View File

@@ -0,0 +1,304 @@
import React, { useCallback, useState } from "react";
import {
Alert,
Linking,
Pressable,
ScrollView,
StyleSheet,
Text,
View,
} from "react-native";
import { Stack, useFocusEffect, useLocalSearchParams, useRouter } from "expo-router";
import { C, STATUS_COLOR } from "../../lib/theme";
import { api } from "../../lib/api";
import { refresh } from "../../lib/store";
import { ago, cadenceLabel } from "../../lib/format";
import { Button, Chips, TagPill } from "../../components/ui";
import { tap, success } from "../../lib/haptics";
import { CADENCES, type PersonDetail } from "../../lib/types";
export default function Person() {
const { id } = useLocalSearchParams<{ id: string }>();
const router = useRouter();
const [person, setPerson] = useState<PersonDetail | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
if (!id) return;
api
.person(id)
.then((p) => {
setPerson(p);
setError(null);
})
.catch((e) => setError(e instanceof Error ? e.message : "failed to load"));
}, [id]);
useFocusEffect(
useCallback(() => {
load();
}, [load])
);
if (!person) {
return (
<View style={s.center}>
<Text style={{ color: error ? C.danger : C.muted }}>{error ?? "Loading…"}</Text>
</View>
);
}
const contactActions: { label: string; url: string }[] = [];
if (person.phone) {
const tel = person.phone.replace(/[^+\d]/g, "");
contactActions.push({ label: "Message", url: `sms:${tel}` });
contactActions.push({ label: "Call", url: `tel:${tel}` });
contactActions.push({ label: "WhatsApp", url: `https://wa.me/${tel.replace("+", "")}` });
}
if (person.email) contactActions.push({ label: "Email", url: `mailto:${person.email}` });
async function setCadence(days: number | null) {
try {
await api.updatePerson(person!.id, { cadence_days: days });
load();
void refresh();
} catch (e) {
Alert.alert("Couldn't update", e instanceof Error ? e.message : "unknown error");
}
}
async function snooze() {
try {
await api.snooze(person!.id, 7);
success();
load();
void refresh();
} catch (e) {
Alert.alert("Couldn't snooze", e instanceof Error ? e.message : "unknown error");
}
}
function confirmArchive() {
Alert.alert(
person!.archived ? "Unarchive?" : "Archive?",
person!.archived
? "They'll reappear in lists and reminders."
: "Hidden from lists and reminders. History is kept.",
[
{ text: "Cancel", style: "cancel" },
{
text: person!.archived ? "Unarchive" : "Archive",
style: "destructive",
onPress: async () => {
await api.updatePerson(person!.id, { archived: !person!.archived });
void refresh();
router.back();
},
},
]
);
}
const currentCadence = CADENCES.find((c) => c.days === person.cadence_days) ?? null;
return (
<>
<Stack.Screen
options={{
title: person.full_name,
headerRight: () => (
<Pressable
onPress={() => {
tap();
router.push({ pathname: "/edit", params: { id: person.id } });
}}
hitSlop={8}
>
<Text style={{ color: C.accent, fontSize: 15, fontWeight: "600" }}>Edit</Text>
</Pressable>
),
}}
/>
<ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={s.body}>
{person.tags.length || person.location ? (
<View style={s.metaRow}>
{person.location ? <Text style={s.location}>{person.location}</Text> : null}
{person.tags.map((t) => (
<TagPill key={t} tag={t} />
))}
</View>
) : null}
<Text style={s.lastContact}>
Last contact:{" "}
<Text style={{ color: C.text }}>{ago(person.last_contacted ?? (person.interactions[0]?.occurred_at ?? null))}</Text>
{" · "}
{person.interactions.length} logged
</Text>
{contactActions.length ? (
<View style={s.actionRow}>
{contactActions.map((a) => (
<Pressable
key={a.label}
onPress={() => {
tap();
void Linking.openURL(a.url).catch(() => {});
}}
style={s.actionBtn}
>
<Text style={s.actionText}>{a.label}</Text>
</Pressable>
))}
</View>
) : null}
<View style={s.card}>
<Text style={s.cardLabel}>Stay in touch</Text>
<Chips
options={CADENCES}
value={currentCadence}
onChange={(c) => void setCadence(c.days)}
getLabel={(c) => c.label}
getKey={(c) => String(c.days)}
/>
{person.snoozed_until ? (
<Text style={s.snoozedNote}>Snoozed until {String(person.snoozed_until).slice(0, 10)}</Text>
) : null}
</View>
<View style={{ flexDirection: "row", gap: 10, marginBottom: 18 }}>
<View style={{ flex: 1 }}>
<Button
title="Log contact"
onPress={() =>
router.push({
pathname: "/log",
params: { personId: person.id, name: person.full_name },
})
}
/>
</View>
<View style={{ flex: 1 }}>
<Button title="Snooze 7d" kind="ghost" onPress={() => void snooze()} />
</View>
</View>
{person.notes ? (
<View style={s.card}>
<Text style={s.cardLabel}>Notes</Text>
<Text style={s.notes}>{person.notes}</Text>
</View>
) : null}
{person.relationships.length ? (
<View style={s.card}>
<Text style={s.cardLabel}>Relationships</Text>
{person.relationships.map((r) => (
<Pressable
key={r.id}
onPress={() =>
router.push({ pathname: "/person/[id]", params: { id: r.other_id } })
}
style={s.relRow}
>
<Text style={s.relName}>{r.other_name}</Text>
<Text style={s.relType}>{r.type}</Text>
</Pressable>
))}
</View>
) : null}
<View style={s.card}>
<Text style={s.cardLabel}>History</Text>
{person.interactions.length === 0 ? (
<Text style={s.notes}>Nothing logged yet.</Text>
) : (
person.interactions.map((i) => (
<Pressable
key={i.id}
onLongPress={() => {
Alert.alert("Delete this entry?", i.summary ?? i.type ?? "", [
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: async () => {
await api.deleteInteraction(i.id);
load();
void refresh();
},
},
]);
}}
style={s.histRow}
>
<Text style={s.histDate}>{String(i.occurred_at).slice(0, 10)}</Text>
<View style={{ flex: 1 }}>
<Text style={s.histType}>{i.type ?? "contact"}</Text>
{i.summary ? <Text style={s.histSummary}>{i.summary}</Text> : null}
</View>
</Pressable>
))
)}
</View>
<Button
title={person.archived ? "Unarchive" : "Archive"}
kind="danger"
onPress={confirmArchive}
/>
<View style={{ height: 40 }} />
</ScrollView>
</>
);
}
const s = StyleSheet.create({
center: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: C.bg },
body: { padding: 16 },
metaRow: { flexDirection: "row", flexWrap: "wrap", gap: 6, alignItems: "center", marginBottom: 10 },
location: { color: C.muted, fontSize: 13, marginRight: 4 },
lastContact: { color: C.muted, fontSize: 14, marginBottom: 14 },
actionRow: { flexDirection: "row", gap: 8, marginBottom: 18, flexWrap: "wrap" },
actionBtn: {
backgroundColor: C.surface2,
borderWidth: 1,
borderColor: C.border,
borderRadius: 10,
paddingHorizontal: 14,
paddingVertical: 9,
},
actionText: { color: C.accent, fontSize: 14, fontWeight: "600" },
card: {
backgroundColor: C.surface,
borderWidth: 1,
borderColor: C.border,
borderRadius: 12,
padding: 14,
marginBottom: 18,
},
cardLabel: {
color: C.muted,
fontSize: 12,
fontWeight: "700",
textTransform: "uppercase",
letterSpacing: 1,
marginBottom: 10,
},
snoozedNote: { color: C.warn, fontSize: 13, marginTop: 10 },
notes: { color: C.text, fontSize: 14, lineHeight: 20 },
relRow: {
flexDirection: "row",
justifyContent: "space-between",
paddingVertical: 8,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: C.border,
},
relName: { color: C.text, fontSize: 14, fontWeight: "600" },
relType: { color: C.muted, fontSize: 13 },
histRow: { flexDirection: "row", gap: 12, paddingVertical: 8 },
histDate: { color: C.muted, fontSize: 13, width: 84 },
histType: { color: C.text, fontSize: 14, fontWeight: "600" },
histSummary: { color: C.muted, fontSize: 13, marginTop: 2 },
});

85
app/src/app/settings.tsx Normal file
View File

@@ -0,0 +1,85 @@
import React, { useEffect, useState } from "react";
import { Alert, ScrollView, Text, View } from "react-native";
import { useRouter } from "expo-router";
import { C } from "../lib/theme";
import { DEFAULT_URL, getConfig, setConfig } from "../lib/config";
import { api } from "../lib/api";
import { refresh } from "../lib/store";
import { Button, Chips, Field } from "../components/ui";
const HOURS = [8, 9, 10, 12, 18, 20];
export default function Settings() {
const router = useRouter();
const [url, setUrl] = useState(DEFAULT_URL);
const [token, setToken] = useState("");
const [hour, setHour] = useState(9);
const [busy, setBusy] = useState(false);
useEffect(() => {
void getConfig().then((c) => {
setUrl(c.url);
setToken(c.token);
setHour(c.notifHour);
});
}, []);
async function save() {
if (busy) return;
setBusy(true);
await setConfig(url, token, hour);
try {
await api.due(); // probe: fails fast on bad URL/token
await refresh();
router.back();
} catch (e) {
Alert.alert(
"Couldn't reach the server",
e instanceof Error ? e.message : "unknown error"
);
setBusy(false);
}
}
return (
<ScrollView
style={{ flex: 1, backgroundColor: C.bg }}
contentContainerStyle={{ padding: 16 }}
keyboardShouldPersistTaps="handled"
>
<Field
label="Server URL"
value={url}
onChangeText={setUrl}
autoCapitalize="none"
autoCorrect={false}
placeholder={DEFAULT_URL}
/>
<Field
label="API token"
value={token}
onChangeText={setToken}
autoCapitalize="none"
autoCorrect={false}
secureTextEntry
placeholder="paste the bearer token"
/>
<Text style={{ color: C.muted, fontSize: 13, marginBottom: 8 }}>
Daily reminder time
</Text>
<Chips
options={HOURS}
value={hour}
onChange={setHour}
getLabel={(h) => `${h}:00`}
getKey={(h) => String(h)}
/>
<View style={{ height: 20 }} />
<Button title={busy ? "Checking…" : "Save"} onPress={() => void save()} />
<Text style={{ color: C.muted, fontSize: 12, marginTop: 24, lineHeight: 18 }}>
Kin is a thin client over your own server all data lives in your
Postgres database. The token is stored only on this device.
</Text>
</ScrollView>
);
}

View File

@@ -0,0 +1,78 @@
import React from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";
import { useRouter } from "expo-router";
import { C, STATUS_COLOR } from "../lib/theme";
import { ago, cadenceLabel, dueLine } from "../lib/format";
import { tap } from "../lib/haptics";
import type { DuePerson, Person } from "../lib/types";
// One row, used by both the Today (due) list and the People list.
// `due` rows show overdue info + a quick-log button.
export function PersonRow({ person, due }: { person: Person; due?: DuePerson }) {
const router = useRouter();
const subtitle = due
? dueLine(due.days_since, due.cadence_days ?? 0, due.last_contacted)
: `${ago(person.last_contacted)} · ${cadenceLabel(person.cadence_days)}`;
return (
<Pressable
onPress={() => {
tap();
router.push({ pathname: "/person/[id]", params: { id: person.id } });
}}
style={({ pressed }) => [s.row, pressed && { backgroundColor: C.surface2 }]}
>
{due ? <View style={[s.dot, { backgroundColor: STATUS_COLOR[due.status] }]} /> : null}
<View style={{ flex: 1 }}>
<Text style={s.name} numberOfLines={1}>
{person.full_name}
</Text>
<Text style={s.sub} numberOfLines={1}>
{subtitle}
</Text>
</View>
{due ? (
<Pressable
onPress={(e) => {
e.stopPropagation();
tap();
router.push({
pathname: "/log",
params: { personId: person.id, name: person.full_name },
});
}}
style={({ pressed }) => [s.logBtn, pressed && { opacity: 0.6 }]}
hitSlop={8}
>
<Text style={s.logBtnText}></Text>
</Pressable>
) : null}
</Pressable>
);
}
const s = StyleSheet.create({
row: {
flexDirection: "row",
alignItems: "center",
gap: 10,
paddingHorizontal: 16,
paddingVertical: 12,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: C.border,
},
dot: { width: 8, height: 8, borderRadius: 4 },
name: { color: C.text, fontSize: 16, fontWeight: "600" },
sub: { color: C.muted, fontSize: 13, marginTop: 2 },
logBtn: {
width: 34,
height: 34,
borderRadius: 17,
backgroundColor: C.surface2,
borderWidth: 1,
borderColor: C.border,
alignItems: "center",
justifyContent: "center",
},
logBtnText: { color: C.accent, fontSize: 16, fontWeight: "700" },
});

164
app/src/components/ui.tsx Normal file
View File

@@ -0,0 +1,164 @@
import React from "react";
import {
Pressable,
StyleSheet,
Text,
TextInput,
View,
type TextInputProps,
} from "react-native";
import { C } from "../lib/theme";
import { tap } from "../lib/haptics";
export function Button({
title,
onPress,
kind = "primary",
small,
}: {
title: string;
onPress: () => void;
kind?: "primary" | "ghost" | "danger";
small?: boolean;
}) {
return (
<Pressable
onPress={() => {
tap();
onPress();
}}
style={({ pressed }) => [
s.btn,
small && s.btnSmall,
kind === "primary" && { backgroundColor: C.accent },
kind === "ghost" && { backgroundColor: C.surface2, borderWidth: 1, borderColor: C.border },
kind === "danger" && { backgroundColor: "transparent", borderWidth: 1, borderColor: C.danger },
pressed && { opacity: 0.7 },
]}
>
<Text
style={[
s.btnText,
small && { fontSize: 13 },
kind === "primary" && { color: "#1A0E10", fontWeight: "700" },
kind === "ghost" && { color: C.text },
kind === "danger" && { color: C.danger },
]}
>
{title}
</Text>
</Pressable>
);
}
export function Field({
label,
...props
}: TextInputProps & { label: string }) {
return (
<View style={{ marginBottom: 14 }}>
<Text style={s.label}>{label}</Text>
<TextInput
placeholderTextColor={C.muted}
style={[s.input, props.multiline && { minHeight: 80, textAlignVertical: "top" }]}
{...props}
/>
</View>
);
}
export function Chips<T>({
options,
value,
onChange,
getLabel,
getKey,
}: {
options: T[];
value: T | null;
onChange: (v: T) => void;
getLabel: (v: T) => string;
getKey: (v: T) => string;
}) {
return (
<View style={s.chips}>
{options.map((o) => {
const active = value != null && getKey(o) === getKey(value);
return (
<Pressable
key={getKey(o)}
onPress={() => {
tap();
onChange(o);
}}
style={[s.chip, active && { backgroundColor: C.accent, borderColor: C.accent }]}
>
<Text style={[s.chipText, active && { color: "#1A0E10", fontWeight: "700" }]}>
{getLabel(o)}
</Text>
</Pressable>
);
})}
</View>
);
}
export function TagPill({ tag }: { tag: string }) {
return (
<View style={s.tag}>
<Text style={s.tagText}>{tag}</Text>
</View>
);
}
export function Empty({ title, hint }: { title: string; hint?: string }) {
return (
<View style={s.empty}>
<Text style={s.emptyTitle}>{title}</Text>
{hint ? <Text style={s.emptyHint}>{hint}</Text> : null}
</View>
);
}
const s = StyleSheet.create({
btn: {
borderRadius: 10,
paddingVertical: 12,
paddingHorizontal: 18,
alignItems: "center",
justifyContent: "center",
},
btnSmall: { paddingVertical: 7, paddingHorizontal: 12 },
btnText: { fontSize: 15, fontWeight: "600" },
label: { color: C.muted, fontSize: 13, marginBottom: 6 },
input: {
backgroundColor: C.surface,
borderWidth: 1,
borderColor: C.border,
borderRadius: 10,
paddingHorizontal: 12,
paddingVertical: 10,
color: C.text,
fontSize: 15,
},
chips: { flexDirection: "row", flexWrap: "wrap", gap: 8 },
chip: {
borderRadius: 16,
borderWidth: 1,
borderColor: C.border,
backgroundColor: C.surface,
paddingHorizontal: 12,
paddingVertical: 6,
},
chipText: { color: C.text, fontSize: 13 },
tag: {
backgroundColor: C.surface2,
borderRadius: 10,
paddingHorizontal: 8,
paddingVertical: 2,
},
tagText: { color: C.muted, fontSize: 12 },
empty: { alignItems: "center", paddingVertical: 48, paddingHorizontal: 24 },
emptyTitle: { color: C.text, fontSize: 16, fontWeight: "600", marginBottom: 6 },
emptyHint: { color: C.muted, fontSize: 14, textAlign: "center", lineHeight: 20 },
});

61
app/src/lib/api.ts Normal file
View File

@@ -0,0 +1,61 @@
import { getConfig } from "./config";
import type { DuePerson, Interaction, Person, PersonDetail } from "./types";
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
async function call<T>(path: string, init?: RequestInit): Promise<T> {
const { url, token } = await getConfig();
if (!token) throw new ApiError(401, "No API token set — open Settings");
const res = await fetch(`${url}${path}`, {
...init,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
...init?.headers,
},
});
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try {
const body = (await res.json()) as { error?: string };
if (body.error) msg = body.error;
} catch {}
throw new ApiError(res.status, msg);
}
return (await res.json()) as T;
}
// The server normalizes `tags` from either an array or a comma-separated string.
export type PersonInput = Partial<Omit<Person, "tags"> & { tags: string[] | string }>;
export const api = {
due: () => call<DuePerson[]>("/due"),
people: () => call<Person[]>("/people?sort=stale"),
person: (id: string) => call<PersonDetail>(`/people/${id}`),
createPerson: (body: PersonInput) =>
call<Person>("/people", { method: "POST", body: JSON.stringify(body) }),
updatePerson: (id: string, body: PersonInput) =>
call<Person>(`/people/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
deletePerson: (id: string) => call<{ deleted: string }>(`/people/${id}`, { method: "DELETE" }),
logInteraction: (
personId: string,
body: { type?: string; occurred_at?: string; summary?: string; notes?: string }
) =>
call<Interaction>(`/people/${personId}/interactions`, {
method: "POST",
body: JSON.stringify(body),
}),
deleteInteraction: (id: string) =>
call<{ deleted: string }>(`/interactions/${id}`, { method: "DELETE" }),
snooze: (personId: string, days: number) =>
call<{ id: string; snoozed_until: string | null }>(`/people/${personId}/snooze`, {
method: "POST",
body: JSON.stringify({ days }),
}),
};

32
app/src/lib/config.ts Normal file
View File

@@ -0,0 +1,32 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
export const DEFAULT_URL = "https://crm.rehbock.xyz/api";
const KEYS = { url: "kin_api_url", token: "kin_api_token", hour: "kin_notif_hour" };
let cached: { url: string; token: string; notifHour: number } | null = null;
export async function getConfig() {
if (cached) return cached;
const [url, token, hour] = await Promise.all([
AsyncStorage.getItem(KEYS.url),
AsyncStorage.getItem(KEYS.token),
AsyncStorage.getItem(KEYS.hour),
]);
cached = {
url: url || DEFAULT_URL,
token: token || "",
notifHour: hour ? Number(hour) : 9,
};
return cached;
}
export async function setConfig(url: string, token: string, notifHour: number) {
const cleanUrl = (url.trim() || DEFAULT_URL).replace(/\/+$/, "");
cached = { url: cleanUrl, token: token.trim(), notifHour };
await Promise.all([
AsyncStorage.setItem(KEYS.url, cleanUrl),
AsyncStorage.setItem(KEYS.token, cached.token),
AsyncStorage.setItem(KEYS.hour, String(notifHour)),
]);
}

29
app/src/lib/format.ts Normal file
View File

@@ -0,0 +1,29 @@
import { CADENCES } from "./types";
// "3d ago", "2w ago", "5mo ago", "never"
export function ago(iso: string | null): string {
if (!iso) return "never";
const days = Math.floor((Date.now() - new Date(iso).getTime()) / 86400_000);
if (days <= 0) return "today";
if (days === 1) return "yesterday";
if (days < 14) return `${days}d ago`;
if (days < 60) return `${Math.round(days / 7)}w ago`;
if (days < 365) return `${Math.round(days / 30)}mo ago`;
return `${Math.round((days / 365) * 10) / 10}y ago`;
}
export function cadenceLabel(days: number | null): string {
if (days == null) return "no cadence";
const preset = CADENCES.find((c) => c.days === days);
if (preset) return preset.label.toLowerCase();
return `every ${days}d`;
}
// Human line for the due list: how late someone is.
export function dueLine(daysSince: number, cadence: number, lastContacted: string | null): string {
const late = daysSince - cadence;
const base = lastContacted ? `last contact ${ago(lastContacted)}` : "never contacted";
if (late > 0) return `${base} · ${late}d overdue`;
if (late === 0) return `${base} · due today`;
return `${base} · due in ${-late}d`;
}

11
app/src/lib/haptics.ts Normal file
View File

@@ -0,0 +1,11 @@
import * as Haptics from "expo-haptics";
import { Platform } from "react-native";
export function tap() {
if (Platform.OS !== "web") void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
}
export function success() {
if (Platform.OS !== "web")
void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
}

View File

@@ -0,0 +1,82 @@
import * as Notifications from "expo-notifications";
import { Platform } from "react-native";
import { getConfig } from "./config";
import type { DuePerson } from "./types";
// Local daily digest, scheduled 7 days ahead from the latest due data every
// time we sync. No server push involved: each day at notifHour the phone
// shows how many people are due, computed from cadences known at sync time.
// If the app isn't opened for a week the notifications run out — which is
// itself a decent nudge to open the app.
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowBanner: true,
shouldShowList: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
let permissionAsked = false;
export async function ensurePermission(): Promise<boolean> {
if (Platform.OS === "web") return false;
const cur = await Notifications.getPermissionsAsync();
if (cur.granted) return true;
if (permissionAsked) return false;
permissionAsked = true;
const req = await Notifications.requestPermissionsAsync();
return req.granted;
}
// Number of people whose due date falls on or before `day`.
function dueCountOn(due: DuePerson[], day: Date): number {
const dayEnd = new Date(day);
dayEnd.setHours(23, 59, 59, 999);
return due.filter((p) => {
if (p.snoozed || p.cadence_days == null) return false;
const anchor = p.last_contacted ? new Date(p.last_contacted) : null;
if (!anchor) return true; // never contacted → always due
const dueAt = new Date(anchor.getTime() + p.cadence_days * 86400_000);
return dueAt <= dayEnd;
}).length;
}
export async function scheduleDigest(due: DuePerson[]) {
if (Platform.OS === "web") return;
if (!(await ensurePermission())) return;
if (Platform.OS === "android") {
await Notifications.setNotificationChannelAsync("reminders", {
name: "Catch-up reminders",
importance: Notifications.AndroidImportance.DEFAULT,
});
}
await Notifications.cancelAllScheduledNotificationsAsync();
const { notifHour } = await getConfig();
const now = new Date();
for (let i = 0; i < 7; i++) {
const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() + i, notifHour, 0, 0);
if (day <= now) continue;
const n = dueCountOn(due, day);
if (n === 0) continue;
const names = due
.filter((p) => !p.snoozed)
.slice(0, 3)
.map((p) => p.full_name.split(" ")[0])
.join(", ");
await Notifications.scheduleNotificationAsync({
content: {
title: n === 1 ? "1 person is due for a catch-up" : `${n} people are due for a catch-up`,
body: names ? `Start with ${names}` : "Open Kin to see who",
},
trigger: {
type: Notifications.SchedulableTriggerInputTypes.DATE,
date: day,
channelId: "reminders",
},
});
}
}

69
app/src/lib/store.ts Normal file
View File

@@ -0,0 +1,69 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { api } from "./api";
import { scheduleDigest } from "./notifications";
import type { DuePerson, Person } from "./types";
// Read-cache store: renders instantly from AsyncStorage, refreshes from the
// API on focus/foreground. Writes go straight to the API (this app is a thin
// client over the VPS database) — screens call api.* then refresh().
export type State = {
due: DuePerson[] | null;
people: Person[] | null;
loading: boolean;
error: string | null;
lastSync: number | null;
};
let state: State = { due: null, people: null, loading: false, error: null, lastSync: null };
const listeners = new Set<() => void>();
const CACHE_KEY = "kin_cache_v1";
function emit(next: Partial<State>) {
state = { ...state, ...next };
for (const l of listeners) l();
}
export function getState() {
return state;
}
export function subscribe(l: () => void) {
listeners.add(l);
return () => {
listeners.delete(l);
};
}
let hydrated = false;
export async function hydrate() {
if (hydrated) return;
hydrated = true;
try {
const raw = await AsyncStorage.getItem(CACHE_KEY);
if (raw) {
const c = JSON.parse(raw) as Pick<State, "due" | "people" | "lastSync">;
emit({ due: c.due, people: c.people, lastSync: c.lastSync });
}
} catch {}
void refresh();
}
let inflight: Promise<void> | null = null;
export function refresh(): Promise<void> {
if (inflight) return inflight;
inflight = (async () => {
emit({ loading: true });
try {
const [due, people] = await Promise.all([api.due(), api.people()]);
emit({ due, people, error: null, loading: false, lastSync: Date.now() });
void AsyncStorage.setItem(CACHE_KEY, JSON.stringify({ due, people, lastSync: state.lastSync }));
void scheduleDigest(due);
} catch (e) {
emit({ loading: false, error: e instanceof Error ? e.message : "sync failed" });
} finally {
inflight = null;
}
})();
return inflight;
}

20
app/src/lib/theme.ts Normal file
View File

@@ -0,0 +1,20 @@
// Warm dark palette. Single source of truth for colors, imported as C.
export const C = {
bg: "#14110F",
surface: "#1D1916",
surface2: "#272220",
border: "#332D29",
text: "#F2EDE7",
muted: "#9C9088",
accent: "#E8747C", // warm rose — this is a people app
good: "#58B387",
warn: "#E5B458",
danger: "#E06060",
} as const;
export const STATUS_COLOR: Record<string, string> = {
overdue: C.danger,
due_soon: C.warn,
ok: C.good,
snoozed: C.muted,
};

66
app/src/lib/types.ts Normal file
View File

@@ -0,0 +1,66 @@
export type Person = {
id: string;
full_name: string;
first_name?: string | null;
last_name?: string | null;
email: string | null;
phone: string | null;
tags: string[];
notes?: string | null;
location: string | null;
source?: string | null;
cadence_days: number | null;
snoozed_until: string | null;
archived: boolean;
birthday: string | null;
last_contacted: string | null;
interaction_count: number;
created_at?: string;
updated_at?: string;
};
export type DueStatus = "overdue" | "due_soon" | "ok" | "snoozed";
export type DuePerson = Person & {
days_since: number;
urgency: number;
due_in_days: number;
snoozed: boolean;
status: DueStatus;
last_type: string | null;
};
export type Interaction = {
id: string;
type: string | null;
occurred_at: string;
summary: string | null;
notes: string | null;
};
export type Relationship = {
id: string;
type: string;
notes: string | null;
other_id: string;
other_name: string;
outgoing: boolean;
};
export type PersonDetail = Person & {
interactions: Interaction[];
relationships: Relationship[];
};
export const INTERACTION_TYPES = ["text", "call", "video", "hangout", "email", "other"] as const;
// Cadence presets shown in the picker. Label → days.
export const CADENCES: { label: string; days: number | null }[] = [
{ label: "Weekly", days: 7 },
{ label: "2 weeks", days: 14 },
{ label: "Monthly", days: 30 },
{ label: "2 months", days: 60 },
{ label: "Quarterly", days: 90 },
{ label: "6 months", days: 180 },
{ label: "None", days: null },
];

6
app/src/lib/useStore.ts Normal file
View File

@@ -0,0 +1,6 @@
import { useSyncExternalStore } from "react";
import { getState, subscribe, type State } from "./store";
export function useStore(): State {
return useSyncExternalStore(subscribe, getState, getState);
}