expo-utils-mng 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-utils-mng",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Expo reusable TypeScript utilities",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.cjs",
@@ -14,7 +14,11 @@
14
14
  }
15
15
  },
16
16
  "files": [
17
- "dist"
17
+ "src",
18
+ "dist",
19
+ "package.json",
20
+ "tsconfig.json",
21
+ "README.md"
18
22
  ],
19
23
  "scripts": {
20
24
  "build": "tsup src/index.ts --format esm,cjs --dts",
@@ -24,4 +28,4 @@
24
28
  "tsup": "^8.5.1",
25
29
  "typescript": "^5.9.3"
26
30
  }
27
- }
31
+ }
@@ -0,0 +1,170 @@
1
+ import React, { useCallback, useEffect, useLayoutEffect, useState } from 'react';
2
+ import { View, Text, FlatList, ActivityIndicator, Switch, TextInput, Button, RefreshControl, Image, StyleSheet } from 'react-native';
3
+ import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
4
+ import { NavigationContainer } from '@react-navigation/native';
5
+ import { createNativeStackNavigator } from '@react-navigation/native-stack';
6
+ import { Provider, useDispatch, useSelector } from 'react-redux';
7
+ import AsyncStorage from '@react-native-async-storage/async-storage';
8
+ import HomestayCard from './components/HomestayCard';
9
+ import { Homestay } from './types/homestay';
10
+ import { formatVND } from './utils/format';
11
+ import { loadHomestays } from './services/homestayService';
12
+ import data from './data/homestays.json';
13
+ import { store, addHomestay, removeHomestay, setHomestays, clearHomestays,
14
+ selectSavedItems, selectSavedCount, selectSavedTotal } from './store';
15
+
16
+ const Stack = createNativeStackNavigator<any>();
17
+ const KEY = '@homestay_saved_items';
18
+ const ALL = data as Homestay[];
19
+
20
+ // ===== Câu 1-5 (+6c, 7b) =====
21
+ function Home({ navigation }: any) {
22
+ const [items, setItems] = useState<Homestay[]>([]);
23
+ const [loading, setLoading] = useState(true);
24
+ const [refreshing, setRefreshing] = useState(false);
25
+ const [isTile, setIsTile] = useState(false);
26
+ const [q, setQ] = useState('');
27
+ const [selected, setSelected] = useState('');
28
+ const [updatedAt, setUpdatedAt] = useState('');
29
+ const count = useSelector(selectSavedCount);
30
+
31
+ const fetchData = async () => {
32
+ setItems(await loadHomestays());
33
+ setUpdatedAt(new Date().toTimeString().slice(0, 8));
34
+ };
35
+ useEffect(() => { fetchData().finally(() => setLoading(false)); }, []);
36
+ const onRefresh = async () => { setRefreshing(true); await fetchData(); setRefreshing(false); };
37
+
38
+ const onSelect = useCallback((id: string) => {
39
+ setSelected(ALL.find(h => h.id === id)?.name ?? '');
40
+ navigation.navigate('Detail', { id });
41
+ }, [navigation]);
42
+
43
+ const numColumns = isTile ? 2 : 1;
44
+ const k = q.trim().toLowerCase();
45
+ const list = items.filter(h => h.name.toLowerCase().includes(k) || h.city.toLowerCase().includes(k));
46
+
47
+ return (
48
+ <SafeAreaView style={s.box}>
49
+ <Text style={s.title}>Homestay Booking</Text>
50
+ {updatedAt !== '' && <Text>Cập nhật lúc: {updatedAt}</Text>}
51
+ <View style={s.row}>
52
+ <Text>Dạng lưới</Text>
53
+ <Switch value={isTile} onValueChange={setIsTile} />
54
+ <Button title="Làm mới" onPress={onRefresh} />
55
+ <Button title={`Homestay đã lưu (${count})`} onPress={() => navigation.navigate('Saved')} />
56
+ </View>
57
+ <View style={s.row}>
58
+ <TextInput style={s.input} placeholder="Tìm homestay hoặc thành phố..." value={q} onChangeText={setQ} />
59
+ <Button title="Xóa" onPress={() => setQ('')} />
60
+ </View>
61
+ {selected !== '' && <Text>Đã chọn: {selected}</Text>}
62
+ {loading ? (
63
+ <ActivityIndicator size="large" />
64
+ ) : (
65
+ <FlatList
66
+ key={String(numColumns)}
67
+ data={list}
68
+ numColumns={numColumns}
69
+ keyExtractor={h => h.id}
70
+ columnWrapperStyle={numColumns > 1 ? { justifyContent: 'space-between' } : undefined}
71
+ renderItem={({ item }) => (
72
+ <HomestayCard homestay={item} layout={isTile ? 'tile' : 'row'} onSelect={onSelect} />
73
+ )}
74
+ refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
75
+ ListEmptyComponent={<Text>Không tìm thấy homestay.</Text>}
76
+ />
77
+ )}
78
+ </SafeAreaView>
79
+ );
80
+ }
81
+
82
+ // ===== Câu 6b, 7c =====
83
+ function Detail({ route, navigation }: any) {
84
+ const h = ALL.find(x => x.id === route.params.id);
85
+ const saved = useSelector(selectSavedItems).some(x => x.id === route.params.id);
86
+ const dispatch = useDispatch();
87
+ useLayoutEffect(() => { navigation.setOptions({ title: h?.name ?? '' }); }, [navigation, h]);
88
+ if (!h) return <Text>Không tìm thấy</Text>;
89
+ return (
90
+ <View style={s.box}>
91
+ <Image source={{ uri: h.image }} style={{ width: '100%', aspectRatio: 4 / 3, borderRadius: 8 }} />
92
+ <Text style={s.title}>{h.name}</Text>
93
+ <Text>{h.city} · {h.guests} khách</Text>
94
+ <Text>{formatVND(h.price)}/đêm · ⭐ {h.rating.toFixed(1)}</Text>
95
+ <Text>{h.isAvailable ? '✅ Còn phòng' : '❌ Hết phòng'}</Text>
96
+ <Button
97
+ title={!h.isAvailable ? 'Hết phòng' : saved ? 'Bỏ lưu' : 'Lưu homestay'}
98
+ disabled={!h.isAvailable}
99
+ onPress={() => dispatch(saved ? removeHomestay(h.id) : addHomestay(h))}
100
+ />
101
+ </View>
102
+ );
103
+ }
104
+
105
+ // ===== Câu 8a, 8c =====
106
+ function Saved() {
107
+ const items = useSelector(selectSavedItems);
108
+ const total = useSelector(selectSavedTotal);
109
+ const dispatch = useDispatch();
110
+ const clearAll = () => { dispatch(clearHomestays()); AsyncStorage.removeItem(KEY); };
111
+ return (
112
+ <View style={s.box}>
113
+ <FlatList
114
+ data={items}
115
+ keyExtractor={h => h.id}
116
+ renderItem={({ item }) => (
117
+ <View style={s.row}>
118
+ <Text style={{ flex: 1 }}>{item.name} - {formatVND(item.price)}/đêm</Text>
119
+ <Button title="Bỏ lưu" onPress={() => dispatch(removeHomestay(item.id))} />
120
+ </View>
121
+ )}
122
+ ListEmptyComponent={<Text>Chưa có homestay nào.</Text>}
123
+ />
124
+ <Text style={s.title}>Tổng: {formatVND(total)}</Text>
125
+ <Button title="Xóa tất cả" color="red" onPress={clearAll} />
126
+ </View>
127
+ );
128
+ }
129
+
130
+ // ===== Câu 8b: đồng bộ AsyncStorage =====
131
+ function StorageSync() {
132
+ const items = useSelector(selectSavedItems);
133
+ const dispatch = useDispatch();
134
+ const [hydrated, setHydrated] = useState(false);
135
+ useEffect(() => {
136
+ AsyncStorage.getItem(KEY).then(json => {
137
+ dispatch(setHomestays(json ? JSON.parse(json) : []));
138
+ setHydrated(true);
139
+ });
140
+ }, [dispatch]);
141
+ useEffect(() => {
142
+ if (hydrated) AsyncStorage.setItem(KEY, JSON.stringify(items));
143
+ }, [items, hydrated]);
144
+ return null;
145
+ }
146
+
147
+ // ===== Câu 1a, 6a, 7a =====
148
+ export default function App() {
149
+ return (
150
+ <Provider store={store}>
151
+ <StorageSync />
152
+ <SafeAreaProvider>
153
+ <NavigationContainer>
154
+ <Stack.Navigator>
155
+ <Stack.Screen name="Home" component={Home} options={{ headerShown: false }} />
156
+ <Stack.Screen name="Detail" component={Detail} />
157
+ <Stack.Screen name="Saved" component={Saved} options={{ title: 'Đã lưu' }} />
158
+ </Stack.Navigator>
159
+ </NavigationContainer>
160
+ </SafeAreaProvider>
161
+ </Provider>
162
+ );
163
+ }
164
+
165
+ const s = StyleSheet.create({
166
+ box: { flex: 1, padding: 12, backgroundColor: '#f6f4ef' },
167
+ title: { fontSize: 22, fontWeight: 'bold', marginVertical: 6 },
168
+ row: { flexDirection: 'row', alignItems: 'center', gap: 8, marginVertical: 4 },
169
+ input: { flex: 1, borderWidth: 1, borderColor: '#aaa', borderRadius: 6, padding: 8, backgroundColor: '#fff' },
170
+ });
@@ -0,0 +1,37 @@
1
+ import React from 'react';
2
+ import { TouchableOpacity, View, Text, Image, StyleSheet } from 'react-native';
3
+ import { Homestay } from '../types/homestay';
4
+ import { formatVND } from '../utils/format';
5
+
6
+ type Props = { homestay: Homestay; layout?: 'row' | 'tile'; onSelect: (id: string) => void };
7
+
8
+ function HomestayCard({ homestay: h, layout = 'row', onSelect }: Props) {
9
+ const isTile = layout === 'tile';
10
+ return (
11
+ <TouchableOpacity style={[s.card, isTile && s.cardTile]} onPress={() => onSelect(h.id)}>
12
+ <View>
13
+ <Image source={{ uri: h.image }} style={isTile ? s.imgTile : s.img} />
14
+ {isTile && <Text style={s.badge}>⭐ {h.rating.toFixed(1)}</Text>}
15
+ </View>
16
+ <View style={[s.info, isTile && s.infoTile]}>
17
+ <Text style={s.name} numberOfLines={isTile ? 1 : undefined}>{h.name}</Text>
18
+ {!isTile && <Text>{h.city}</Text>}
19
+ <Text>{h.guests} khách · {formatVND(h.price)}/đêm</Text>
20
+ {!isTile && <Text>⭐ {h.rating.toFixed(1)}</Text>}
21
+ <Text>{h.isAvailable ? '✅ Còn phòng' : '❌ Hết phòng'}</Text>
22
+ </View>
23
+ </TouchableOpacity>
24
+ );
25
+ }
26
+ export default React.memo(HomestayCard);
27
+
28
+ const s = StyleSheet.create({
29
+ card: { flexDirection: 'row', padding: 8, marginVertical: 4, backgroundColor: '#fff', borderRadius: 8 },
30
+ cardTile: { flexDirection: 'column', width: '48%' },
31
+ img: { width: 80, height: 80, borderRadius: 6 },
32
+ imgTile: { width: '100%', aspectRatio: 4 / 3, borderRadius: 6 },
33
+ badge: { position: 'absolute', top: 4, left: 4, backgroundColor: '#000a', color: '#fff', paddingHorizontal: 4 },
34
+ info: { flex: 1, marginLeft: 8 },
35
+ infoTile: { marginLeft: 0, marginTop: 6 },
36
+ name: { fontWeight: 'bold' },
37
+ });
@@ -0,0 +1,192 @@
1
+ [
2
+ {
3
+ "id": "h01",
4
+ "name": "Nhà gỗ bên hồ",
5
+ "city": "Đà Lạt",
6
+ "guests": 4,
7
+ "price": 850000,
8
+ "rating": 8.9,
9
+ "image": "https://picsum.photos/seed/home01/400/300",
10
+ "isAvailable": true
11
+ },
12
+ {
13
+ "id": "h02",
14
+ "name": "Phố cổ Garden House",
15
+ "city": "Hội An",
16
+ "guests": 2,
17
+ "price": 690000,
18
+ "rating": 9.2,
19
+ "image": "https://picsum.photos/seed/home02/400/300",
20
+ "isAvailable": true
21
+ },
22
+ {
23
+ "id": "h03",
24
+ "name": "Sapa Cloud Hill",
25
+ "city": "Sa Pa",
26
+ "guests": 6,
27
+ "price": 1250000,
28
+ "rating": 8.6,
29
+ "image": "https://picsum.photos/seed/home03/400/300",
30
+ "isAvailable": true
31
+ },
32
+ {
33
+ "id": "h04",
34
+ "name": "Biển Xanh Villa",
35
+ "city": "Vũng Tàu",
36
+ "guests": 8,
37
+ "price": 2450000,
38
+ "rating": 8.1,
39
+ "image": "https://picsum.photos/seed/home04/400/300",
40
+ "isAvailable": true
41
+ },
42
+ {
43
+ "id": "h05",
44
+ "name": "Mây Núi Lodge",
45
+ "city": "Hà Giang",
46
+ "guests": 3,
47
+ "price": 590000,
48
+ "rating": 9.4,
49
+ "image": "https://picsum.photos/seed/home05/400/300",
50
+ "isAvailable": false
51
+ },
52
+ {
53
+ "id": "h06",
54
+ "name": "Sông Hương Retreat",
55
+ "city": "Huế",
56
+ "guests": 2,
57
+ "price": 720000,
58
+ "rating": 8.3,
59
+ "image": "https://picsum.photos/seed/home06/400/300",
60
+ "isAvailable": true
61
+ },
62
+ {
63
+ "id": "h07",
64
+ "name": "Tràng An Riverside",
65
+ "city": "Ninh Bình",
66
+ "guests": 4,
67
+ "price": 980000,
68
+ "rating": 9,
69
+ "image": "https://picsum.photos/seed/home07/400/300",
70
+ "isAvailable": true
71
+ },
72
+ {
73
+ "id": "h08",
74
+ "name": "Sunset Bungalow",
75
+ "city": "Phú Quốc",
76
+ "guests": 2,
77
+ "price": 1590000,
78
+ "rating": 8.8,
79
+ "image": "https://picsum.photos/seed/home08/400/300",
80
+ "isAvailable": true
81
+ },
82
+ {
83
+ "id": "h09",
84
+ "name": "Đồi Thông Cottage",
85
+ "city": "Đà Lạt",
86
+ "guests": 5,
87
+ "price": 1100000,
88
+ "rating": 7.8,
89
+ "image": "https://picsum.photos/seed/home09/400/300",
90
+ "isAvailable": true
91
+ },
92
+ {
93
+ "id": "h10",
94
+ "name": "Mộc Châu Tea House",
95
+ "city": "Mộc Châu",
96
+ "guests": 6,
97
+ "price": 1350000,
98
+ "rating": 8.5,
99
+ "image": "https://picsum.photos/seed/home10/400/300",
100
+ "isAvailable": false
101
+ },
102
+ {
103
+ "id": "h11",
104
+ "name": "Kỳ Co Beach Stay",
105
+ "city": "Quy Nhơn",
106
+ "guests": 4,
107
+ "price": 1050000,
108
+ "rating": 8.7,
109
+ "image": "https://picsum.photos/seed/home11/400/300",
110
+ "isAvailable": true
111
+ },
112
+ {
113
+ "id": "h12",
114
+ "name": "Miệt Vườn Homestay",
115
+ "city": "Cần Thơ",
116
+ "guests": 3,
117
+ "price": 450000,
118
+ "rating": 8,
119
+ "image": "https://picsum.photos/seed/home12/400/300",
120
+ "isAvailable": true
121
+ },
122
+ {
123
+ "id": "h13",
124
+ "name": "Lagoon View Studio",
125
+ "city": "Nha Trang",
126
+ "guests": 2,
127
+ "price": 790000,
128
+ "rating": 7.6,
129
+ "image": "https://picsum.photos/seed/home13/400/300",
130
+ "isAvailable": true
131
+ },
132
+ {
133
+ "id": "h14",
134
+ "name": "Ruộng Bậc Thang House",
135
+ "city": "Mù Cang Chải",
136
+ "guests": 5,
137
+ "price": 650000,
138
+ "rating": 9.1,
139
+ "image": "https://picsum.photos/seed/home14/400/300",
140
+ "isAvailable": true
141
+ },
142
+ {
143
+ "id": "h15",
144
+ "name": "Phong Nha Farmstay",
145
+ "city": "Quảng Bình",
146
+ "guests": 4,
147
+ "price": 890000,
148
+ "rating": 8.4,
149
+ "image": "https://picsum.photos/seed/home15/400/300",
150
+ "isAvailable": true
151
+ },
152
+ {
153
+ "id": "h16",
154
+ "name": "Mỹ Khê Loft",
155
+ "city": "Đà Nẵng",
156
+ "guests": 3,
157
+ "price": 1190000,
158
+ "rating": 8.2,
159
+ "image": "https://picsum.photos/seed/home16/400/300",
160
+ "isAvailable": false
161
+ },
162
+ {
163
+ "id": "h17",
164
+ "name": "Đảo Ngọc Hideaway",
165
+ "city": "Cát Bà",
166
+ "guests": 4,
167
+ "price": 1290000,
168
+ "rating": 8.6,
169
+ "image": "https://picsum.photos/seed/home17/400/300",
170
+ "isAvailable": true
171
+ },
172
+ {
173
+ "id": "h18",
174
+ "name": "Đồi Cát Studio",
175
+ "city": "Mũi Né",
176
+ "guests": 2,
177
+ "price": 560000,
178
+ "rating": 7.4,
179
+ "image": "https://picsum.photos/seed/home18/400/300",
180
+ "isAvailable": true
181
+ },
182
+ {
183
+ "id": "h19",
184
+ "name": "Tỏi Biển Homestay",
185
+ "city": "Lý Sơn",
186
+ "guests": 6,
187
+ "price": 750000,
188
+ "rating": 8.9,
189
+ "image": "https://picsum.photos/seed/home19/400/300",
190
+ "isAvailable": true
191
+ }
192
+ ]
package/src/format.ts ADDED
@@ -0,0 +1 @@
1
+ export const formatVND = (n: number) => n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.') + 'đ';
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './format';
@@ -0,0 +1,4 @@
1
+ import data from '../data/homestays.json';
2
+ import { Homestay } from '../types/homestay';
3
+ export const loadHomestays = (): Promise<Homestay[]> =>
4
+ new Promise(resolve => setTimeout(() => resolve(data as Homestay[]), 800));
@@ -0,0 +1,23 @@
1
+ import { configureStore, createSlice, PayloadAction } from '@reduxjs/toolkit';
2
+ import { Homestay } from './types/homestay';
3
+
4
+ const savedSlice = createSlice({
5
+ name: 'saved',
6
+ initialState: { items: [] as Homestay[] },
7
+ reducers: {
8
+ addHomestay: (state, a: PayloadAction<Homestay>) => {
9
+ if (a.payload.isAvailable && !state.items.some(h => h.id === a.payload.id)) state.items.push(a.payload);
10
+ },
11
+ removeHomestay: (state, a: PayloadAction<string>) => {
12
+ state.items = state.items.filter(h => h.id !== a.payload);
13
+ },
14
+ setHomestays: (state, a: PayloadAction<Homestay[]>) => { state.items = a.payload; },
15
+ clearHomestays: state => { state.items = []; },
16
+ },
17
+ });
18
+ export const { addHomestay, removeHomestay, setHomestays, clearHomestays } = savedSlice.actions;
19
+ export const store = configureStore({ reducer: { saved: savedSlice.reducer } });
20
+ export type RootState = ReturnType<typeof store.getState>;
21
+ export const selectSavedItems = (s: RootState) => s.saved.items;
22
+ export const selectSavedCount = (s: RootState) => s.saved.items.length;
23
+ export const selectSavedTotal = (s: RootState) => s.saved.items.reduce((t, h) => t + h.price, 0);
@@ -0,0 +1,4 @@
1
+ export type Homestay = {
2
+ id: string; name: string; city: string; guests: number;
3
+ price: number; rating: number; image: string; isAvailable: boolean;
4
+ };
@@ -0,0 +1 @@
1
+ export const formatVND = (n: number) => n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.') + 'đ';
package/tsconfig.json ADDED
@@ -0,0 +1,11 @@
1
+
2
+ {
3
+ "compilerOptions": {
4
+ "target": "ES2020",
5
+ "strict": true,
6
+ "declaration": true,
7
+ "skipLibCheck": true,
8
+ "esModuleInterop": true
9
+ },
10
+ "include": ["src"]
11
+ }