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",
|
"@react-native-async-storage/async-storage": "2.2.0",
|
||||||
"expo": "~57.0.11",
|
"expo": "~57.0.11",
|
||||||
"expo-constants": "~57.0.9",
|
"expo-constants": "~57.0.9",
|
||||||
|
"expo-crypto": "~57.0.1",
|
||||||
"expo-device": "~57.0.1",
|
"expo-device": "~57.0.1",
|
||||||
"expo-font": "~57.0.1",
|
"expo-font": "~57.0.1",
|
||||||
"expo-glass-effect": "~57.0.1",
|
"expo-glass-effect": "~57.0.1",
|
||||||
@@ -3713,6 +3714,15 @@
|
|||||||
"react-native": "*"
|
"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": {
|
"node_modules/expo-device": {
|
||||||
"version": "57.0.1",
|
"version": "57.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/expo-device/-/expo-device-57.0.1.tgz",
|
"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",
|
"@react-native-async-storage/async-storage": "2.2.0",
|
||||||
"expo": "~57.0.11",
|
"expo": "~57.0.11",
|
||||||
"expo-constants": "~57.0.9",
|
"expo-constants": "~57.0.9",
|
||||||
|
"expo-crypto": "~57.0.1",
|
||||||
"expo-device": "~57.0.1",
|
"expo-device": "~57.0.1",
|
||||||
"expo-font": "~57.0.1",
|
"expo-font": "~57.0.1",
|
||||||
"expo-glass-effect": "~57.0.1",
|
"expo-glass-effect": "~57.0.1",
|
||||||
|
|||||||
@@ -1,8 +1,20 @@
|
|||||||
import { Link, Stack } from "expo-router";
|
import { Link, Stack } from "expo-router";
|
||||||
import { StatusBar } from "expo-status-bar";
|
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";
|
import { C } from "../lib/theme";
|
||||||
|
|
||||||
export default function RootLayout() {
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<StatusBar style="light" />
|
<StatusBar style="light" />
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useFocusEffect, useRouter } from "expo-router";
|
import { useRouter } from "expo-router";
|
||||||
import { useCallback, useState } from "react";
|
import { useState } from "react";
|
||||||
import { Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
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 { C } from "../lib/theme";
|
||||||
import type { Project, Task } from "../lib/types";
|
import { useStore } from "../lib/useStore";
|
||||||
|
|
||||||
const Q = {
|
const Q = {
|
||||||
next: { title: "Next up", color: "#3DBF77", bg: "#15301F", border: "#1E4D33" },
|
next: { title: "Next up", color: "#3DBF77", bg: "#15301F", border: "#1E4D33" },
|
||||||
@@ -25,10 +25,7 @@ function Quadrant({
|
|||||||
}) {
|
}) {
|
||||||
const q = Q[kind];
|
const q = Q[kind];
|
||||||
return (
|
return (
|
||||||
<Pressable
|
<Pressable style={[s.quad, { backgroundColor: q.bg, borderColor: q.border }]} onPress={onPress}>
|
||||||
style={[s.quad, { backgroundColor: q.bg, borderColor: q.border }]}
|
|
||||||
onPress={onPress}
|
|
||||||
>
|
|
||||||
<View style={s.quadHead}>
|
<View style={s.quadHead}>
|
||||||
<Text style={[s.quadTitle, { color: q.color }]}>{q.title}</Text>
|
<Text style={[s.quadTitle, { color: q.color }]}>{q.title}</Text>
|
||||||
<Text style={[s.quadCount, { color: q.color }]}>{count}</Text>
|
<Text style={[s.quadCount, { color: q.color }]}>{count}</Text>
|
||||||
@@ -44,42 +41,21 @@ function Quadrant({
|
|||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
const store = useStore();
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
|
||||||
const [draft, setDraft] = useState("");
|
const [draft, setDraft] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const capture = () => {
|
||||||
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 title = draft.trim();
|
const title = draft.trim();
|
||||||
if (!title) return;
|
if (!title) return;
|
||||||
setDraft("");
|
setDraft("");
|
||||||
try {
|
createTask({ title });
|
||||||
await api.tasks.create({ title });
|
|
||||||
} finally {
|
|
||||||
load();
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const byStatus = (st: string) => tasks.filter((t) => t.status === st);
|
const inbox = tasksByStatus(store, "inbox");
|
||||||
const inboxCount = byStatus("inbox").length;
|
const next = tasksByStatus(store, "next");
|
||||||
const titles = (st: string) => byStatus(st).slice(0, 3).map((t) => t.title);
|
const waiting = tasksByStatus(store, "waiting");
|
||||||
|
const someday = tasksByStatus(store, "someday");
|
||||||
|
const projects = activeProjects(store).filter((p) => p.status === "active");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={s.screen}>
|
<View style={s.screen}>
|
||||||
@@ -95,22 +71,20 @@ export default function Home() {
|
|||||||
/>
|
/>
|
||||||
<Pressable style={s.inboxPill} onPress={() => router.push("/list/inbox")}>
|
<Pressable style={s.inboxPill} onPress={() => router.push("/list/inbox")}>
|
||||||
<Text style={s.inboxText}>📥 Inbox</Text>
|
<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>
|
</Pressable>
|
||||||
{error && <Text style={s.error}>{error}</Text>}
|
{store.syncError && <Text style={s.error}>{store.syncError}</Text>}
|
||||||
<View style={s.grid}>
|
<View style={s.grid}>
|
||||||
<View style={s.gridRow}>
|
<View style={s.gridRow}>
|
||||||
<Quadrant kind="next" count={byStatus("next").length} preview={titles("next")} onPress={() => router.push("/list/next")} />
|
<Quadrant kind="next" count={next.length} preview={next.slice(0, 3).map((t) => t.title)} onPress={() => router.push("/list/next")} />
|
||||||
<Quadrant kind="waiting" count={byStatus("waiting").length} preview={titles("waiting")} onPress={() => router.push("/list/waiting")} />
|
<Quadrant kind="waiting" count={waiting.length} preview={waiting.slice(0, 3).map((t) => t.title)} onPress={() => router.push("/list/waiting")} />
|
||||||
</View>
|
</View>
|
||||||
<View style={s.gridRow}>
|
<View style={s.gridRow}>
|
||||||
<Quadrant kind="someday" count={byStatus("someday").length} preview={titles("someday")} onPress={() => router.push("/list/someday")} />
|
<Quadrant kind="someday" count={someday.length} preview={someday.slice(0, 3).map((t) => t.title)} onPress={() => router.push("/list/someday")} />
|
||||||
<Quadrant
|
<Quadrant kind="projects" count={projects.length} preview={projects.slice(0, 3).map((p) => p.name)} onPress={() => router.push("/projects")} />
|
||||||
kind="projects"
|
|
||||||
count={projects.length}
|
|
||||||
preview={projects.slice(0, 3).map((p) => p.name)}
|
|
||||||
onPress={() => router.push("/projects")}
|
|
||||||
/>
|
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
@@ -141,14 +115,10 @@ const s = StyleSheet.create({
|
|||||||
borderColor: C.border,
|
borderColor: C.border,
|
||||||
},
|
},
|
||||||
inboxText: { color: C.text, fontSize: 16, fontWeight: "600" },
|
inboxText: { color: C.text, fontSize: 16, fontWeight: "600" },
|
||||||
|
pendingDot: { color: C.muted, fontSize: 13 },
|
||||||
grid: { flex: 1, marginTop: 10, gap: 10 },
|
grid: { flex: 1, marginTop: 10, gap: 10 },
|
||||||
gridRow: { flex: 1, flexDirection: "row", gap: 10 },
|
gridRow: { flex: 1, flexDirection: "row", gap: 10 },
|
||||||
quad: {
|
quad: { flex: 1, borderRadius: 16, borderWidth: 1, padding: 14 },
|
||||||
flex: 1,
|
|
||||||
borderRadius: 16,
|
|
||||||
borderWidth: 1,
|
|
||||||
padding: 14,
|
|
||||||
},
|
|
||||||
quadHead: { flexDirection: "row", justifyContent: "space-between", marginBottom: 8 },
|
quadHead: { flexDirection: "row", justifyContent: "space-between", marginBottom: 8 },
|
||||||
quadTitle: { fontSize: 17, fontWeight: "700" },
|
quadTitle: { fontSize: 17, fontWeight: "700" },
|
||||||
quadCount: { fontSize: 17, fontWeight: "700" },
|
quadCount: { fontSize: 17, fontWeight: "700" },
|
||||||
|
|||||||
@@ -1,46 +1,32 @@
|
|||||||
import { Stack, useFocusEffect, useLocalSearchParams, useRouter } from "expo-router";
|
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||||
import { useCallback, useState } from "react";
|
import { useState } from "react";
|
||||||
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
||||||
import { Button, Chips } from "../../components/ui";
|
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 { 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"];
|
const STATUSES: ProjectStatus[] = ["active", "someday", "completed"];
|
||||||
|
|
||||||
export default function ProjectDetail() {
|
export default function ProjectDetail() {
|
||||||
const { id } = useLocalSearchParams<{ id: string }>();
|
const { id } = useLocalSearchParams<{ id: string }>();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [project, setProject] = useState<Project | null>(null);
|
const store = useStore();
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
|
||||||
const [draft, setDraft] = useState("");
|
const [draft, setDraft] = useState("");
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const project = store.projects.find((p) => p.id === id);
|
||||||
const [ps, ts] = await Promise.all([api.projects.list(), api.tasks.list({ project_id: id })]);
|
if (!project) return <Text style={{ color: C.muted, margin: 16 }}>Project not found.</Text>;
|
||||||
setProject(ps.find((p) => p.id === id) ?? null);
|
|
||||||
setTasks(ts.filter((t) => t.status !== "done"));
|
|
||||||
}, [id]);
|
|
||||||
|
|
||||||
useFocusEffect(
|
const tasks = store.tasks
|
||||||
useCallback(() => {
|
.filter((t) => t.project_id === id && t.status !== "done" && t.status !== "trashed")
|
||||||
load();
|
.sort((a, b) => a.sort_order - b.sort_order || b.created_at.localeCompare(a.created_at));
|
||||||
}, [load]),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!project) return <Text style={{ color: C.muted, margin: 16 }}>Loading…</Text>;
|
const add = () => {
|
||||||
|
|
||||||
const add = async () => {
|
|
||||||
const title = draft.trim();
|
const title = draft.trim();
|
||||||
if (!title) return;
|
if (!title) return;
|
||||||
setDraft("");
|
setDraft("");
|
||||||
await api.tasks.create({ title, status: "next", project_id: id });
|
createTask({ 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();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -51,10 +37,7 @@ export default function ProjectDetail() {
|
|||||||
label="Status"
|
label="Status"
|
||||||
options={STATUSES}
|
options={STATUSES}
|
||||||
value={project.status}
|
value={project.status}
|
||||||
onChange={async (status) => {
|
onChange={(status) => updateProject(project.id, { status })}
|
||||||
setProject({ ...project, status });
|
|
||||||
await api.projects.update(project.id, { status });
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
<TextInput
|
<TextInput
|
||||||
@@ -64,6 +47,7 @@ export default function ProjectDetail() {
|
|||||||
value={draft}
|
value={draft}
|
||||||
onChangeText={setDraft}
|
onChangeText={setDraft}
|
||||||
onSubmitEditing={add}
|
onSubmitEditing={add}
|
||||||
|
submitBehavior="submit"
|
||||||
returnKeyType="done"
|
returnKeyType="done"
|
||||||
/>
|
/>
|
||||||
<FlatList
|
<FlatList
|
||||||
@@ -71,7 +55,11 @@ export default function ProjectDetail() {
|
|||||||
keyExtractor={(t) => t.id}
|
keyExtractor={(t) => t.id}
|
||||||
renderItem={({ item }) => (
|
renderItem={({ item }) => (
|
||||||
<Pressable style={s.row} onPress={() => router.push(`/task/${item.id}`)}>
|
<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 }}>
|
<View style={{ flex: 1 }}>
|
||||||
<Text style={s.title}>{item.title}</Text>
|
<Text style={s.title}>{item.title}</Text>
|
||||||
<Text style={s.meta}>{[item.status, item.context].filter(Boolean).join(" · ")}</Text>
|
<Text style={s.meta}>{[item.status, item.context].filter(Boolean).join(" · ")}</Text>
|
||||||
@@ -84,8 +72,8 @@ export default function ProjectDetail() {
|
|||||||
<Button
|
<Button
|
||||||
title="Drop project"
|
title="Drop project"
|
||||||
danger
|
danger
|
||||||
onPress={async () => {
|
onPress={() => {
|
||||||
await api.projects.drop(project.id);
|
dropProject(project.id);
|
||||||
router.back();
|
router.back();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,37 +1,21 @@
|
|||||||
import { useFocusEffect, useRouter } from "expo-router";
|
import { useRouter } from "expo-router";
|
||||||
import { useCallback, useState } from "react";
|
import { useState } from "react";
|
||||||
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
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 { C } from "../lib/theme";
|
||||||
import type { Project } from "../lib/types";
|
import { useStore } from "../lib/useStore";
|
||||||
|
|
||||||
export default function Projects() {
|
export default function Projects() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const store = useStore();
|
||||||
const [draft, setDraft] = useState("");
|
const [draft, setDraft] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const projects = activeProjects(store);
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const add = () => {
|
||||||
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 name = draft.trim();
|
const name = draft.trim();
|
||||||
if (!name) return;
|
if (!name) return;
|
||||||
setDraft("");
|
setDraft("");
|
||||||
await api.projects.create({ name });
|
createProject({ name });
|
||||||
load();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -45,7 +29,6 @@ export default function Projects() {
|
|||||||
onSubmitEditing={add}
|
onSubmitEditing={add}
|
||||||
returnKeyType="done"
|
returnKeyType="done"
|
||||||
/>
|
/>
|
||||||
{error && <Text style={s.error}>{error}</Text>}
|
|
||||||
<FlatList
|
<FlatList
|
||||||
data={projects}
|
data={projects}
|
||||||
keyExtractor={(p) => p.id}
|
keyExtractor={(p) => p.id}
|
||||||
@@ -54,8 +37,7 @@ export default function Projects() {
|
|||||||
<View style={{ flex: 1 }}>
|
<View style={{ flex: 1 }}>
|
||||||
<Text style={s.title}>{item.name}</Text>
|
<Text style={s.title}>{item.name}</Text>
|
||||||
<Text style={s.meta}>
|
<Text style={s.meta}>
|
||||||
{item.status}
|
{item.status} · {openTaskCount(store, item.id)} open
|
||||||
{item.open_tasks != null && ` · ${item.open_tasks} open`}
|
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
<Text style={{ color: C.muted }}>›</Text>
|
<Text style={{ color: C.muted }}>›</Text>
|
||||||
@@ -91,5 +73,4 @@ const s = StyleSheet.create({
|
|||||||
title: { color: C.text, fontSize: 16 },
|
title: { color: C.text, fontSize: 16 },
|
||||||
meta: { color: C.muted, fontSize: 13, marginTop: 2 },
|
meta: { color: C.muted, fontSize: 13, marginTop: 2 },
|
||||||
empty: { color: C.muted, textAlign: "center", marginTop: 48 },
|
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 { Button, Field } from "../components/ui";
|
||||||
import { api } from "../lib/api";
|
import { api } from "../lib/api";
|
||||||
import { DEFAULT_URL, getConfig, setConfig } from "../lib/config";
|
import { DEFAULT_URL, getConfig, setConfig } from "../lib/config";
|
||||||
|
import { sync } from "../lib/store";
|
||||||
import { C } from "../lib/theme";
|
import { C } from "../lib/theme";
|
||||||
|
|
||||||
export default function Settings() {
|
export default function Settings() {
|
||||||
@@ -23,6 +24,7 @@ export default function Settings() {
|
|||||||
await setConfig(url, token);
|
await setConfig(url, token);
|
||||||
try {
|
try {
|
||||||
await api.tasks.list({ status: "inbox" });
|
await api.tasks.list({ status: "inbox" });
|
||||||
|
void sync();
|
||||||
router.back();
|
router.back();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setStatus(`Connection failed: ${e instanceof Error ? e.message : e}`);
|
setStatus(`Connection failed: ${e instanceof Error ? e.message : e}`);
|
||||||
|
|||||||
@@ -1,109 +1,100 @@
|
|||||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||||
import { useEffect, useState } from "react";
|
import { useState } from "react";
|
||||||
import { ScrollView, Text } from "react-native";
|
import { ScrollView, Text } from "react-native";
|
||||||
import { Button, Chips, Field } from "../../components/ui";
|
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 { 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"];
|
const STATUSES: TaskStatus[] = ["inbox", "next", "waiting", "scheduled", "someday", "done"];
|
||||||
|
|
||||||
export default function TaskDetail() {
|
export default function TaskDetail() {
|
||||||
const { id } = useLocalSearchParams<{ id: string }>();
|
const { id } = useLocalSearchParams<{ id: string }>();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [task, setTask] = useState<Task | null>(null);
|
const store = useStore();
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const original = store.tasks.find((t) => t.id === id);
|
||||||
const [error, setError] = useState<string | null>(null);
|
// Draft is local to the screen; nothing is written until Save.
|
||||||
|
const [draft, setDraft] = useState<Task | null>(original ?? null);
|
||||||
|
|
||||||
useEffect(() => {
|
if (!draft) return <Text style={{ color: C.muted, margin: 16 }}>Task not found.</Text>;
|
||||||
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 (error) return <Text style={{ color: C.danger, margin: 16 }}>{error}</Text>;
|
const set = (patch: Partial<Task>) => setDraft({ ...draft, ...patch });
|
||||||
if (!task) return <Text style={{ color: C.muted, margin: 16 }}>Loading…</Text>;
|
|
||||||
|
|
||||||
const set = (patch: Partial<Task>) => setTask({ ...task, ...patch });
|
const save = () => {
|
||||||
|
updateTask(draft.id, {
|
||||||
const save = async () => {
|
title: draft.title,
|
||||||
try {
|
notes: draft.notes,
|
||||||
await api.tasks.update(task.id, {
|
status: draft.status,
|
||||||
title: task.title,
|
project_id: draft.project_id,
|
||||||
notes: task.notes,
|
context: draft.context,
|
||||||
status: task.status,
|
waiting_for: draft.waiting_for,
|
||||||
project_id: task.project_id,
|
due_date: draft.due_date,
|
||||||
context: task.context,
|
defer_date: draft.defer_date,
|
||||||
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);
|
|
||||||
router.back();
|
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 projectOptions = ["none", ...projects.map((p) => p.id)];
|
||||||
const projectLabels = Object.fromEntries([["none", "None"], ...projects.map((p) => [p.id, p.name])]);
|
const projectLabels = Object.fromEntries([["none", "None"], ...projects.map((p) => [p.id, p.name])]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={{ padding: 16 }}>
|
<ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={{ padding: 16 }}>
|
||||||
<Field label="Title" value={task.title} onChangeText={(v) => set({ title: v })} />
|
<Field label="Title" value={draft.title} onChangeText={(v) => set({ title: v })} />
|
||||||
<Chips label="List" options={STATUSES} value={task.status} onChange={(status) => set({ status })} />
|
<Chips label="List" options={STATUSES} value={draft.status} onChange={(status) => set({ status })} />
|
||||||
<Chips
|
<Chips
|
||||||
label="Project"
|
label="Project"
|
||||||
options={projectOptions}
|
options={projectOptions}
|
||||||
labels={projectLabels}
|
labels={projectLabels}
|
||||||
value={task.project_id ?? "none"}
|
value={draft.project_id ?? "none"}
|
||||||
onChange={(v) => set({ project_id: v === "none" ? null : v })}
|
onChange={(v) => set({ project_id: v === "none" ? null : v })}
|
||||||
/>
|
/>
|
||||||
<Field
|
<Field
|
||||||
label="Context"
|
label="Context"
|
||||||
value={task.context ?? ""}
|
value={draft.context ?? ""}
|
||||||
onChangeText={(v) => set({ context: v || null })}
|
onChangeText={(v) => set({ context: v || null })}
|
||||||
placeholder="@home, @computer, @errands…"
|
placeholder="@home, @computer, @errands…"
|
||||||
autoCapitalize="none"
|
autoCapitalize="none"
|
||||||
/>
|
/>
|
||||||
{task.status === "waiting" && (
|
{draft.status === "waiting" && (
|
||||||
<Field
|
<Field
|
||||||
label="Waiting for"
|
label="Waiting for"
|
||||||
value={task.waiting_for ?? ""}
|
value={draft.waiting_for ?? ""}
|
||||||
onChangeText={(v) => set({ waiting_for: v || null })}
|
onChangeText={(v) => set({ waiting_for: v || null })}
|
||||||
placeholder="Who or what?"
|
placeholder="Who or what?"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<Field
|
<Field
|
||||||
label="Due date"
|
label="Due date"
|
||||||
value={task.due_date ?? ""}
|
value={draft.due_date ?? ""}
|
||||||
onChangeText={(v) => set({ due_date: v || null })}
|
onChangeText={(v) => set({ due_date: v || null })}
|
||||||
placeholder="YYYY-MM-DD"
|
placeholder="YYYY-MM-DD"
|
||||||
autoCapitalize="none"
|
autoCapitalize="none"
|
||||||
/>
|
/>
|
||||||
<Field
|
<Field
|
||||||
label="Defer until"
|
label="Defer until"
|
||||||
value={task.defer_date ?? ""}
|
value={draft.defer_date ?? ""}
|
||||||
onChangeText={(v) => set({ defer_date: v || null })}
|
onChangeText={(v) => set({ defer_date: v || null })}
|
||||||
placeholder="YYYY-MM-DD"
|
placeholder="YYYY-MM-DD"
|
||||||
autoCapitalize="none"
|
autoCapitalize="none"
|
||||||
/>
|
/>
|
||||||
<Field
|
<Field
|
||||||
label="Notes"
|
label="Notes"
|
||||||
value={task.notes}
|
value={draft.notes}
|
||||||
onChangeText={(v) => set({ notes: v })}
|
onChangeText={(v) => set({ notes: v })}
|
||||||
multiline
|
multiline
|
||||||
style={{ minHeight: 80, textAlignVertical: "top" }}
|
style={{ minHeight: 80, textAlignVertical: "top" }}
|
||||||
/>
|
/>
|
||||||
<Button title="Save" onPress={save} />
|
<Button title="Save" onPress={save} />
|
||||||
<Button title="Delete" onPress={trash} danger />
|
<Button
|
||||||
|
title="Delete"
|
||||||
|
danger
|
||||||
|
onPress={() => {
|
||||||
|
trashTask(draft.id);
|
||||||
|
router.back();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useFocusEffect, useRouter } from "expo-router";
|
import { useRouter } from "expo-router";
|
||||||
import { useCallback, useState } from "react";
|
import { useState } from "react";
|
||||||
import {
|
import {
|
||||||
FlatList,
|
FlatList,
|
||||||
Pressable,
|
Pressable,
|
||||||
@@ -9,18 +9,23 @@ import {
|
|||||||
TextInput,
|
TextInput,
|
||||||
View,
|
View,
|
||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { api } from "../lib/api";
|
import { createTask, sync, tasksByStatus, updateTask } from "../lib/store";
|
||||||
import { C } from "../lib/theme";
|
import { C } from "../lib/theme";
|
||||||
|
import { useStore } from "../lib/useStore";
|
||||||
import type { Task, TaskStatus } from "../lib/types";
|
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 router = useRouter();
|
||||||
const meta = [task.context, task.waiting_for && `→ ${task.waiting_for}`, task.due_date && `due ${task.due_date}`]
|
const meta = [task.context, task.waiting_for && `→ ${task.waiting_for}`, task.due_date && `due ${task.due_date}`]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" · ");
|
.join(" · ");
|
||||||
return (
|
return (
|
||||||
<Pressable style={s.row} onPress={() => router.push(`/task/${task.id}`)}>
|
<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} />}
|
{task.status === "done" && <View style={s.checkboxFill} />}
|
||||||
</Pressable>
|
</Pressable>
|
||||||
<View style={{ flex: 1 }}>
|
<View style={{ flex: 1 }}>
|
||||||
@@ -42,46 +47,16 @@ export default function TaskListScreen({
|
|||||||
capture?: boolean;
|
capture?: boolean;
|
||||||
emptyHint: string;
|
emptyHint: string;
|
||||||
}) {
|
}) {
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
const store = useStore();
|
||||||
const [refreshing, setRefreshing] = useState(false);
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [draft, setDraft] = useState("");
|
const [draft, setDraft] = useState("");
|
||||||
|
const tasks = tasksByStatus(store, status);
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const add = () => {
|
||||||
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 title = draft.trim();
|
const title = draft.trim();
|
||||||
if (!title) return;
|
if (!title) return;
|
||||||
setDraft("");
|
setDraft("");
|
||||||
setTasks((cur) => [{ id: `tmp-${title}`, title, status } as Task, ...cur]);
|
createTask({ title, status });
|
||||||
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();
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -98,18 +73,17 @@ export default function TaskListScreen({
|
|||||||
returnKeyType="done"
|
returnKeyType="done"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{error && <Text style={s.error}>{error}</Text>}
|
|
||||||
<FlatList
|
<FlatList
|
||||||
data={tasks}
|
data={tasks}
|
||||||
keyExtractor={(t) => t.id}
|
keyExtractor={(t) => t.id}
|
||||||
renderItem={({ item }) => <TaskRow task={item} onToggle={toggle} />}
|
renderItem={({ item }) => <TaskRow task={item} listStatus={status} />}
|
||||||
refreshControl={
|
refreshControl={
|
||||||
<RefreshControl
|
<RefreshControl
|
||||||
refreshing={refreshing}
|
refreshing={refreshing}
|
||||||
tintColor={C.muted}
|
tintColor={C.muted}
|
||||||
onRefresh={async () => {
|
onRefresh={async () => {
|
||||||
setRefreshing(true);
|
setRefreshing(true);
|
||||||
await load();
|
await sync();
|
||||||
setRefreshing(false);
|
setRefreshing(false);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -156,5 +130,4 @@ const s = StyleSheet.create({
|
|||||||
title: { color: C.text, fontSize: 16 },
|
title: { color: C.text, fontSize: 16 },
|
||||||
meta: { color: C.muted, fontSize: 13, marginTop: 2 },
|
meta: { color: C.muted, fontSize: 13, marginTop: 2 },
|
||||||
empty: { color: C.muted, textAlign: "center", marginTop: 48, fontSize: 15 },
|
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}` : ""}`);
|
return req<Task[]>(`/v1/tasks${q ? `?${q}` : ""}`);
|
||||||
},
|
},
|
||||||
get: (id: string) => req<Task>(`/v1/tasks/${id}`),
|
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) }),
|
req<Task>("/v1/tasks", { method: "POST", body: JSON.stringify(data) }),
|
||||||
update: (id: string, data: Partial<Task>) =>
|
update: (id: string, data: Partial<Task>) =>
|
||||||
req<Task>(`/v1/tasks/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
req<Task>(`/v1/tasks/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||||
@@ -42,7 +42,7 @@ export const api = {
|
|||||||
},
|
},
|
||||||
projects: {
|
projects: {
|
||||||
list: () => req<Project[]>("/v1/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) }),
|
req<Project>("/v1/projects", { method: "POST", body: JSON.stringify(data) }),
|
||||||
update: (id: string, data: Partial<Project>) =>
|
update: (id: string, data: Partial<Project>) =>
|
||||||
req<Project>(`/v1/projects/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
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);
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ const PROJECT_COLS = `id, name, status, notes, sort_order, created_at, updated_a
|
|||||||
|
|
||||||
const TASK_STATUSES = ["inbox", "next", "waiting", "scheduled", "someday", "done", "trashed"];
|
const TASK_STATUSES = ["inbox", "next", "waiting", "scheduled", "someday", "done", "trashed"];
|
||||||
const PROJECT_STATUSES = ["active", "someday", "completed", "dropped"];
|
const PROJECT_STATUSES = ["active", "someday", "completed", "dropped"];
|
||||||
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||||
|
|
||||||
const CORS = {
|
const CORS = {
|
||||||
"Access-Control-Allow-Origin": "*",
|
"Access-Control-Allow-Origin": "*",
|
||||||
@@ -69,13 +70,18 @@ async function handle(req: Request): Promise<Response> {
|
|||||||
const t = pick(body, TASK_FIELDS);
|
const t = pick(body, TASK_FIELDS);
|
||||||
if (typeof t.title !== "string" || !t.title.trim()) return err("title required", 400);
|
if (typeof t.title !== "string" || !t.title.trim()) return err("title required", 400);
|
||||||
if (t.status && !TASK_STATUSES.includes(t.status as string)) return err("bad status", 400);
|
if (t.status && !TASK_STATUSES.includes(t.status as string)) return err("bad status", 400);
|
||||||
|
const id = typeof body.id === "string" && UUID_RE.test(body.id) ? body.id : null;
|
||||||
|
// Client-supplied id + on-conflict no-op make offline-queue retries idempotent.
|
||||||
const rows = await sql.unsafe(
|
const rows = await sql.unsafe(
|
||||||
`insert into tasks (title, notes, status, project_id, context, waiting_for, due_date, defer_date, sort_order)
|
`insert into tasks (id, title, notes, status, project_id, context, waiting_for, due_date, defer_date, sort_order)
|
||||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
values (coalesce($1::uuid, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
|
on conflict (id) do nothing
|
||||||
returning ${TASK_COLS}`,
|
returning ${TASK_COLS}`,
|
||||||
[t.title, t.notes ?? "", t.status ?? "inbox", t.project_id ?? null, t.context ?? null,
|
[id, t.title, t.notes ?? "", t.status ?? "inbox", t.project_id ?? null, t.context ?? null,
|
||||||
t.waiting_for ?? null, t.due_date ?? null, t.defer_date ?? null, t.sort_order ?? 0]);
|
t.waiting_for ?? null, t.due_date ?? null, t.defer_date ?? null, t.sort_order ?? 0]);
|
||||||
return json(rows[0], 201);
|
if (rows.length) return json(rows[0], 201);
|
||||||
|
const existing = await sql.unsafe(`select ${TASK_COLS} from tasks where id = $1`, [id]);
|
||||||
|
return json(existing[0], 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
let m = path.match(/^\/v1\/tasks\/([0-9a-f-]{36})$/);
|
let m = path.match(/^\/v1\/tasks\/([0-9a-f-]{36})$/);
|
||||||
@@ -115,11 +121,16 @@ async function handle(req: Request): Promise<Response> {
|
|||||||
const p = pick(body, PROJECT_FIELDS);
|
const p = pick(body, PROJECT_FIELDS);
|
||||||
if (typeof p.name !== "string" || !p.name.trim()) return err("name required", 400);
|
if (typeof p.name !== "string" || !p.name.trim()) return err("name required", 400);
|
||||||
if (p.status && !PROJECT_STATUSES.includes(p.status as string)) return err("bad status", 400);
|
if (p.status && !PROJECT_STATUSES.includes(p.status as string)) return err("bad status", 400);
|
||||||
|
const id = typeof body.id === "string" && UUID_RE.test(body.id) ? body.id : null;
|
||||||
const rows = await sql.unsafe(
|
const rows = await sql.unsafe(
|
||||||
`insert into projects (name, status, notes, sort_order) values ($1, $2, $3, $4)
|
`insert into projects (id, name, status, notes, sort_order)
|
||||||
|
values (coalesce($1::uuid, gen_random_uuid()), $2, $3, $4, $5)
|
||||||
|
on conflict (id) do nothing
|
||||||
returning ${PROJECT_COLS}`,
|
returning ${PROJECT_COLS}`,
|
||||||
[p.name, p.status ?? "active", p.notes ?? "", p.sort_order ?? 0]);
|
[id, p.name, p.status ?? "active", p.notes ?? "", p.sort_order ?? 0]);
|
||||||
return json(rows[0], 201);
|
if (rows.length) return json(rows[0], 201);
|
||||||
|
const existing = await sql.unsafe(`select ${PROJECT_COLS} from projects where id = $1`, [id]);
|
||||||
|
return json(existing[0], 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
m = path.match(/^\/v1\/projects\/([0-9a-f-]{36})$/);
|
m = path.match(/^\/v1\/projects\/([0-9a-f-]{36})$/);
|
||||||
|
|||||||
Reference in New Issue
Block a user