refactor create/editTask into one upsertTask page, and remove all remaining console.log and debugging helpers

This commit is contained in:
Fhj0607
2026-04-30 11:34:26 +02:00
parent 152a91718a
commit 2f483b8ef9
7 changed files with 102 additions and 587 deletions

View File

@@ -41,7 +41,6 @@ export default function ViewDetailsAssignment() {
.single(); .single();
if (error || !data) { if (error || !data) {
console.log('GetAssignment error:', error);
Alert.alert('Assignment could not be fetched, please try again'); Alert.alert('Assignment could not be fetched, please try again');
return; return;
} }
@@ -56,7 +55,6 @@ export default function ViewDetailsAssignment() {
.single(); .single();
if (subjectError || !subjectData) { if (subjectError || !subjectData) {
console.log('GetSubjectMeta error:', subjectError);
setSubjectMeta({ setSubjectMeta({
title: 'Unknown Subject', title: 'Unknown Subject',
color: 'slate' color: 'slate'
@@ -355,7 +353,7 @@ export default function ViewDetailsAssignment() {
className="mb-6 mt-5 h-14 items-center justify-center rounded-2xl bg-accent" className="mb-6 mt-5 h-14 items-center justify-center rounded-2xl bg-accent"
onPress={() => onPress={() =>
router.push({ router.push({
pathname: '/task/createTask', pathname: '/task/upsertTask',
params: { aId: assignment.aId }, params: { aId: assignment.aId },
}) })
} }
@@ -436,7 +434,7 @@ export default function ViewDetailsAssignment() {
className="mr-3 flex-1 items-center justify-center rounded-2xl border border-app-border bg-app-subtle py-3" className="mr-3 flex-1 items-center justify-center rounded-2xl border border-app-border bg-app-subtle py-3"
onPress={() => onPress={() =>
router.push({ router.push({
pathname: '/task/editTask', pathname: '/task/upsertTask',
params: { tId: item.tId }, params: { tId: item.tId },
}) })
} }

View File

@@ -86,20 +86,6 @@ export default function ViewDetailsSubject() {
}, [session, sId]) }, [session, sId])
); );
useEffect(() => {
const test = async () => {
try {
const { data, error } = await supabase.from('subjects').select('*').limit(1);
console.log('test data:', data);
console.log('test error:', error);
} catch (err) {
console.log('test crashed:', err);
}
};
test();
}, []);
const DeleteSubject = async (subjectId: string) => { const DeleteSubject = async (subjectId: string) => {
Alert.alert( Alert.alert(
'Delete Subject', 'Delete Subject',

View File

@@ -3,9 +3,7 @@ import { Stack } from "expo-router";
export default function TaskLayout() { export default function TaskLayout() {
return ( return (
<Stack> <Stack>
<Stack.Screen name="tasks" options={{ title: 'Tasks' }} /> <Stack.Screen name="upsertTask" options={{ title: "Create Task" }} />
<Stack.Screen name="createTask" options={{ title: "Create Task" }} />
<Stack.Screen name="editTask" options={{ title: "Edit Task" }} />
<Stack.Screen name="viewDetailsTask" options={{ title: "Task Details" }} /> <Stack.Screen name="viewDetailsTask" options={{ title: "Task Details" }} />
</Stack> </Stack>
); );

View File

@@ -1,255 +0,0 @@
import { CheckAssignmentCompletion } from '@/lib/progress';
import { supabase } from '@/lib/supabase';
import type { Task } from '@/lib/types';
import { router, Stack, useFocusEffect, useLocalSearchParams } from 'expo-router';
import { useCallback, useState } from 'react';
import {
ActivityIndicator,
Alert,
Keyboard,
KeyboardAvoidingView,
Platform,
Pressable,
ScrollView,
Text,
TextInput,
TouchableWithoutFeedback,
View,
} from 'react-native';
export default function EditTask() {
const { tId } = useLocalSearchParams<{ tId: string }>();
const [task, SetTask] = useState<Task | null>(null);
const [isSaving, SetIsSaving] = useState(false);
const GetTask = async (tId: string) => {
const { data, error } = await supabase.from("tasks").select("*").eq("tId", tId).single();
if (error) {
Alert.alert("Task could not be fetched, please try again");
return;
}
SetTask(data ?? null);
}
useFocusEffect(
useCallback(() => {
if (tId) {
GetTask(tId);
}
}, [tId])
);
const EditTask = async () => {
if (!task) return;
if(task.title.trim() === '') {
Alert.alert("Title is required!");
return;
}
const { data, error: userError } = await supabase.auth.getUser();
if(userError || !data.user) {
router.replace("../createUser");
return;
}
SetIsSaving(true);
const { error: dbError } = await supabase.from("tasks").update({
title: task.title,
description: task.description,
isCompleted: task.isCompleted,
lastChanged: new Date().toISOString(),
uId: data.user.id,
aId: task.aId,
}).eq("tId", tId);
SetIsSaving(false);
if (dbError) {
Alert.alert("Task could not be edited, please try again");
return;
}
if (task.aId) {
try {
await CheckAssignmentCompletion(task.aId);
} catch {
Alert.alert("Failed to update assignment completion state");
}
}
Alert.alert("Task successfully edited!");
router.back();
};
const inputClassName =
'rounded-2xl border border-app-border bg-app-subtle px-4 py-3 text-base text-text-main';
const labelClassName = 'mb-2 text-sm font-semibold text-text-secondary';
return (
<>
<Stack.Screen
options={{
title: 'Edit Task',
}}
/>
{!task ? (
<View className="flex-1 bg-app-bg px-5 pt-6">
<View className="rounded-3xl border border-app-border bg-app-surface p-5">
<Text className="text-2xl font-bold text-text-main">
Task not found
</Text>
<Text className="mt-2 text-base text-text-secondary">
The task could not be loaded.
</Text>
<Pressable
className="mt-5 h-12 items-center justify-center rounded-2xl bg-accent"
onPress={() => router.back()}
>
<Text className="text-base font-bold text-text-inverse">
Go back
</Text>
</Pressable>
</View>
</View>
) : (
<KeyboardAvoidingView
className="flex-1 bg-app-bg"
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<ScrollView
className="flex-1"
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
flexGrow: 1,
justifyContent: 'center',
paddingHorizontal: 20,
paddingVertical: 32,
}}
>
<View className="mb-6">
<Text className="text-3xl font-bold text-text-main">
Edit Task
</Text>
<Text className="mt-2 text-base leading-6 text-text-secondary">
Update the task details and completion state.
</Text>
</View>
<View className="rounded-3xl border border-app-border bg-app-surface p-5">
<View className="mb-5">
<Text className={labelClassName}>Title</Text>
<TextInput
className={inputClassName}
placeholder="Enter task title"
placeholderTextColor="#9CA3AF"
value={task.title}
onChangeText={(text) =>
SetTask((prev) => (prev ? { ...prev, title: text } : prev))
}
returnKeyType="next"
/>
</View>
<View className="mb-5">
<Text className={labelClassName}>Description</Text>
<TextInput
className={`${inputClassName} min-h-28`}
placeholder="Add a short description"
placeholderTextColor="#9CA3AF"
value={task.description}
onChangeText={(text) =>
SetTask((prev) =>
prev ? { ...prev, description: text } : prev
)
}
multiline
textAlignVertical="top"
/>
</View>
<Pressable
onPress={() =>
SetTask((prev) =>
prev ? { ...prev, isCompleted: !prev.isCompleted } : prev
)
}
disabled={isSaving}
className={`mb-6 flex-row items-center rounded-2xl border p-4 ${
task.isCompleted
? 'border-accent bg-accent-soft'
: 'border-app-border bg-app-subtle'
}`}
>
<View
className={`mr-3 h-6 w-6 items-center justify-center rounded-md border-2 ${
task.isCompleted
? 'border-accent bg-accent'
: 'border-app-border bg-app-surface'
}`}
>
{task.isCompleted && (
<Text className="text-sm font-bold text-text-inverse">
</Text>
)}
</View>
<View className="flex-1">
<Text className="text-base font-semibold text-text-main">
Mark as completed
</Text>
<Text className="mt-1 text-sm text-text-muted">
You can change this again later.
</Text>
</View>
</Pressable>
<Pressable
className={`h-14 items-center justify-center rounded-2xl ${
isSaving ? 'bg-accent-disabled' : 'bg-accent'
}`}
onPress={EditTask}
disabled={isSaving}
>
{isSaving ? (
<View className="flex-row items-center">
<ActivityIndicator size="small" />
<Text className="ml-3 text-base font-bold text-text-inverse">
Saving...
</Text>
</View>
) : (
<Text className="text-base font-bold text-text-inverse">
Save Changes
</Text>
)}
</Pressable>
<Pressable
className="mt-3 h-14 items-center justify-center rounded-2xl border border-app-border bg-app-subtle"
onPress={() => router.back()}
disabled={isSaving}
>
<Text className="text-base font-semibold text-text-secondary">
Cancel
</Text>
</Pressable>
</View>
</ScrollView>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
)}
</>
);
}

View File

@@ -1,277 +0,0 @@
import { defaultStyles } from '@/constants/defaultStyles';
import { CheckAssignmentCompletion } from '@/lib/progress';
import { supabase } from '@/lib/supabase';
import type { Task } from '@/lib/types';
import { Ionicons } from '@expo/vector-icons';
import { Session } from '@supabase/supabase-js';
import { router, Stack, useFocusEffect } from 'expo-router';
import { useCallback, useEffect, useState } from 'react';
import {
Alert,
Pressable,
SectionList,
Text,
View,
} from 'react-native';
export default function Tasks() {
const [tasks, SetTasks] = useState<Task[]>([]);
const [session, SetSession] = useState<Session | null>(null);
const taskSections = [
{
title: 'Upcoming Tasks',
data: tasks.filter((task) => !task.isCompleted),
emptyMessage: 'No upcoming tasks',
},
{
title: 'Completed Tasks',
data: tasks.filter((task) => task.isCompleted),
emptyMessage: 'No completed tasks',
},
];
useEffect(() => {
supabase.auth
.getSession()
.then(({ data }) => SetSession(data.session ?? null));
const { data: sub } = supabase.auth.onAuthStateChange(
(_event, newSession) => {
SetSession(newSession);
}
);
return () => sub.subscription.unsubscribe();
}, []);
const GetTasks = async () => {
const { data, error } = await supabase.from('tasks').select('*');
if (error) {
Alert.alert('Tasks could not be fetched, please try again');
return;
}
SetTasks(data ?? []);
};
useFocusEffect(
useCallback(() => {
if (session) {
GetTasks();
}
}, [session])
);
const DeleteTask = async (tId: string, aId: string) => {
Alert.alert(
'Delete Task',
'Are you sure you want to delete this task?',
[
{
text: 'Cancel',
style: 'cancel',
},
{
text: 'Delete',
style: 'destructive',
onPress: async () => {
const { error } = await supabase
.from('tasks')
.delete()
.eq('tId', tId);
if (error) {
Alert.alert('Task could not be deleted, please try again');
return;
}
Alert.alert('Task deleted successfully!');
try {
await CheckAssignmentCompletion(aId);
} catch {
Alert.alert("Failed to update assignment completion state");
}
GetTasks();
},
},
]
);
};
return (
<View className="flex-1 bg-app-bg">
<Stack.Screen
options={{
title: 'Tasks',
headerTitleStyle: defaultStyles.title,
headerRight: () => (
<View className="flex-row items-center">
<Pressable
className="mr-3 h-10 w-10 items-center justify-center rounded-full border border-app-border bg-app-surface"
onPress={GetTasks}
>
<Ionicons name="refresh" size={20} color="#333" />
</Pressable>
<Pressable
className="rounded-full bg-app-subtle px-4 py-2"
onPress={async () => await supabase.auth.signOut()}
>
<Text className="text-sm font-semibold text-text-secondary">
Logout
</Text>
</Pressable>
</View>
),
}}
/>
<View className="flex-1 px-5 pt-5">
<View className="mb-6">
<Text className="text-3xl font-bold text-text-main">
Tasks
</Text>
<Text className="mt-2 text-base leading-6 text-text-secondary">
Break assignments into small steps and keep your progress clear.
</Text>
</View>
<Pressable
className="mb-6 h-14 items-center justify-center rounded-2xl bg-accent"
onPress={() => router.push('/task/createTask')}
>
<Text className="text-base font-bold text-text-inverse">
Create Task
</Text>
</Pressable>
<SectionList
sections={taskSections}
keyExtractor={(item) => item.tId}
showsVerticalScrollIndicator={false}
stickySectionHeadersEnabled={false}
contentContainerStyle={{
paddingBottom: 32,
}}
renderSectionHeader={({ section: { title, data } }) => (
<View className="mb-3 mt-2 flex-row items-center justify-between">
<Text className="text-lg font-bold text-text-main">
{title}
</Text>
<View className="rounded-full bg-app-subtle px-3 py-1">
<Text className="text-xs font-semibold text-text-muted">
{data.length}
</Text>
</View>
</View>
)}
renderItem={({ item }) => {
const isOwner = session?.user.id === item.uId;
return (
<View className="mb-4 rounded-3xl border border-app-border bg-app-surface p-4 shadow-sm">
<Pressable
onPress={() =>
router.push({
pathname: '/task/viewDetailsTask',
params: { tId: item.tId },
})
}
>
<View className="flex-row items-start">
<View
className={`mr-3 mt-1 h-6 w-6 items-center justify-center rounded-md border-2 ${
item.isCompleted
? 'border-accent bg-accent'
: 'border-app-border bg-app-subtle'
}`}
>
{item.isCompleted && (
<Text className="text-sm font-bold text-text-inverse">
</Text>
)}
</View>
<View className="flex-1">
<Text
className={`text-base font-bold ${
item.isCompleted
? 'text-text-secondary'
: 'text-text-main'
}`}
>
{item.title}
</Text>
{item.description ? (
<Text
className="mt-1 text-sm leading-5 text-text-muted"
numberOfLines={2}
>
{item.description}
</Text>
) : null}
<View className="mt-3 self-start rounded-full bg-app-subtle px-3 py-1">
<Text className="text-xs font-semibold text-text-secondary">
{item.isCompleted ? 'Completed' : 'In progress'}
</Text>
</View>
</View>
</View>
</Pressable>
{isOwner && (
<View className="mt-4 flex-row border-t border-app-border pt-4">
<Pressable
className="mr-3 flex-1 items-center justify-center rounded-2xl border border-app-border bg-app-subtle py-3"
onPress={() =>
router.push({
pathname: '/task/editTask',
params: { tId: item.tId },
})
}
>
<Text className="text-sm font-bold text-text-secondary">
Edit
</Text>
</Pressable>
<Pressable
className="flex-1 items-center justify-center rounded-2xl border border-app-border bg-app-surface py-3"
onPress={() => DeleteTask(item.tId, item.aId)}
>
<Text className="text-sm font-bold text-status-danger">
Delete
</Text>
</Pressable>
</View>
)}
</View>
);
}}
renderSectionFooter={({ section }) =>
section.data.length === 0 ? (
<View className="mb-6 rounded-3xl border border-app-border bg-app-surface p-5">
<Text className="text-center text-base font-semibold text-text-secondary">
{section.emptyMessage}
</Text>
<Text className="mt-1 text-center text-sm text-text-muted">
Tasks for this assignment will show up here.
</Text>
</View>
) : (
<View className="mb-2" />
)
}
/>
</View>
</View>
);
}

View File

@@ -1,8 +1,9 @@
import { defaultStyles } from '@/constants/defaultStyles'; import { defaultStyles } from '@/constants/defaultStyles';
import { CheckAssignmentCompletion } from '@/lib/progress'; import { CheckAssignmentCompletion } from '@/lib/progress';
import { supabase } from '@/lib/supabase'; import { supabase } from '@/lib/supabase';
import type { Task } from '@/lib/types';
import { router, Stack, useLocalSearchParams } from 'expo-router'; import { router, Stack, useLocalSearchParams } from 'expo-router';
import { useState } from 'react'; import { useEffect, useState } from 'react';
import { import {
ActivityIndicator, ActivityIndicator,
Alert, Alert,
@@ -17,15 +18,57 @@ import {
View, View,
} from 'react-native'; } from 'react-native';
export default function CreateTask() { export default function UpsertTask() {
const aId = (useLocalSearchParams().aId as string) ?? null; const { tId, aId: routeAId } = useLocalSearchParams<{
tId?: string;
aId?: string;
}>();
const isEditMode = Boolean(tId);
const [title, SetTitle] = useState(''); const [title, SetTitle] = useState('');
const [description, SetDescription] = useState(''); const [description, SetDescription] = useState('');
const [isCompleted, SetIsCompleted] = useState(false); const [isCompleted, SetIsCompleted] = useState(false);
const [assignmentId, SetAssignmentId] = useState<string | null>(routeAId ?? null);
const [isLoading, SetIsLoading] = useState(isEditMode);
const [isSaving, SetIsSaving] = useState(false); const [isSaving, SetIsSaving] = useState(false);
const CreateTask = async () => { useEffect(() => {
if (!isEditMode || !tId) {
SetIsLoading(false);
return;
}
const loadTask = async () => {
SetIsLoading(true);
const { data, error } = await supabase
.from('tasks')
.select('*')
.eq('tId', tId)
.single();
SetIsLoading(false);
if (error || !data) {
Alert.alert('Task could not be loaded, please try again');
router.back();
return;
}
const task = data as Task;
SetTitle(task.title ?? '');
SetDescription(task.description ?? '');
SetIsCompleted(task.isCompleted ?? false);
SetAssignmentId(task.aId ?? routeAId ?? null);
};
loadTask();
}, [isEditMode, tId, routeAId]);
const handleSubmit = async () => {
if (title.trim() === '') { if (title.trim() === '') {
Alert.alert('Title is required!'); Alert.alert('Title is required!');
return; return;
@@ -34,42 +77,55 @@ export default function CreateTask() {
const { data, error: userError } = await supabase.auth.getUser(); const { data, error: userError } = await supabase.auth.getUser();
if (userError || !data.user) { if (userError || !data.user) {
router.replace('../createUser'); router.replace('/login');
return;
}
if (!assignmentId) {
Alert.alert('Missing assignment', 'This task is not linked to an assignment.');
return; return;
} }
SetIsSaving(true); SetIsSaving(true);
const { error: dbError } = await supabase.from('tasks').insert({ const payload = {
title: title.trim(), title: title.trim(),
description: description.trim(), description: description.trim(),
isCompleted, isCompleted,
lastChanged: new Date().toISOString(), lastChanged: new Date().toISOString(),
uId: data.user.id, uId: data.user.id,
aId, aId: assignmentId,
}); };
if (dbError) { const result =
isEditMode && tId
? await supabase.from('tasks').update(payload).eq('tId', tId)
: await supabase.from('tasks').insert(payload);
if (result.error) {
SetIsSaving(false); SetIsSaving(false);
Alert.alert('Task could not be created, please try again'); Alert.alert(
isEditMode
? 'Task could not be updated, please try again'
: 'Task could not be created, please try again'
);
return; return;
} }
Alert.alert('Task successfully created!'); try {
await CheckAssignmentCompletion(assignmentId);
if (aId) { } catch {
try { SetIsSaving(false);
await CheckAssignmentCompletion(aId); Alert.alert('Failed to update assignment completion state');
} catch { return;
Alert.alert("Failed to update assignment completion state");
}
} }
SetTitle('');
SetDescription('');
SetIsCompleted(false);
SetIsSaving(false); SetIsSaving(false);
Alert.alert(
isEditMode ? 'Task successfully updated!' : 'Task successfully created!'
);
router.back(); router.back();
}; };
@@ -78,11 +134,19 @@ export default function CreateTask() {
const labelClassName = 'mb-2 text-sm font-semibold text-text-secondary'; const labelClassName = 'mb-2 text-sm font-semibold text-text-secondary';
if (isLoading) {
return (
<View className="flex-1 items-center justify-center bg-app-bg">
<ActivityIndicator size="large" />
</View>
);
}
return ( return (
<> <>
<Stack.Screen <Stack.Screen
options={{ options={{
title: 'Create Task', title: isEditMode ? 'Edit Task' : 'Create Task',
headerTitleStyle: defaultStyles.title, headerTitleStyle: defaultStyles.title,
}} }}
/> />
@@ -104,10 +168,12 @@ export default function CreateTask() {
> >
<View className="mb-6"> <View className="mb-6">
<Text className="text-3xl font-bold text-text-main"> <Text className="text-3xl font-bold text-text-main">
Create Task {isEditMode ? 'Edit Task' : 'Create Task'}
</Text> </Text>
<Text className="mt-2 text-base leading-6 text-text-secondary"> <Text className="mt-2 text-base leading-6 text-text-secondary">
Add a small step to move this assignment forward. {isEditMode
? 'Update this task and keep your assignment moving forward.'
: 'Add a small step to move this assignment forward.'}
</Text> </Text>
</View> </View>
@@ -117,6 +183,7 @@ export default function CreateTask() {
<TextInput <TextInput
className={inputClassName} className={inputClassName}
placeholder="Enter task title" placeholder="Enter task title"
placeholderTextColor="#9CA3AF"
value={title} value={title}
onChangeText={SetTitle} onChangeText={SetTitle}
returnKeyType="next" returnKeyType="next"
@@ -128,6 +195,7 @@ export default function CreateTask() {
<TextInput <TextInput
className={`${inputClassName} min-h-28`} className={`${inputClassName} min-h-28`}
placeholder="Add a short description" placeholder="Add a short description"
placeholderTextColor="#9CA3AF"
value={description} value={description}
onChangeText={SetDescription} onChangeText={SetDescription}
multiline multiline
@@ -172,19 +240,19 @@ export default function CreateTask() {
className={`h-14 items-center justify-center rounded-2xl ${ className={`h-14 items-center justify-center rounded-2xl ${
isSaving ? 'bg-accent-disabled' : 'bg-accent' isSaving ? 'bg-accent-disabled' : 'bg-accent'
}`} }`}
onPress={CreateTask} onPress={handleSubmit}
disabled={isSaving} disabled={isSaving}
> >
{isSaving ? ( {isSaving ? (
<View className="flex-row items-center"> <View className="flex-row items-center">
<ActivityIndicator size="small" /> <ActivityIndicator size="small" />
<Text className="ml-3 text-base font-bold text-text-inverse"> <Text className="ml-3 text-base font-bold text-text-inverse">
Creating... {isEditMode ? 'Saving...' : 'Creating...'}
</Text> </Text>
</View> </View>
) : ( ) : (
<Text className="text-base font-bold text-text-inverse"> <Text className="text-base font-bold text-text-inverse">
Create Task {isEditMode ? 'Save Changes' : 'Create Task'}
</Text> </Text>
)} )}
</Pressable> </Pressable>

View File

@@ -37,7 +37,6 @@ export default function ViewDetailsTask() {
.single(); .single();
if (error || !data) { if (error || !data) {
console.log('GetTask error:', error);
Alert.alert('Task could not be fetched, please try again'); Alert.alert('Task could not be fetched, please try again');
return; return;
} }
@@ -52,7 +51,6 @@ export default function ViewDetailsTask() {
.single(); .single();
if (assignmentError || !assignmentData) { if (assignmentError || !assignmentData) {
console.log('GetTaskAssignment error:', assignmentError);
setContextMeta({ setContextMeta({
subjectTitle: 'Unknown Subject', subjectTitle: 'Unknown Subject',
assignmentTitle: 'Unknown Assignment', assignmentTitle: 'Unknown Assignment',
@@ -69,7 +67,6 @@ export default function ViewDetailsTask() {
.single(); .single();
if (subjectError || !subjectData) { if (subjectError || !subjectData) {
console.log('GetTaskSubject error:', subjectError);
setContextMeta({ setContextMeta({
subjectTitle: 'Unknown Subject', subjectTitle: 'Unknown Subject',
assignmentTitle: assignmentData.title ?? 'Unknown Assignment', assignmentTitle: assignmentData.title ?? 'Unknown Assignment',
@@ -275,7 +272,7 @@ export default function ViewDetailsTask() {
className="mr-3 flex-1 items-center justify-center rounded-2xl border border-app-border bg-app-subtle py-3" className="mr-3 flex-1 items-center justify-center rounded-2xl border border-app-border bg-app-subtle py-3"
onPress={() => onPress={() =>
router.push({ router.push({
pathname: '/task/editTask', pathname: '/task/upsertTask',
params: { tId: task.tId }, params: { tId: task.tId },
}) })
} }