10 ноября 2025 г.
Установка клиента
npm install -g @react-native-community/cli
Возможные проблемы с Gradle
Необходимо установить GRADLE_USER_HOME в переменных среды.
Создание приложения
npx @react-native-community/cli@latest init TodoApp
cd TodoApp
Установка зависимостей
# Для навигации
npm install @react-navigation/native @react-navigation/stack
npm install react-native-screens react-native-safe-area-context
# Для хранения задач
npm install @react-native-async-storage/async-storage
Генерация иконок
- Перейдите на https://appicon.co/
- Загрузите вашу иконку (1024x1024px)
- Скачайте архив
- Для Android: распакуйте в android/app/src/main/res/
- Для iOS: откройте Xcode и перетащите в Assets.xcassets
Или создание с помощью Sharp скрипта:
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
async function generateIcons() {
const inputIcon = './assets/icon.png';
if (!fs.existsSync(inputIcon)) {
console.log('❌ Иконка не найдена:', inputIcon);
return;
}
// Android mipmap папки и размеры
const androidConfig = [
{ folder: 'mipmap-ldpi', size: 36 },
{ folder: 'mipmap-mdpi', size: 48 },
{ folder: 'mipmap-hdpi', size: 72 },
{ folder: 'mipmap-xhdpi', size: 96 },
{ folder: 'mipmap-xxhdpi', size: 144 },
{ folder: 'mipmap-xxxhdpi', size: 192 }
];
console.log('Генерация Android иконок...');
for (const config of androidConfig) {
const androidPath = `./android/app/src/main/res/${config.folder}`;
const iconPath = `${androidPath}/ic_launcher.png`;
const roundIconPath = `${androidPath}/ic_launcher_round.png`;
// Создаем папку если нет
if (!fs.existsSync(androidPath)) {
fs.mkdirSync(androidPath, { recursive: true });
console.log(`Создана папка: ${config.folder}`);
}
try {
// Основная иконка
await sharp(inputIcon)
.resize(config.size, config.size)
.png()
.toFile(iconPath);
// Круглая иконка (та же самая, но можно сделать круглую)
await sharp(inputIcon)
.resize(config.size, config.size)
.png()
.toFile(roundIconPath);
console.log(`✅ ${config.folder}: ${config.size}x${config.size}`);
} catch (error) {
console.log(`❌ Ошибка в ${config.folder}:`, error.message);
}
}
console.log('Все Android иконки созданы!');
}
generateIcons();
Для установки sharp:
npm install sharp
Генерируем иконки:
node generate-icons.js
Структура приложения
- src
- components
- AddTodoModal.tsx
- Icon.tsx
- hooks
- screens
- HomeScreen.tsx
- TaskDetailScreen.tsx
- types
- utils
- App.tsx
- index.js
Файл App.tsx
import React from 'react';
import HomeScreen from './src/screens/HomeScreen';
const App: React.FC = () => {
return <HomeScreen />;
};
export default App;
Файл src/components/AddTodoModal.tsx
import React, { useState } from 'react';
import {
View,
Text,
TextInput,
TouchableOpacity,
Modal,
StyleSheet,
KeyboardAvoidingView,
Platform,
Alert
} from 'react-native';
import Icon from './Icon';
interface AddTodoModalProps {
visible: boolean;
onClose: () => void;
onAddTodo: (text: string) => Promise<void>;
}
const AddTodoModal: React.FC<AddTodoModalProps> = ({
visible,
onClose,
onAddTodo
}) => {
const [text, setText] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleAdd = async () => {
if (text.trim().length === 0) {
Alert.alert('Ошибка', 'Введите описание задачи');
return;
}
if (text.trim().length > 500) {
Alert.alert('Ошибка', 'Задача не может быть длиннее 500 символов');
return;
}
setIsLoading(true);
try {
await onAddTodo(text.trim());
setText('');
onClose();
} catch (error) {
Alert.alert('Ошибка', 'Не удалось добавить задачу');
console.error('Ошибка добавления задачи:', error);
} finally {
setIsLoading(false);
}
};
const handleClose = () => {
if (text.trim().length > 0) {
Alert.alert(
'Отменить добавление?',
'Введенные данные будут потеряны',
[
{ text: 'Продолжить редактирование', style: 'cancel' },
{
text: 'Отменить',
style: 'destructive',
onPress: () => {
setText('');
onClose();
}
}
]
);
} else {
setText('');
onClose();
}
};
return (
<Modal
visible={visible}
animationType="slide"
onRequestClose={handleClose}
>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.container}
>
<View style={styles.header}>
<Text style={styles.title}>Новая задача</Text>
<TouchableOpacity onPress={handleClose}>
<Icon name="close" size={24} color="#333" />
</TouchableOpacity>
</View>
<View style={styles.content}>
<Text style={styles.label}>Описание задачи</Text>
<TextInput
style={styles.input}
placeholder="Например: Сделать домашнее задание..."
value={text}
onChangeText={setText}
multiline
autoFocus
maxLength={500}
textAlignVertical="top"
editable={!isLoading}
/>
<Text style={styles.charCount}>
{text.length}/500 символов
</Text>
</View>
<View style={styles.footer}>
<TouchableOpacity
style={[styles.cancelButton, isLoading && styles.buttonDisabled]}
onPress={handleClose}
disabled={isLoading}
>
<Text style={styles.cancelButtonText}>Отмена</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.addButton,
(text.trim().length === 0 || isLoading) && styles.addButtonDisabled
]}
onPress={handleAdd}
disabled={text.trim().length === 0 || isLoading}
>
{isLoading ? (
<Text style={styles.addButtonText}>Добавление...</Text>
) : (
<Text style={styles.addButtonText}>Добавить</Text>
)}
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</Modal>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
paddingTop: 50, // Отступ для статус бара
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
title: {
fontSize: 20,
fontWeight: 'bold',
color: '#333',
},
content: {
flex: 1,
padding: 16,
},
label: {
fontSize: 16,
fontWeight: '600',
color: '#333',
marginBottom: 8,
},
input: {
flex: 1,
fontSize: 16,
color: '#333',
borderWidth: 1,
borderColor: '#E0E0E0',
borderRadius: 8,
padding: 12,
textAlignVertical: 'top',
minHeight: 120,
},
charCount: {
textAlign: 'right',
color: '#999',
fontSize: 12,
marginTop: 8,
},
footer: {
flexDirection: 'row',
padding: 16,
borderTopWidth: 1,
borderTopColor: '#E0E0E0',
gap: 12,
},
cancelButton: {
flex: 1,
padding: 16,
borderRadius: 12,
alignItems: 'center',
borderWidth: 1,
borderColor: '#E0E0E0',
},
cancelButtonText: {
color: '#666',
fontSize: 16,
fontWeight: '600',
},
addButton: {
flex: 1,
backgroundColor: '#007AFF',
padding: 16,
borderRadius: 12,
alignItems: 'center',
},
addButtonDisabled: {
backgroundColor: '#E0E0E0',
},
buttonDisabled: {
opacity: 0.5,
},
addButtonText: {
color: 'white',
fontSize: 16,
fontWeight: '600',
},
});
export default AddTodoModal;
Файл src/components/Icon.tsx
import React from 'react';
import { Text, StyleSheet } from 'react-native';
interface IconProps {
name: string;
size?: number;
color?: string;
style?: any;
}
const Icon: React.FC<IconProps> = ({ name, size = 24, color = '#000', style }) => {
const iconMap: { [key: string]: string } = {
'add': '+',
'check-circle': '✓',
'radio-button-unchecked': '○',
'delete': '×',
'close': '×',
'check-circle-outline': '○',
'hourglass-empty': '⏳',
};
return (
<Text style={[
styles.icon,
{ fontSize: size, color },
style
]}>
{iconMap[name] || '?'}
</Text>
);
};
const styles = StyleSheet.create({
icon: {
fontFamily: 'System',
fontWeight: 'bold',
textAlign: 'center',
},
});
export default Icon;
Файл src/hooks/useTodoStorage.ts
import { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Todo } from '../types';
const STORAGE_KEY = '@todos';
export const useTodoStorage = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [isLoading, setIsLoading] = useState(true);
// Загрузка задач из хранилища
const loadTodos = async () => {
try {
const storedTodos = await AsyncStorage.getItem(STORAGE_KEY);
if (storedTodos) {
const parsedTodos: Todo[] = JSON.parse(storedTodos).map((todo: any) => ({
...todo,
createdAt: new Date(todo.createdAt)
}));
setTodos(parsedTodos);
}
} catch (error) {
console.error('Ошибка загрузки задач:', error);
} finally {
setIsLoading(false);
}
};
// Сохранение задач в хранилище
const saveTodos = async (newTodos: Todo[]) => {
try {
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(newTodos));
setTodos(newTodos);
} catch (error) {
console.error('Ошибка сохранения задач:', error);
}
};
// Добавление новой задачи
const addTodo = async (text: string) => {
const newTodo: Todo = {
id: Date.now().toString(),
text: text.trim(),
completed: false,
createdAt: new Date()
};
const newTodos = [newTodo, ...todos];
await saveTodos(newTodos);
return newTodo;
};
// Переключение статуса задачи
const toggleTodo = async (id: string) => {
const newTodos = todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
);
await saveTodos(newTodos);
};
// Удаление задачи
const deleteTodo = async (id: string) => {
const newTodos = todos.filter(todo => todo.id !== id);
await saveTodos(newTodos);
};
// Редактирование задачи
const editTodo = async (id: string, newText: string) => {
const newTodos = todos.map(todo =>
todo.id === id ? { ...todo, text: newText.trim() } : todo
);
await saveTodos(newTodos);
};
// Очистка всех выполненных задач
const clearCompleted = async () => {
const newTodos = todos.filter(todo => !todo.completed);
await saveTodos(newTodos);
};
// Очистка всех задач
const clearAll = async () => {
await saveTodos([]);
};
// Загрузка начальных данных
useEffect(() => {
loadTodos();
}, []);
return {
todos,
isLoading,
addTodo,
toggleTodo,
deleteTodo,
editTodo,
clearCompleted,
clearAll,
refresh: loadTodos
};
};
Файл src/screens/HomeScreen.tsx
import React, { useState } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
SafeAreaView,
StatusBar,
Alert,
RefreshControl,
Modal,
ScrollView
} from 'react-native';
import Icon from '../components/Icon';
import { useTodoStorage } from '../hooks/useTodoStorage';
import { formatDate } from '../utils/dateUtils';
import AddTodoModal from '../components/AddTodoModal';
import { Todo } from '../types';
const HomeScreen: React.FC = () => {
const {
todos,
isLoading,
addTodo,
toggleTodo,
deleteTodo,
refresh
} = useTodoStorage();
const [isAddModalVisible, setIsAddModalVisible] = useState(false);
const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
const [selectedTask, setSelectedTask] = useState<Todo | null>(null);
const [refreshing, setRefreshing] = useState(false);
const handleDeleteTodo = (id: string, text: string) => {
Alert.alert(
'Удаление задачи',
`Удалить задачу "${text.length > 30 ? text.substring(0, 30) + '...' : text}"?`,
[
{ text: 'Отмена', style: 'cancel' },
{
text: 'Удалить',
style: 'destructive',
onPress: () => deleteTodo(id)
}
]
);
};
const handleAddTodo = async (text: string) => {
await addTodo(text);
};
const onRefresh = async () => {
setRefreshing(true);
await refresh();
setRefreshing(false);
};
const handleTaskPress = (task: Todo) => {
setSelectedTask(task);
setIsDetailModalVisible(true);
};
const closeDetailModal = () => {
setIsDetailModalVisible(false);
setSelectedTask(null);
};
const completedTodosCount = todos.filter(todo => todo.completed).length;
const renderTodoItem = ({ item }: { item: any }) => (
<TouchableOpacity
style={styles.todoItem}
onPress={() => handleTaskPress(item)}
activeOpacity={0.7}
>
<TouchableOpacity
style={styles.checkbox}
onPress={(e) => {
e.stopPropagation();
toggleTodo(item.id);
}}
>
<Icon
name={item.completed ? 'check-circle' : 'radio-button-unchecked'}
size={24}
color={item.completed ? '#4CAF50' : '#757575'}
/>
</TouchableOpacity>
<View style={styles.todoContent}>
<View style={styles.todoTextContainer}>
<Text
style={[
styles.todoText,
item.completed && styles.completedTodoText
]}
numberOfLines={2}
>
{item.text}
</Text>
<Text style={styles.todoDate}>
{formatDate(item.createdAt)}
</Text>
</View>
<View style={styles.actionsContainer}>
{item.text.length > 50 && (
<Text style={styles.moreIndicator}>...</Text>
)}
<TouchableOpacity
style={styles.deleteButton}
onPress={(e) => {
e.stopPropagation();
handleDeleteTodo(item.id, item.text);
}}
>
<Icon name="delete" size={20} color="#F44336" />
</TouchableOpacity>
</View>
</View>
</TouchableOpacity>
);
if (isLoading) {
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="dark-content" />
<View style={styles.loadingContainer}>
<Icon name="hourglass-empty" size={48} color="#007AFF" />
<Text style={styles.loadingText}>Загрузка задач...</Text>
</View>
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="dark-content" />
<View style={styles.header}>
<Text style={styles.title}>Мои задачи</Text>
<View style={styles.progressContainer}>
<Text style={styles.subtitle}>
Выполнено: {completedTodosCount} из {todos.length}
</Text>
{todos.length > 0 && (
<View style={styles.progressBar}>
<View
style={[
styles.progressFill,
{ width: `${(completedTodosCount / todos.length) * 100}%` }
]}
/>
</View>
)}
</View>
</View>
{todos.length === 0 ? (
<View style={styles.emptyState}>
<Icon name="check-circle-outline" size={64} color="#E0E0E0" />
<Text style={styles.emptyStateText}>Нет задач</Text>
<Text style={styles.emptyStateSubtext}>
Добавьте новую задачу, нажав на кнопку ниже
</Text>
</View>
) : (
<FlatList
data={todos}
renderItem={renderTodoItem}
keyExtractor={item => item.id}
style={styles.todoList}
showsVerticalScrollIndicator={false}
contentContainerStyle={styles.todoListContent}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={['#007AFF']}
tintColor="#007AFF"
/>
}
/>
)}
<TouchableOpacity
style={styles.addButton}
onPress={() => setIsAddModalVisible(true)}
activeOpacity={0.8}
>
<Icon name="add" size={24} color="white" />
<Text style={styles.addButtonText}>Добавить задачу</Text>
</TouchableOpacity>
{/* Модальное окно добавления задачи */}
<AddTodoModal
visible={isAddModalVisible}
onClose={() => setIsAddModalVisible(false)}
onAddTodo={handleAddTodo}
/>
{/* Модальное окно просмотра деталей задачи */}
<Modal
visible={isDetailModalVisible}
animationType="slide"
onRequestClose={closeDetailModal}
>
<View style={styles.detailContainer}>
<View style={styles.detailHeader}>
<TouchableOpacity
style={styles.backButton}
onPress={closeDetailModal}
>
<Icon name="close" size={24} color="#333" />
</TouchableOpacity>
<Text style={styles.detailTitle}>Детали задачи</Text>
<View style={styles.headerPlaceholder} />
</View>
<ScrollView style={styles.detailContent}>
{selectedTask && (
<>
<View style={styles.taskCard}>
<View style={styles.statusBadge}>
<Icon
name={selectedTask.completed ? 'check-circle' : 'radio-button-unchecked'}
size={16}
color={selectedTask.completed ? '#4CAF50' : '#757575'}
/>
<Text style={[
styles.statusText,
selectedTask.completed && styles.statusCompleted
]}>
{selectedTask.completed ? 'Выполнено' : 'В процессе'}
</Text>
</View>
<Text style={styles.fullTaskText}>
{selectedTask.text}
</Text>
<View style={styles.dateContainer}>
<Text style={styles.dateLabel}>Создана:</Text>
<Text style={styles.dateValue}>{formatDate(selectedTask.createdAt)}</Text>
</View>
</View>
<View style={styles.taskInfo}>
<Text style={styles.infoTitle}>Информация о задаче</Text>
<View style={styles.infoItem}>
<Text style={styles.infoLabel}>Статус:</Text>
<Text style={[
styles.infoValue,
selectedTask.completed ? styles.completedValue : styles.pendingValue
]}>
{selectedTask.completed ? 'Завершена' : 'Ожидает выполнения'}
</Text>
</View>
<View style={styles.infoItem}>
<Text style={styles.infoLabel}>Длина текста:</Text>
<Text style={styles.infoValue}>{selectedTask.text.length} символов</Text>
</View>
<View style={styles.infoItem}>
<Text style={styles.infoLabel}>Дата создания:</Text>
<Text style={styles.infoValue}>
{selectedTask.createdAt.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</Text>
</View>
</View>
</>
)}
</ScrollView>
</View>
</Modal>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f8f9fa',
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingTop: 50, // Добавляем отступ сверху для безопасной области
},
loadingText: {
marginTop: 16,
fontSize: 16,
color: '#666',
},
header: {
padding: 20,
paddingTop: 50, // Отступ для статус бара
backgroundColor: 'white',
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 3,
elevation: 3,
},
title: {
fontSize: 28,
fontWeight: 'bold',
color: '#333',
marginBottom: 10,
},
progressContainer: {
marginTop: 5,
},
subtitle: {
fontSize: 16,
color: '#666',
marginBottom: 8,
},
progressBar: {
height: 6,
backgroundColor: '#E0E0E0',
borderRadius: 3,
overflow: 'hidden',
},
progressFill: {
height: '100%',
backgroundColor: '#4CAF50',
borderRadius: 3,
},
todoList: {
flex: 1,
},
todoListContent: {
padding: 10,
},
todoItem: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'white',
padding: 15,
marginVertical: 5,
borderRadius: 12,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.1,
shadowRadius: 3,
elevation: 2,
},
checkbox: {
marginRight: 15,
},
todoContent: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
todoTextContainer: {
flex: 1,
marginRight: 10,
},
todoText: {
fontSize: 16,
color: '#333',
lineHeight: 20,
},
completedTodoText: {
textDecorationLine: 'line-through',
color: '#999',
},
todoDate: {
fontSize: 12,
color: '#999',
marginTop: 4,
},
actionsContainer: {
flexDirection: 'row',
alignItems: 'center',
},
moreIndicator: {
color: '#007AFF',
fontSize: 16,
fontWeight: 'bold',
marginRight: 8,
},
deleteButton: {
padding: 8,
borderRadius: 6,
backgroundColor: '#FFEBEE',
},
emptyState: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
paddingTop: 100, // Отступ сверху
},
emptyStateText: {
fontSize: 20,
color: '#999',
marginTop: 16,
marginBottom: 8,
fontWeight: '600',
},
emptyStateSubtext: {
fontSize: 14,
color: '#999',
textAlign: 'center',
lineHeight: 20,
},
addButton: {
flexDirection: 'row',
backgroundColor: '#007AFF',
margin: 20,
marginBottom: 30, // Отступ снизу для безопасной области
padding: 16,
borderRadius: 12,
alignItems: 'center',
justifyContent: 'center',
shadowColor: '#007AFF',
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 5,
},
addButtonText: {
color: 'white',
fontSize: 16,
fontWeight: '600',
marginLeft: 8,
},
// Стили для модального окна деталей
detailContainer: {
flex: 1,
backgroundColor: '#f8f9fa',
paddingTop: 50, // Отступ для статус бара
},
detailHeader: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
padding: 16,
backgroundColor: 'white',
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
backButton: {
padding: 8,
},
detailTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
},
headerPlaceholder: {
width: 40,
},
detailContent: {
flex: 1,
padding: 16,
},
taskCard: {
backgroundColor: 'white',
padding: 20,
borderRadius: 12,
marginBottom: 16,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
statusBadge: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 16,
},
statusText: {
marginLeft: 8,
fontSize: 14,
color: '#757575',
fontWeight: '500',
},
statusCompleted: {
color: '#4CAF50',
},
fullTaskText: {
fontSize: 16,
lineHeight: 24,
color: '#333',
marginBottom: 16,
},
dateContainer: {
flexDirection: 'row',
alignItems: 'center',
},
dateLabel: {
fontSize: 14,
color: '#666',
marginRight: 8,
},
dateValue: {
fontSize: 14,
color: '#333',
fontWeight: '500',
},
taskInfo: {
backgroundColor: 'white',
padding: 20,
borderRadius: 12,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
infoTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
marginBottom: 16,
},
infoItem: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 12,
borderBottomWidth: 1,
borderBottomColor: '#f0f0f0',
},
infoLabel: {
fontSize: 14,
color: '#666',
},
infoValue: {
fontSize: 14,
fontWeight: '500',
color: '#333',
},
completedValue: {
color: '#4CAF50',
},
pendingValue: {
color: '#FF9800',
},
});
export default HomeScreen;
Файл src/screens/TaskDetailScreen.tsx
import React from 'react';
import {
View,
Text,
StyleSheet,
ScrollView,
TouchableOpacity,
SafeAreaView,
StatusBar
} from 'react-native';
import Icon from '../components/Icon';
import { Todo } from '../types';
import { formatDate } from '../utils/dateUtils';
interface TaskDetailScreenProps {
route: {
params: {
task: Todo;
};
};
navigation: any;
}
const TaskDetailScreen: React.FC<TaskDetailScreenProps> = ({ route, navigation }) => {
const { task } = route.params;
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="dark-content" backgroundColor="#ffffff" />
<View style={styles.header}>
<TouchableOpacity
style={styles.backButton}
onPress={() => navigation.goBack()}
>
<Icon name="close" size={24} color="#333" />
</TouchableOpacity>
<Text style={styles.headerTitle}>Детали задачи</Text>
<View style={styles.headerPlaceholder} />
</View>
<ScrollView style={styles.content}>
<View style={styles.taskCard}>
<View style={styles.statusBadge}>
<Icon
name={task.completed ? 'check-circle' : 'radio-button-unchecked'}
size={16}
color={task.completed ? '#4CAF50' : '#757575'}
/>
<Text style={[
styles.statusText,
task.completed && styles.statusCompleted
]}>
{task.completed ? 'Выполнено' : 'В процессе'}
</Text>
</View>
<Text style={styles.taskText}>
{task.text}
</Text>
<View style={styles.dateContainer}>
<Text style={styles.dateLabel}>Создана:</Text>
<Text style={styles.dateValue}>{formatDate(task.createdAt)}</Text>
</View>
</View>
<View style={styles.taskInfo}>
<Text style={styles.infoTitle}>Информация о задаче</Text>
<View style={styles.infoItem}>
<Text style={styles.infoLabel}>Статус:</Text>
<Text style={[
styles.infoValue,
task.completed ? styles.completedValue : styles.pendingValue
]}>
{task.completed ? 'Завершена' : 'Ожидает выполнения'}
</Text>
</View>
<View style={styles.infoItem}>
<Text style={styles.infoLabel}>Длина текста:</Text>
<Text style={styles.infoValue}>{task.text.length} символов</Text>
</View>
<View style={styles.infoItem}>
<Text style={styles.infoLabel}>Дата создания:</Text>
<Text style={styles.infoValue}>
{task.createdAt.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</Text>
</View>
</View>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f8f9fa',
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
padding: 16,
backgroundColor: 'white',
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
backButton: {
padding: 8,
},
headerTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
},
headerPlaceholder: {
width: 40,
},
content: {
flex: 1,
padding: 16,
},
taskCard: {
backgroundColor: 'white',
padding: 20,
borderRadius: 12,
marginBottom: 16,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
statusBadge: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 16,
},
statusText: {
marginLeft: 8,
fontSize: 14,
color: '#757575',
fontWeight: '500',
},
statusCompleted: {
color: '#4CAF50',
},
taskText: {
fontSize: 16,
lineHeight: 24,
color: '#333',
marginBottom: 16,
},
dateContainer: {
flexDirection: 'row',
alignItems: 'center',
},
dateLabel: {
fontSize: 14,
color: '#666',
marginRight: 8,
},
dateValue: {
fontSize: 14,
color: '#333',
fontWeight: '500',
},
taskInfo: {
backgroundColor: 'white',
padding: 20,
borderRadius: 12,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
infoTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
marginBottom: 16,
},
infoItem: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 12,
borderBottomWidth: 1,
borderBottomColor: '#f0f0f0',
},
infoLabel: {
fontSize: 14,
color: '#666',
},
infoValue: {
fontSize: 14,
fontWeight: '500',
color: '#333',
},
completedValue: {
color: '#4CAF50',
},
pendingValue: {
color: '#FF9800',
},
});
export default TaskDetailScreen;
Файл src/types/index.ts
export interface Todo {
id: string;
text: string;
completed: boolean;
createdAt: Date;
}
export interface TodoStorage {
todos: Todo[];
isLoading: boolean;
addTodo: (text: string) => Promise<Todo>;
toggleTodo: (id: string) => Promise<void>;
deleteTodo: (id: string) => Promise<void>;
editTodo: (id: string, newText: string) => Promise<void>;
clearCompleted: () => Promise<void>;
clearAll: () => Promise<void>;
refresh: () => Promise<void>;
}
Файл src/utils/dateUtils.ts
export const formatDate = (date: Date): string => {
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
if (date.toDateString() === today.toDateString()) {
return 'Сегодня';
} else if (date.toDateString() === yesterday.toDateString()) {
return 'Вчера';
} else {
return date.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric'
});
}
};
export const isToday = (date: Date): boolean => {
const today = new Date();
return date.toDateString() === today.toDateString();
};
export const isYesterday = (date: Date): boolean => {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
return date.toDateString() === yesterday.toDateString();
};
Запуск
npm run android
// или
npm run ios
Сборка
Настройка подписи приложения
Создаём ключ для подписи:
keytool -genkey -v -keystore todo-app-key.keystore -alias todo-app -keyalg RSA -keysize 2048 -validity 10000
Параметры которые нужно ввести:
- Пароль для хранилища ключей: (придумайте надежный пароль)
- Имя и фамилия: Ваше Имя
- Название организационной единицы: (можно пропустить)
- Название организации: (можно пропустить)
- Название города: Ваш город
- Область: Ваш регион
- Двухбуквенный код страны: RU
- Подтвердить данные: yes
Переместите ключ в папку android/app:
move todo-app-key.keystore android\app\
Настройка gradle для подписи
Создадим (если нет) файл android/gradle.properties и добавим:
MYAPP_UPLOAD_STORE_FILE=todo-app-key.keystore
MYAPP_UPLOAD_KEY_ALIAS=todo-app
MYAPP_UPLOAD_STORE_PASSWORD=ваш_пароль
MYAPP_UPLOAD_KEY_PASSWORD=ваш_пароль
Обновим android/app/build.gradle:
android {
// ... существующий код
signingConfigs {
release {
if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
storeFile file(MYAPP_UPLOAD_STORE_FILE)
storePassword MYAPP_UPLOAD_STORE_PASSWORD
keyAlias MYAPP_UPLOAD_KEY_ALIAS
keyPassword MYAPP_UPLOAD_KEY_PASSWORD
}
}
}
buildTypes {
release {
// ... существующий код
signingConfig signingConfigs.release
}
}
}
Сборка Release APK
# Сборка напрямую
cd android
./gradlew assembleRelease
# Сборка с очисткой
cd android
./gradlew clean
./gradlew assembleRelease
Собранный APK можно будет найти здесь:
android/app/build/outputs/apk/release/app-release.apk
Установка на устройство
Через ADB:
adb install android/app/build/outputs/apk/release/app-release.apk
Или вручную:
- Скопируем app-release.apk на телефон
- Откроем файловый менеджер на телефоне
- Найдём и установим APK файл
- Разрешим установку из неизвестных источников (если потребуется)
Сборка AAB (для Google Play)
Если планируется публикация в Google Play:
cd android
./gradlew bundleRelease
AAB файл будет здесь:
android/app/build/outputs/bundle/release/app-release.aab
Упрощенная сборка без подписи (для тестирования)
Если не хотите настраивать подпись, можно собрать unsigned APK. Обновите android/app/build.gradle:
buildTypes {
release {
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
Затем соберите:
cd android
./gradlew assembleRelease
Оптимизация размера APK
Включение сжатия и минификации:
android {
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// Для Flutter:
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
shrinkResources false
}
}
}