-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExerciseScreen.tsxgg
More file actions
356 lines (326 loc) · 9.56 KB
/
ExerciseScreen.tsxgg
File metadata and controls
356 lines (326 loc) · 9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import React, { useState, useEffect } from 'react';
import {
View,
ScrollView,
TouchableOpacity,
Text,
FlatList,
StyleSheet,
Platform,
Image,
} from 'react-native';
import SQLite from 'react-native-sqlite-storage';
SQLite.DEBUG(true);
SQLite.enablePromise(true);
const openDatabase = async () => {
// Try multiple strategies and provide detailed logging to help diagnose failures.
// Many common issues:
// - Prepopulated DB must be placed in platform-specific bundle locations
// Android: android/app/src/main/assets/www/<dbfile>
// iOS: add file to Xcode bundle (Copy Bundle Resources)
// - createFromLocation option may be required to copy from bundle on first run
const name = 'exercise.db';
// Attempt 1: use createFromLocation (recommended for prepopulated DB)
try {
const opts: any = {
name,
location: 'default',
createFromLocation: 1,
};
// assetFilename is only used in some platforms/versions; include for iOS fallback
if (Platform.OS === 'ios') {
opts.assetFilename = name;
}
const db = await SQLite.openDatabase(opts);
console.log('✅ DB 연결 성공 (createFromLocation)');
return db;
} catch (err1) {
console.warn('DB 연결 실패 (createFromLocation):', err1);
// Attempt 2: try opening without createFromLocation (database may be created/copied by other setup)
try {
const db = await SQLite.openDatabase({ name, location: 'default' });
console.log('✅ DB 연결 성공 (without createFromLocation)');
return db;
} catch (err2) {
console.error('DB 연결 두번째 시도 실패:', err2);
// Provide actionable hint in the thrown error message
const hint = `Ensure ${name} is bundled in the native app: Android -> android/app/src/main/assets/www/${name} (or assets/), iOS -> add to Xcode Copy Bundle Resources. See react-native-sqlite-storage docs.`;
const finalError = new Error(`DB open failed. ${hint} Original errors: ${err1}; ${err2}`);
// attach original errors
(finalError as any).original = { err1, err2 };
throw finalError;
}
}
};
const ExerciseScreen = () => {
const [selectedCategory, setSelectedCategory] = useState(null);
const [categories, setCategories] = useState([]);
const [exercises, setExercises] = useState([]);
const [selectedExercise, setSelectedExercise] = useState(null);
useEffect(() => {
const init = async () => {
const data = await fetchCategories();
setCategories(data);
if (data.length > 0) {
setSelectedCategory(data[0].id); // ⭐ 최초 선택
}
};
init();
}, []);
useEffect(() => {
if (selectedCategory) {
fetchExercises(selectedCategory).then(setExercises);
setSelectedExercise(null); // 카테고리 바뀌면 상세화면 닫기
}
}, [selectedCategory]);
const fetchCategories = async () => {
try {
const db = await openDatabase();
console.log(db);
return new Promise((resolve, reject) => {
db.transaction(tx => {
console.log('카테고리 조회 시작');
tx.executeSql(
'SELECT * FROM exercise_categories',
[],
(tx, results) => {
const rows = results.rows;
const categories = [];
for (let i = 0; i < rows.length; i++) {
categories.push(rows.item(i));
}
console.log('카테고리 조회 성공:', categories);
resolve(categories);
},
(tx, error) => {
console.error('쿼리 실패:', error);
reject(error);
}
);
});
});
} catch (err) {
console.error('전체 실패:', err);
return [];
}
};
const fetchExercises = async (categoryId) => {
try {
const db = await openDatabase();
console.log(db);
return new Promise((resolve, reject) => {
db.transaction(tx => {
console.log('운동 조회 시작');
tx.executeSql('SELECT e.*, p.picture_url FROM exercises e LEFT JOIN exercise_pictures p ON p.id = ( SELECT id FROM exercise_pictures WHERE exercise_id = e.id ORDER BY id ASC LIMIT 1) WHERE e.exercise_category_id = ?;',
[categoryId],
(tx, results) => {
const rows = results.rows;
const exercises = [];
for (let i = 0; i < rows.length; i++) {
exercises.push(rows.item(i));
}
console.log('운동 조회 성공:', exercises);
resolve(exercises);
},
(tx, error) => {
console.error('쿼리 실패:', error);
reject(error);
}
);
});
});
} catch (err) {
console.error('전체 실패:', err);
return [];
}
};
const renderCategoryItem = (category) => (
<TouchableOpacity
key={category.id} // 'category' 객체에 id가 있다고 가정
style={[
styles.categoryButton,
selectedCategory === category.id && styles.categoryButtonActive,
]}
onPress={() => setSelectedCategory(category.id)} // id로 selectedCategory 상태 변경
>
<Text
style={[
styles.categoryText,
selectedCategory === category.id && styles.categoryTextActive,
]}
>
{category.title}
</Text>
</TouchableOpacity>
);
const renderExerciseItem = ({item}) => {
console.log('Rendering exercise item:', item);
return (
<TouchableOpacity
style={styles.exerciseItem}
onPress={() => setSelectedExercise(item)}
>
<View style={styles.exerciseImageContainer}>
{item.picture_url ? (
<Image
source={{uri: `https://humake.blob.core.windows.net/humake/exercise/${item.picture_url}`}}
style={styles.exerciseImage}
resizeMode="cover"
/>
) : (
<Image
source={require('./assets/photo_none.gif')}
style={styles.exerciseImage}
resizeMode="cover"
/>
)}
</View>
<View style={styles.exerciseInfo}>
<Text>{item.title}</Text>
<Text style={{ color : '#ff8d1d', fontWeight: 'bold'}}>{item.content}</Text>
</View>
</TouchableOpacity>
);
};
const renderExerciseDetail = () => (
<View style={styles.detailContainer}>
<TouchableOpacity onPress={() => setSelectedExercise(null)} style={styles.backButton}>
<Text style={styles.backButtonText}>← 목록으로</Text>
</TouchableOpacity>
<View style={styles.exerciseImageContainer}>
{selectedExercise.picture_url ? (
<Image
source={{ uri: `https://humake.blob.core.windows.net/humake/exercise/medium_thumb_${selectedExercise.picture_url}` }}
style={styles.exerciseImage}
resizeMode="cover"
/>
) : (
<Image
source={require('./assets/photo_none.gif')}
style={styles.exerciseImage}
resizeMode="cover"
/>
)}
</View>
<Text style={styles.itemTextActive}>
{selectedExercise.content}
</Text>
</View>
);
return (
<View style={styles.container}>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
style={styles.categoryScroll}
contentContainerStyle={styles.categoryContainer}
>
{categories.map(category => renderCategoryItem(category))}
</ScrollView>
{selectedExercise ? (
renderExerciseDetail()
) : (
<FlatList
data={exercises}
keyExtractor={(item) => item.id.toString()}
contentContainerStyle={styles.listContent}
renderItem={renderExerciseItem}
/>
)}
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#fff' },
categoryScroll: { paddingVertical: 10, maxHeight: 70, height: 70 },
categoryContainer: { paddingHorizontal: 10 },
categoryButton: {
paddingVertical: 8,
paddingHorizontal: 16,
backgroundColor: '#eee',
borderRadius: 20,
marginRight: 8,
justifyContent: 'center',
alignItems: 'center',
},
categoryButtonActive: {
backgroundColor: '#007AFF',
},
categoryText: {
color: '#333',
},
categoryTextActive: {
color: '#fff',
},
listContent: {
padding: 16,
},
itemBox: {
padding: 16,
borderBottomWidth: 1,
borderColor: '#ddd',
},
itemText: {
fontSize: 16,
},
itemTextActive: {
color: '#007AFF',
},
exerciseItem: {
flexDirection: 'row',
alignItems: 'center',
padding: 12,
marginBottom: 12,
backgroundColor: '#fafafa',
borderRadius: 10,
borderWidth: 1,
borderColor: '#eee',
},
exerciseImageContainer: {
width: 60,
height: 70,
marginRight: 16,
borderRadius: 8,
overflow: 'hidden',
backgroundColor: '#eee',
justifyContent: 'center',
alignItems: 'center',
},
exerciseImage: {
width: 60,
height: 60,
},
exerciseInfo: {
flex: 1,
justifyContent: 'center',
},
detailContainer: {
flex: 1,
padding: 16,
backgroundColor: '#fff',
justifyContent: 'flex-start',
},
backButton: {
marginBottom: 16,
alignSelf: 'flex-start',
paddingHorizontal: 12,
paddingVertical: 6,
backgroundColor: '#eee',
borderRadius: 8,
},
backButtonText: {
color: '#007AFF',
fontSize: 16,
fontWeight: 'bold',
},
itemTextActive: {
color: '#ff8d1d',
backgroundColor: '#eee',
borderRadius: 8,
fontWeight: 'bold',
fontSize: 20,
marginVertical: 10,
padding: 16,
},
});
export default ExerciseScreen;