Local-first sync: on-device store + offline mutation queue, idempotent server upserts
All checks were successful
Build & Release APK / build (push) Successful in 10m54s
All checks were successful
Build & Release APK / build (push) Successful in 10m54s
Screens render synchronously from an AsyncStorage-backed store; every mutation applies locally and drains to the API in the background (last-write-wins, client-generated UUIDs). Sydney round-trips are off the interaction path and the app works fully offline. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
10
app/package-lock.json
generated
10
app/package-lock.json
generated
@@ -12,6 +12,7 @@
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
"expo": "~57.0.11",
|
||||
"expo-constants": "~57.0.9",
|
||||
"expo-crypto": "~57.0.1",
|
||||
"expo-device": "~57.0.1",
|
||||
"expo-font": "~57.0.1",
|
||||
"expo-glass-effect": "~57.0.1",
|
||||
@@ -3713,6 +3714,15 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-crypto": {
|
||||
"version": "57.0.1",
|
||||
"resolved": "https://registry.npmjs.org/expo-crypto/-/expo-crypto-57.0.1.tgz",
|
||||
"integrity": "sha512-xwegXQw3ATgeL1ZuqbSNrGzOeG+zNeh6Z6DSJk825Qpa3TEQQ1kG3ioE1p3g/SNF373BAVz2iBKUTSytlIbBRA==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-device": {
|
||||
"version": "57.0.1",
|
||||
"resolved": "https://registry.npmjs.org/expo-device/-/expo-device-57.0.1.tgz",
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
"expo": "~57.0.11",
|
||||
"expo-constants": "~57.0.9",
|
||||
"expo-crypto": "~57.0.1",
|
||||
"expo-device": "~57.0.1",
|
||||
"expo-font": "~57.0.1",
|
||||
"expo-glass-effect": "~57.0.1",
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { Link, Stack } from "expo-router";
|
||||
import { StatusBar } from "expo-status-bar";
|
||||
import { useEffect } from "react";
|
||||
import { AppState } from "react-native";
|
||||
import { hydrate, sync } from "../lib/store";
|
||||
import { C } from "../lib/theme";
|
||||
|
||||
export default function RootLayout() {
|
||||
useEffect(() => {
|
||||
void hydrate();
|
||||
// Re-sync whenever the app returns to the foreground.
|
||||
const sub = AppState.addEventListener("change", (s) => {
|
||||
if (s === "active") void sync();
|
||||
});
|
||||
return () => sub.remove();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatusBar style="light" />
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useFocusEffect, useRouter } from "expo-router";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
||||
import { api } from "../lib/api";
|
||||
import { activeProjects, createTask, tasksByStatus } from "../lib/store";
|
||||
import { C } from "../lib/theme";
|
||||
import type { Project, Task } from "../lib/types";
|
||||
import { useStore } from "../lib/useStore";
|
||||
|
||||
const Q = {
|
||||
next: { title: "Next up", color: "#3DBF77", bg: "#15301F", border: "#1E4D33" },
|
||||
@@ -25,10 +25,7 @@ function Quadrant({
|
||||
}) {
|
||||
const q = Q[kind];
|
||||
return (
|
||||
<Pressable
|
||||
style={[s.quad, { backgroundColor: q.bg, borderColor: q.border }]}
|
||||
onPress={onPress}
|
||||
>
|
||||
<Pressable style={[s.quad, { backgroundColor: q.bg, borderColor: q.border }]} onPress={onPress}>
|
||||
<View style={s.quadHead}>
|
||||
<Text style={[s.quadTitle, { color: q.color }]}>{q.title}</Text>
|
||||
<Text style={[s.quadCount, { color: q.color }]}>{count}</Text>
|
||||
@@ -44,42 +41,21 @@ function Quadrant({
|
||||
|
||||
export default function Home() {
|
||||
const router = useRouter();
|
||||
const [tasks, setTasks] = useState<Task[]>([]);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const store = useStore();
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const [ts, ps] = await Promise.all([api.tasks.list(), api.projects.list()]);
|
||||
setTasks(ts);
|
||||
setProjects(ps.filter((p) => p.status === "active"));
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, []);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
load();
|
||||
}, [load]),
|
||||
);
|
||||
|
||||
const capture = async () => {
|
||||
const capture = () => {
|
||||
const title = draft.trim();
|
||||
if (!title) return;
|
||||
setDraft("");
|
||||
try {
|
||||
await api.tasks.create({ title });
|
||||
} finally {
|
||||
load();
|
||||
}
|
||||
createTask({ title });
|
||||
};
|
||||
|
||||
const byStatus = (st: string) => tasks.filter((t) => t.status === st);
|
||||
const inboxCount = byStatus("inbox").length;
|
||||
const titles = (st: string) => byStatus(st).slice(0, 3).map((t) => t.title);
|
||||
const inbox = tasksByStatus(store, "inbox");
|
||||
const next = tasksByStatus(store, "next");
|
||||
const waiting = tasksByStatus(store, "waiting");
|
||||
const someday = tasksByStatus(store, "someday");
|
||||
const projects = activeProjects(store).filter((p) => p.status === "active");
|
||||
|
||||
return (
|
||||
<View style={s.screen}>
|
||||
@@ -95,22 +71,20 @@ export default function Home() {
|
||||
/>
|
||||
<Pressable style={s.inboxPill} onPress={() => router.push("/list/inbox")}>
|
||||
<Text style={s.inboxText}>📥 Inbox</Text>
|
||||
<Text style={[s.inboxText, { color: inboxCount ? C.text : C.muted }]}>{inboxCount}</Text>
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
|
||||
{store.pending > 0 && <Text style={s.pendingDot}>⇅ {store.pending}</Text>}
|
||||
<Text style={[s.inboxText, { color: inbox.length ? C.text : C.muted }]}>{inbox.length}</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
{error && <Text style={s.error}>{error}</Text>}
|
||||
{store.syncError && <Text style={s.error}>{store.syncError}</Text>}
|
||||
<View style={s.grid}>
|
||||
<View style={s.gridRow}>
|
||||
<Quadrant kind="next" count={byStatus("next").length} preview={titles("next")} onPress={() => router.push("/list/next")} />
|
||||
<Quadrant kind="waiting" count={byStatus("waiting").length} preview={titles("waiting")} onPress={() => router.push("/list/waiting")} />
|
||||
<Quadrant kind="next" count={next.length} preview={next.slice(0, 3).map((t) => t.title)} onPress={() => router.push("/list/next")} />
|
||||
<Quadrant kind="waiting" count={waiting.length} preview={waiting.slice(0, 3).map((t) => t.title)} onPress={() => router.push("/list/waiting")} />
|
||||
</View>
|
||||
<View style={s.gridRow}>
|
||||
<Quadrant kind="someday" count={byStatus("someday").length} preview={titles("someday")} onPress={() => router.push("/list/someday")} />
|
||||
<Quadrant
|
||||
kind="projects"
|
||||
count={projects.length}
|
||||
preview={projects.slice(0, 3).map((p) => p.name)}
|
||||
onPress={() => router.push("/projects")}
|
||||
/>
|
||||
<Quadrant kind="someday" count={someday.length} preview={someday.slice(0, 3).map((t) => t.title)} onPress={() => router.push("/list/someday")} />
|
||||
<Quadrant kind="projects" count={projects.length} preview={projects.slice(0, 3).map((p) => p.name)} onPress={() => router.push("/projects")} />
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
@@ -141,14 +115,10 @@ const s = StyleSheet.create({
|
||||
borderColor: C.border,
|
||||
},
|
||||
inboxText: { color: C.text, fontSize: 16, fontWeight: "600" },
|
||||
pendingDot: { color: C.muted, fontSize: 13 },
|
||||
grid: { flex: 1, marginTop: 10, gap: 10 },
|
||||
gridRow: { flex: 1, flexDirection: "row", gap: 10 },
|
||||
quad: {
|
||||
flex: 1,
|
||||
borderRadius: 16,
|
||||
borderWidth: 1,
|
||||
padding: 14,
|
||||
},
|
||||
quad: { flex: 1, borderRadius: 16, borderWidth: 1, padding: 14 },
|
||||
quadHead: { flexDirection: "row", justifyContent: "space-between", marginBottom: 8 },
|
||||
quadTitle: { fontSize: 17, fontWeight: "700" },
|
||||
quadCount: { fontSize: 17, fontWeight: "700" },
|
||||
|
||||
@@ -1,46 +1,32 @@
|
||||
import { Stack, useFocusEffect, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
||||
import { Button, Chips } from "../../components/ui";
|
||||
import { api } from "../../lib/api";
|
||||
import { createTask, dropProject, updateProject, updateTask } from "../../lib/store";
|
||||
import { C } from "../../lib/theme";
|
||||
import type { Project, ProjectStatus, Task } from "../../lib/types";
|
||||
import { useStore } from "../../lib/useStore";
|
||||
import type { ProjectStatus } from "../../lib/types";
|
||||
|
||||
const STATUSES: ProjectStatus[] = ["active", "someday", "completed"];
|
||||
|
||||
export default function ProjectDetail() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const [project, setProject] = useState<Project | null>(null);
|
||||
const [tasks, setTasks] = useState<Task[]>([]);
|
||||
const store = useStore();
|
||||
const [draft, setDraft] = useState("");
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const [ps, ts] = await Promise.all([api.projects.list(), api.tasks.list({ project_id: id })]);
|
||||
setProject(ps.find((p) => p.id === id) ?? null);
|
||||
setTasks(ts.filter((t) => t.status !== "done"));
|
||||
}, [id]);
|
||||
const project = store.projects.find((p) => p.id === id);
|
||||
if (!project) return <Text style={{ color: C.muted, margin: 16 }}>Project not found.</Text>;
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
load();
|
||||
}, [load]),
|
||||
);
|
||||
const tasks = store.tasks
|
||||
.filter((t) => t.project_id === id && t.status !== "done" && t.status !== "trashed")
|
||||
.sort((a, b) => a.sort_order - b.sort_order || b.created_at.localeCompare(a.created_at));
|
||||
|
||||
if (!project) return <Text style={{ color: C.muted, margin: 16 }}>Loading…</Text>;
|
||||
|
||||
const add = async () => {
|
||||
const add = () => {
|
||||
const title = draft.trim();
|
||||
if (!title) return;
|
||||
setDraft("");
|
||||
await api.tasks.create({ title, status: "next", project_id: id });
|
||||
load();
|
||||
};
|
||||
|
||||
const complete = async (t: Task) => {
|
||||
setTasks((cur) => cur.filter((x) => x.id !== t.id));
|
||||
await api.tasks.update(t.id, { status: "done" });
|
||||
load();
|
||||
createTask({ title, status: "next", project_id: id });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -51,10 +37,7 @@ export default function ProjectDetail() {
|
||||
label="Status"
|
||||
options={STATUSES}
|
||||
value={project.status}
|
||||
onChange={async (status) => {
|
||||
setProject({ ...project, status });
|
||||
await api.projects.update(project.id, { status });
|
||||
}}
|
||||
onChange={(status) => updateProject(project.id, { status })}
|
||||
/>
|
||||
</View>
|
||||
<TextInput
|
||||
@@ -64,6 +47,7 @@ export default function ProjectDetail() {
|
||||
value={draft}
|
||||
onChangeText={setDraft}
|
||||
onSubmitEditing={add}
|
||||
submitBehavior="submit"
|
||||
returnKeyType="done"
|
||||
/>
|
||||
<FlatList
|
||||
@@ -71,7 +55,11 @@ export default function ProjectDetail() {
|
||||
keyExtractor={(t) => t.id}
|
||||
renderItem={({ item }) => (
|
||||
<Pressable style={s.row} onPress={() => router.push(`/task/${item.id}`)}>
|
||||
<Pressable style={s.checkbox} hitSlop={10} onPress={() => complete(item)} />
|
||||
<Pressable
|
||||
style={s.checkbox}
|
||||
hitSlop={10}
|
||||
onPress={() => updateTask(item.id, { status: "done" })}
|
||||
/>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={s.title}>{item.title}</Text>
|
||||
<Text style={s.meta}>{[item.status, item.context].filter(Boolean).join(" · ")}</Text>
|
||||
@@ -84,8 +72,8 @@ export default function ProjectDetail() {
|
||||
<Button
|
||||
title="Drop project"
|
||||
danger
|
||||
onPress={async () => {
|
||||
await api.projects.drop(project.id);
|
||||
onPress={() => {
|
||||
dropProject(project.id);
|
||||
router.back();
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,37 +1,21 @@
|
||||
import { useFocusEffect, useRouter } from "expo-router";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
||||
import { api } from "../lib/api";
|
||||
import { activeProjects, createProject, openTaskCount } from "../lib/store";
|
||||
import { C } from "../lib/theme";
|
||||
import type { Project } from "../lib/types";
|
||||
import { useStore } from "../lib/useStore";
|
||||
|
||||
export default function Projects() {
|
||||
const router = useRouter();
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const store = useStore();
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const projects = activeProjects(store);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setProjects(await api.projects.list());
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, []);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
load();
|
||||
}, [load]),
|
||||
);
|
||||
|
||||
const add = async () => {
|
||||
const add = () => {
|
||||
const name = draft.trim();
|
||||
if (!name) return;
|
||||
setDraft("");
|
||||
await api.projects.create({ name });
|
||||
load();
|
||||
createProject({ name });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -45,7 +29,6 @@ export default function Projects() {
|
||||
onSubmitEditing={add}
|
||||
returnKeyType="done"
|
||||
/>
|
||||
{error && <Text style={s.error}>{error}</Text>}
|
||||
<FlatList
|
||||
data={projects}
|
||||
keyExtractor={(p) => p.id}
|
||||
@@ -54,8 +37,7 @@ export default function Projects() {
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={s.title}>{item.name}</Text>
|
||||
<Text style={s.meta}>
|
||||
{item.status}
|
||||
{item.open_tasks != null && ` · ${item.open_tasks} open`}
|
||||
{item.status} · {openTaskCount(store, item.id)} open
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={{ color: C.muted }}>›</Text>
|
||||
@@ -91,5 +73,4 @@ const s = StyleSheet.create({
|
||||
title: { color: C.text, fontSize: 16 },
|
||||
meta: { color: C.muted, fontSize: 13, marginTop: 2 },
|
||||
empty: { color: C.muted, textAlign: "center", marginTop: 48 },
|
||||
error: { color: C.danger, marginHorizontal: 16, marginTop: 8 },
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ScrollView, Text } from "react-native";
|
||||
import { Button, Field } from "../components/ui";
|
||||
import { api } from "../lib/api";
|
||||
import { DEFAULT_URL, getConfig, setConfig } from "../lib/config";
|
||||
import { sync } from "../lib/store";
|
||||
import { C } from "../lib/theme";
|
||||
|
||||
export default function Settings() {
|
||||
@@ -23,6 +24,7 @@ export default function Settings() {
|
||||
await setConfig(url, token);
|
||||
try {
|
||||
await api.tasks.list({ status: "inbox" });
|
||||
void sync();
|
||||
router.back();
|
||||
} catch (e) {
|
||||
setStatus(`Connection failed: ${e instanceof Error ? e.message : e}`);
|
||||
|
||||
@@ -1,109 +1,100 @@
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { ScrollView, Text } from "react-native";
|
||||
import { Button, Chips, Field } from "../../components/ui";
|
||||
import { api } from "../../lib/api";
|
||||
import { activeProjects, trashTask, updateTask } from "../../lib/store";
|
||||
import { C } from "../../lib/theme";
|
||||
import type { Project, Task, TaskStatus } from "../../lib/types";
|
||||
import { useStore } from "../../lib/useStore";
|
||||
import type { Task, TaskStatus } from "../../lib/types";
|
||||
|
||||
const STATUSES: TaskStatus[] = ["inbox", "next", "waiting", "scheduled", "someday", "done"];
|
||||
|
||||
export default function TaskDetail() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const [task, setTask] = useState<Task | null>(null);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const store = useStore();
|
||||
const original = store.tasks.find((t) => t.id === id);
|
||||
// Draft is local to the screen; nothing is written until Save.
|
||||
const [draft, setDraft] = useState<Task | null>(original ?? null);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([api.tasks.get(id), api.projects.list()])
|
||||
.then(([t, ps]) => {
|
||||
setTask(t);
|
||||
setProjects(ps.filter((p) => p.status === "active" || p.id === t.project_id));
|
||||
})
|
||||
.catch((e) => setError(e instanceof Error ? e.message : String(e)));
|
||||
}, [id]);
|
||||
if (!draft) return <Text style={{ color: C.muted, margin: 16 }}>Task not found.</Text>;
|
||||
|
||||
if (error) return <Text style={{ color: C.danger, margin: 16 }}>{error}</Text>;
|
||||
if (!task) return <Text style={{ color: C.muted, margin: 16 }}>Loading…</Text>;
|
||||
const set = (patch: Partial<Task>) => setDraft({ ...draft, ...patch });
|
||||
|
||||
const set = (patch: Partial<Task>) => setTask({ ...task, ...patch });
|
||||
|
||||
const save = async () => {
|
||||
try {
|
||||
await api.tasks.update(task.id, {
|
||||
title: task.title,
|
||||
notes: task.notes,
|
||||
status: task.status,
|
||||
project_id: task.project_id,
|
||||
context: task.context,
|
||||
waiting_for: task.waiting_for,
|
||||
due_date: task.due_date,
|
||||
defer_date: task.defer_date,
|
||||
});
|
||||
router.back();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
const trash = async () => {
|
||||
await api.tasks.trash(task.id);
|
||||
const save = () => {
|
||||
updateTask(draft.id, {
|
||||
title: draft.title,
|
||||
notes: draft.notes,
|
||||
status: draft.status,
|
||||
project_id: draft.project_id,
|
||||
context: draft.context,
|
||||
waiting_for: draft.waiting_for,
|
||||
due_date: draft.due_date,
|
||||
defer_date: draft.defer_date,
|
||||
});
|
||||
router.back();
|
||||
};
|
||||
|
||||
const projects = activeProjects(store).filter((p) => p.status === "active" || p.id === draft.project_id);
|
||||
const projectOptions = ["none", ...projects.map((p) => p.id)];
|
||||
const projectLabels = Object.fromEntries([["none", "None"], ...projects.map((p) => [p.id, p.name])]);
|
||||
|
||||
return (
|
||||
<ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={{ padding: 16 }}>
|
||||
<Field label="Title" value={task.title} onChangeText={(v) => set({ title: v })} />
|
||||
<Chips label="List" options={STATUSES} value={task.status} onChange={(status) => set({ status })} />
|
||||
<Field label="Title" value={draft.title} onChangeText={(v) => set({ title: v })} />
|
||||
<Chips label="List" options={STATUSES} value={draft.status} onChange={(status) => set({ status })} />
|
||||
<Chips
|
||||
label="Project"
|
||||
options={projectOptions}
|
||||
labels={projectLabels}
|
||||
value={task.project_id ?? "none"}
|
||||
value={draft.project_id ?? "none"}
|
||||
onChange={(v) => set({ project_id: v === "none" ? null : v })}
|
||||
/>
|
||||
<Field
|
||||
label="Context"
|
||||
value={task.context ?? ""}
|
||||
value={draft.context ?? ""}
|
||||
onChangeText={(v) => set({ context: v || null })}
|
||||
placeholder="@home, @computer, @errands…"
|
||||
autoCapitalize="none"
|
||||
/>
|
||||
{task.status === "waiting" && (
|
||||
{draft.status === "waiting" && (
|
||||
<Field
|
||||
label="Waiting for"
|
||||
value={task.waiting_for ?? ""}
|
||||
value={draft.waiting_for ?? ""}
|
||||
onChangeText={(v) => set({ waiting_for: v || null })}
|
||||
placeholder="Who or what?"
|
||||
/>
|
||||
)}
|
||||
<Field
|
||||
label="Due date"
|
||||
value={task.due_date ?? ""}
|
||||
value={draft.due_date ?? ""}
|
||||
onChangeText={(v) => set({ due_date: v || null })}
|
||||
placeholder="YYYY-MM-DD"
|
||||
autoCapitalize="none"
|
||||
/>
|
||||
<Field
|
||||
label="Defer until"
|
||||
value={task.defer_date ?? ""}
|
||||
value={draft.defer_date ?? ""}
|
||||
onChangeText={(v) => set({ defer_date: v || null })}
|
||||
placeholder="YYYY-MM-DD"
|
||||
autoCapitalize="none"
|
||||
/>
|
||||
<Field
|
||||
label="Notes"
|
||||
value={task.notes}
|
||||
value={draft.notes}
|
||||
onChangeText={(v) => set({ notes: v })}
|
||||
multiline
|
||||
style={{ minHeight: 80, textAlignVertical: "top" }}
|
||||
/>
|
||||
<Button title="Save" onPress={save} />
|
||||
<Button title="Delete" onPress={trash} danger />
|
||||
<Button
|
||||
title="Delete"
|
||||
danger
|
||||
onPress={() => {
|
||||
trashTask(draft.id);
|
||||
router.back();
|
||||
}}
|
||||
/>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useFocusEffect, useRouter } from "expo-router";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
FlatList,
|
||||
Pressable,
|
||||
@@ -9,18 +9,23 @@ import {
|
||||
TextInput,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { api } from "../lib/api";
|
||||
import { createTask, sync, tasksByStatus, updateTask } from "../lib/store";
|
||||
import { C } from "../lib/theme";
|
||||
import { useStore } from "../lib/useStore";
|
||||
import type { Task, TaskStatus } from "../lib/types";
|
||||
|
||||
function TaskRow({ task, onToggle }: { task: Task; onToggle: (t: Task) => void }) {
|
||||
function TaskRow({ task, listStatus }: { task: Task; listStatus: TaskStatus }) {
|
||||
const router = useRouter();
|
||||
const meta = [task.context, task.waiting_for && `→ ${task.waiting_for}`, task.due_date && `due ${task.due_date}`]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
return (
|
||||
<Pressable style={s.row} onPress={() => router.push(`/task/${task.id}`)}>
|
||||
<Pressable style={s.checkbox} hitSlop={10} onPress={() => onToggle(task)}>
|
||||
<Pressable
|
||||
style={s.checkbox}
|
||||
hitSlop={10}
|
||||
onPress={() => updateTask(task.id, { status: task.status === "done" ? listStatus : "done" })}
|
||||
>
|
||||
{task.status === "done" && <View style={s.checkboxFill} />}
|
||||
</Pressable>
|
||||
<View style={{ flex: 1 }}>
|
||||
@@ -42,46 +47,16 @@ export default function TaskListScreen({
|
||||
capture?: boolean;
|
||||
emptyHint: string;
|
||||
}) {
|
||||
const [tasks, setTasks] = useState<Task[]>([]);
|
||||
const store = useStore();
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState("");
|
||||
const tasks = tasksByStatus(store, status);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setTasks(await api.tasks.list({ status }));
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
load();
|
||||
}, [load]),
|
||||
);
|
||||
|
||||
const add = async () => {
|
||||
const add = () => {
|
||||
const title = draft.trim();
|
||||
if (!title) return;
|
||||
setDraft("");
|
||||
setTasks((cur) => [{ id: `tmp-${title}`, title, status } as Task, ...cur]);
|
||||
try {
|
||||
await api.tasks.create({ title, status });
|
||||
} finally {
|
||||
load();
|
||||
}
|
||||
};
|
||||
|
||||
const toggle = async (task: Task) => {
|
||||
const done = task.status !== "done";
|
||||
setTasks((cur) => cur.filter((t) => t.id !== task.id));
|
||||
try {
|
||||
await api.tasks.update(task.id, { status: done ? "done" : status });
|
||||
} finally {
|
||||
load();
|
||||
}
|
||||
createTask({ title, status });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -98,18 +73,17 @@ export default function TaskListScreen({
|
||||
returnKeyType="done"
|
||||
/>
|
||||
)}
|
||||
{error && <Text style={s.error}>{error}</Text>}
|
||||
<FlatList
|
||||
data={tasks}
|
||||
keyExtractor={(t) => t.id}
|
||||
renderItem={({ item }) => <TaskRow task={item} onToggle={toggle} />}
|
||||
renderItem={({ item }) => <TaskRow task={item} listStatus={status} />}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={refreshing}
|
||||
tintColor={C.muted}
|
||||
onRefresh={async () => {
|
||||
setRefreshing(true);
|
||||
await load();
|
||||
await sync();
|
||||
setRefreshing(false);
|
||||
}}
|
||||
/>
|
||||
@@ -156,5 +130,4 @@ const s = StyleSheet.create({
|
||||
title: { color: C.text, fontSize: 16 },
|
||||
meta: { color: C.muted, fontSize: 13, marginTop: 2 },
|
||||
empty: { color: C.muted, textAlign: "center", marginTop: 48, fontSize: 15 },
|
||||
error: { color: C.danger, marginHorizontal: 16, marginTop: 8 },
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ export const api = {
|
||||
return req<Task[]>(`/v1/tasks${q ? `?${q}` : ""}`);
|
||||
},
|
||||
get: (id: string) => req<Task>(`/v1/tasks/${id}`),
|
||||
create: (data: Partial<Task> & { title: string }) =>
|
||||
create: (data: Partial<Task> & { title: string; id?: string }) =>
|
||||
req<Task>("/v1/tasks", { method: "POST", body: JSON.stringify(data) }),
|
||||
update: (id: string, data: Partial<Task>) =>
|
||||
req<Task>(`/v1/tasks/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
@@ -42,7 +42,7 @@ export const api = {
|
||||
},
|
||||
projects: {
|
||||
list: () => req<Project[]>("/v1/projects"),
|
||||
create: (data: Partial<Project> & { name: string }) =>
|
||||
create: (data: Partial<Project> & { name: string; id?: string }) =>
|
||||
req<Project>("/v1/projects", { method: "POST", body: JSON.stringify(data) }),
|
||||
update: (id: string, data: Partial<Project>) =>
|
||||
req<Project>(`/v1/projects/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
|
||||
254
app/src/lib/store.ts
Normal file
254
app/src/lib/store.ts
Normal file
@@ -0,0 +1,254 @@
|
||||
// Local-first store — the single source of truth for the UI.
|
||||
//
|
||||
// Screens render synchronously from the in-memory state (hydrated from
|
||||
// AsyncStorage at launch). Mutations apply locally immediately and enqueue an
|
||||
// op; a background worker drains the queue to the API and then pulls the
|
||||
// server state, so the network is never on the interaction path. Single-user
|
||||
// last-write-wins: rows with queued local ops keep their local version during
|
||||
// a pull; everything else takes the server's.
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import * as Crypto from "expo-crypto";
|
||||
import { api } from "./api";
|
||||
import { getConfig } from "./config";
|
||||
import type { Project, Task } from "./types";
|
||||
|
||||
export interface State {
|
||||
tasks: Task[];
|
||||
projects: Project[];
|
||||
hydrated: boolean;
|
||||
syncing: boolean;
|
||||
pending: number;
|
||||
syncError: string | null;
|
||||
}
|
||||
|
||||
type Op =
|
||||
| { kind: "task.create" | "task.update"; id: string; data: Partial<Task> }
|
||||
| { kind: "project.create" | "project.update"; id: string; data: Partial<Project> };
|
||||
|
||||
const DATA_KEY = "store_v1";
|
||||
const QUEUE_KEY = "queue_v1";
|
||||
|
||||
let state: State = {
|
||||
tasks: [],
|
||||
projects: [],
|
||||
hydrated: false,
|
||||
syncing: false,
|
||||
pending: 0,
|
||||
syncError: null,
|
||||
};
|
||||
let queue: Op[] = [];
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export function getState(): State {
|
||||
return state;
|
||||
}
|
||||
|
||||
export function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
function setState(patch: Partial<State>) {
|
||||
state = { ...state, ...patch, pending: queue.length };
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
function persistData() {
|
||||
void AsyncStorage.setItem(DATA_KEY, JSON.stringify({ tasks: state.tasks, projects: state.projects }));
|
||||
}
|
||||
|
||||
function persistQueue() {
|
||||
void AsyncStorage.setItem(QUEUE_KEY, JSON.stringify(queue));
|
||||
}
|
||||
|
||||
export async function hydrate() {
|
||||
if (state.hydrated) return;
|
||||
const [data, q] = await Promise.all([AsyncStorage.getItem(DATA_KEY), AsyncStorage.getItem(QUEUE_KEY)]);
|
||||
if (q) queue = JSON.parse(q);
|
||||
const parsed = data ? JSON.parse(data) : { tasks: [], projects: [] };
|
||||
setState({ tasks: parsed.tasks, projects: parsed.projects, hydrated: true });
|
||||
void sync();
|
||||
}
|
||||
|
||||
// ---- mutations (instant; network happens later) ----
|
||||
|
||||
function now() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
// Fields the API accepts — everything else (timestamps, completed_at) is local
|
||||
// bookkeeping until the server's authoritative row arrives via pull().
|
||||
const TASK_FIELDS = ["title", "notes", "status", "project_id", "context", "waiting_for", "due_date", "defer_date", "sort_order"] as const;
|
||||
const PROJECT_FIELDS = ["name", "status", "notes", "sort_order"] as const;
|
||||
|
||||
function pickFields<T>(data: Partial<T>, fields: readonly (keyof T & string)[]): Partial<T> {
|
||||
const out: Partial<T> = {};
|
||||
for (const f of fields) if (f in data) out[f] = data[f];
|
||||
return out;
|
||||
}
|
||||
|
||||
function enqueue(op: Op) {
|
||||
// Coalesce consecutive updates to the same row into one op.
|
||||
const last = queue[queue.length - 1];
|
||||
if (last && op.kind === last.kind && op.kind.endsWith("update") && last.id === op.id) {
|
||||
last.data = { ...last.data, ...op.data };
|
||||
} else {
|
||||
queue.push(op);
|
||||
}
|
||||
persistQueue();
|
||||
setState({});
|
||||
void sync();
|
||||
}
|
||||
|
||||
export function createTask(data: Partial<Task> & { title: string }): Task {
|
||||
const task: Task = {
|
||||
id: Crypto.randomUUID(),
|
||||
title: data.title,
|
||||
notes: data.notes ?? "",
|
||||
status: data.status ?? "inbox",
|
||||
project_id: data.project_id ?? null,
|
||||
context: data.context ?? null,
|
||||
waiting_for: data.waiting_for ?? null,
|
||||
due_date: data.due_date ?? null,
|
||||
defer_date: data.defer_date ?? null,
|
||||
completed_at: null,
|
||||
sort_order: data.sort_order ?? 0,
|
||||
created_at: now(),
|
||||
updated_at: now(),
|
||||
};
|
||||
setState({ tasks: [task, ...state.tasks] });
|
||||
persistData();
|
||||
enqueue({ kind: "task.create", id: task.id, data: pickFields(task, TASK_FIELDS) });
|
||||
return task;
|
||||
}
|
||||
|
||||
export function updateTask(id: string, patch: Partial<Task>) {
|
||||
setState({
|
||||
tasks: state.tasks.map((t) => {
|
||||
if (t.id !== id) return t;
|
||||
const next = { ...t, ...patch, updated_at: now() };
|
||||
// Mirror the server's completed_at rule so the UI is right pre-sync.
|
||||
next.completed_at = next.status === "done" ? (t.completed_at ?? now()) : null;
|
||||
return next;
|
||||
}),
|
||||
});
|
||||
persistData();
|
||||
enqueue({ kind: "task.update", id, data: pickFields(patch, TASK_FIELDS) });
|
||||
}
|
||||
|
||||
export function trashTask(id: string) {
|
||||
updateTask(id, { status: "trashed" });
|
||||
}
|
||||
|
||||
export function createProject(data: Partial<Project> & { name: string }): Project {
|
||||
const project: Project = {
|
||||
id: Crypto.randomUUID(),
|
||||
name: data.name,
|
||||
status: data.status ?? "active",
|
||||
notes: data.notes ?? "",
|
||||
sort_order: data.sort_order ?? 0,
|
||||
created_at: now(),
|
||||
updated_at: now(),
|
||||
};
|
||||
setState({ projects: [project, ...state.projects] });
|
||||
persistData();
|
||||
enqueue({ kind: "project.create", id: project.id, data: pickFields(project, PROJECT_FIELDS) });
|
||||
return project;
|
||||
}
|
||||
|
||||
export function updateProject(id: string, patch: Partial<Project>) {
|
||||
setState({ projects: state.projects.map((p) => (p.id === id ? { ...p, ...patch, updated_at: now() } : p)) });
|
||||
persistData();
|
||||
enqueue({ kind: "project.update", id, data: pickFields(patch, PROJECT_FIELDS) });
|
||||
}
|
||||
|
||||
export function dropProject(id: string) {
|
||||
updateProject(id, { status: "dropped" });
|
||||
}
|
||||
|
||||
// ---- sync ----
|
||||
|
||||
let syncRunning = false;
|
||||
let syncAgain = false;
|
||||
|
||||
export async function sync() {
|
||||
if (syncRunning) {
|
||||
syncAgain = true;
|
||||
return;
|
||||
}
|
||||
const { token } = await getConfig();
|
||||
if (!token) return;
|
||||
syncRunning = true;
|
||||
setState({ syncing: true });
|
||||
try {
|
||||
while (queue.length) {
|
||||
await push(queue[0]);
|
||||
queue.shift();
|
||||
persistQueue();
|
||||
setState({});
|
||||
}
|
||||
await pull();
|
||||
setState({ syncError: null });
|
||||
} catch (e) {
|
||||
setState({ syncError: e instanceof Error ? e.message : String(e) });
|
||||
} finally {
|
||||
syncRunning = false;
|
||||
setState({ syncing: false });
|
||||
if (syncAgain) {
|
||||
syncAgain = false;
|
||||
void sync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function push(op: Op) {
|
||||
try {
|
||||
if (op.kind === "task.create") await api.tasks.create({ id: op.id, ...op.data } as never);
|
||||
else if (op.kind === "task.update") await api.tasks.update(op.id, op.data as Partial<Task>);
|
||||
else if (op.kind === "project.create") await api.projects.create({ id: op.id, ...op.data } as never);
|
||||
else await api.projects.update(op.id, op.data as Partial<Project>);
|
||||
} catch (e) {
|
||||
// 4xx (bad data, row gone) would poison the queue forever — drop the op.
|
||||
// Anything else (offline, 5xx) rethrows and we retry on the next sync.
|
||||
const status = (e as { status?: number }).status;
|
||||
if (status && status >= 400 && status < 500 && status !== 401) return;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function pull() {
|
||||
const [tasks, projects] = await Promise.all([api.tasks.list(), api.projects.list()]);
|
||||
// Rows with ops still queued keep their local version; the next sync pass
|
||||
// pushes those ops and then this merge converges to the server state.
|
||||
const dirty = new Set(queue.map((o) => o.id));
|
||||
const keepLocal = <T extends { id: string }>(local: T[], server: T[]) => {
|
||||
const serverIds = new Set(server.map((r) => r.id));
|
||||
return [
|
||||
...server.map((r) => (dirty.has(r.id) ? local.find((l) => l.id === r.id) ?? r : r)),
|
||||
...local.filter((l) => dirty.has(l.id) && !serverIds.has(l.id)),
|
||||
];
|
||||
};
|
||||
setState({
|
||||
tasks: keepLocal(state.tasks, tasks),
|
||||
projects: keepLocal(state.projects, projects),
|
||||
});
|
||||
persistData();
|
||||
}
|
||||
|
||||
// ---- selectors ----
|
||||
|
||||
export function tasksByStatus(s: State, status: Task["status"]): Task[] {
|
||||
return s.tasks
|
||||
.filter((t) => t.status === status)
|
||||
.sort((a, b) => a.sort_order - b.sort_order || b.created_at.localeCompare(a.created_at));
|
||||
}
|
||||
|
||||
export function activeProjects(s: State): Project[] {
|
||||
return s.projects
|
||||
.filter((p) => p.status !== "dropped")
|
||||
.sort((a, b) => a.sort_order - b.sort_order || b.created_at.localeCompare(a.created_at));
|
||||
}
|
||||
|
||||
export function openTaskCount(s: State, projectId: string): number {
|
||||
return s.tasks.filter((t) => t.project_id === projectId && t.status !== "done" && t.status !== "trashed").length;
|
||||
}
|
||||
8
app/src/lib/useStore.ts
Normal file
8
app/src/lib/useStore.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { getState, subscribe, type State } from "./store";
|
||||
|
||||
// Subscribe a component to the local-first store. The whole state object is
|
||||
// the snapshot (replaced immutably on every change), so derive lists inline.
|
||||
export function useStore(): State {
|
||||
return useSyncExternalStore(subscribe, getState, getState);
|
||||
}
|
||||
Reference in New Issue
Block a user