Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | 72x 18x 18x 18x 18x 18x 4x 4x 18x 18x 18x 12x 12x 12x 3x 3x 9x 18x 18x 18x 18x 18x 5x 5x 5x 1x 1x 1x 1x 18x 18x 18x 5x 5x 5x 18x 18x 16x 16x 16x 16x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 72x 2x 2x 2x 2x 18x 18x 18x 18x 72x 18x 18x 18x 18x 18x 3x 3x 3x 3x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x | import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { createBrowserRouter, RouterProvider, Navigate, } from "react-router-dom"; import './App.css'; import Navbar from './component/navBar/NavBar'; import { Login } from "./pages/login/Login" import { Register } from './pages/register/Register'; import Home from './pages/Home/Home'; import Header from './component/header/Header' import TaskArea from './component/taskArea/TaskArea' import ShopArea from "./component/shopArea/ShopArea"; import ChallengeArea from './component/challengeArea/ChallengeArea'; import Popup from './component/popup/Popup'; import {BASE_URL, STATUS_CODE, SERVER_API} from './utils/constants' // function to create default items for TaskArea const createDefaultItem = (content, options = {}) => ({ id: Date.now(), content, ...options, }); function App() { /* limitation to get access to home page before login (change to false to apply) */ const currentUser = true; /* Popup */ const [showPopup, setShowPopup] = useState(false); const [popupMessage, setPopupMessage] = useState({ title: '', body: '', background_color: ''}); const closePopup = () => { setShowPopup(false); }; const showCustomPopup = (title, body, background_color) => { setPopupMessage({ title, body, background_color }); setShowPopup(true); }; /* health bar Get initial health from local storage, default to 100 if not found -10 per update */ const initialHealth = parseInt(localStorage.getItem('health')) || 100; const [health, setHealth] = useState(initialHealth); const updateHealth = () => { setHealth(prevHealth => { const newHealth = prevHealth - 10; if (newHealth <= 0) { showCustomPopup("Health Depleted", "Your health has depleted to zero. Try upgrading to restore full health.", "rgba(243, 97, 105, 0.7)"); return 0; } return newHealth; }); }; /* level bar Get initial level from local storage, default to 0 if not found +1Q per update */ const initialLevel = parseInt(localStorage.getItem('level')) || 1; const [level, setLevel] = useState(initialLevel); const initialExperience = parseInt(localStorage.getItem('experience')) || 0; const [experience, setExperience] = useState(initialExperience); const updateLevel = () => { const newExperience = experience + 20; setExperience(newExperience); if (newExperience >= 100) { setLevel(prevLevel => prevLevel + Math.floor(newExperience / 100)); setExperience(0); setHealth(100); showCustomPopup("Level Up", "Congratulations! You've leveled up!", "rgba(255, 204, 85, 0.7)"); } }; /* coin +1Q per task decrease corresponding coins from purchasing items in shop */ const initialCoin = parseInt(localStorage.getItem('coin')) || 0; const [coin, setCoin] = useState(initialCoin); const updateCoin = () => { setCoin(prevCoin => { const newCoin = prevCoin + 10; return newCoin; }); }; const decreaseCoin = (price) => { setCoin(prevCoin => { // let coin >= 0 const newCoin = Math.max(0, prevCoin - price); localStorage.setItem('coin', newCoin); // update in localStorage return newCoin; }); showCustomPopup("Purchase Successfully", "You have purchased an item.", "rgba(8,186,255, 0.7)"); }; useEffect(() => { // Save health & level to local storage whenever it changes localStorage.setItem('health', health.toString()); localStorage.setItem('level', level.toString()); localStorage.setItem('experience', experience.toString()); localStorage.setItem('coin', coin.toString()); }, [health, level, experience, coin]); /* TaskArea: Habit, Daily, To-do, reward */ // initialize with default tasks and add a new habit, daily, to-do, reward to the task lists const defaultHabit = createDefaultItem('Your default habit', { positive: true, negative: true }); const defaultDaily = createDefaultItem('Your default daily', { completed: false }); const defaultTodo = createDefaultItem('Your default to-do', { completed: false }); const defaultReward = createDefaultItem('Your default reward', { price: 10}); const [habits, setHabits] = useState(() => JSON.parse(localStorage.getItem('habits')) || [defaultHabit]); const [dailies, setDailies] = useState(() => JSON.parse(localStorage.getItem('dailies')) || [defaultDaily]); const [todos, setTodos] = useState(() => JSON.parse(localStorage.getItem('todos')) || [defaultTodo]); const [rewards, setRewards] = useState(() => JSON.parse(localStorage.getItem('rewards')) || [defaultReward]); // TODO: 账号信息如何管理?全局变量?Context?props传 随用随取? // TODO: task数据从server获取后 增删改的回调函数逻辑是否可以挪回组件内部 let validToken; const login = async(username, password) => { try { const response = await axios.post(BASE_URL + SERVER_API.LOGIN, { // TODO: delete the stub username/psw when login is integrated with backend 'username': username ?? 'Yue', 'password': password ?? 'yue@memominder' }); console.debug('login success:', response.status); return response?.data?.token; } catch (error) { return Promise.reject(error) } }; let retryCount = 0; const addHabitToServer = async (habit) => { try { console.debug('addHabitToServer:', habit); if (!habit?.content || !habit?.notes) { console.warn('invalid habit, no need to post'); return; } if (!validToken) { validToken = await login(); } const response = await axios.post(BASE_URL + SERVER_API.ADD_HABIT, { 'title': habit.content, 'type': habit.positive && habit.negative ? 'both' : !habit.positive && !habit.negative ? 'neutral' : habit.positive ? 'positive' : 'negative', 'note': habit.notes }, { headers: { 'Authorization': validToken, 'Content-Type': 'application/json' } }); console.debug('post new habit success:', response.status); } catch (error) { if (error.response.status === STATUS_CODE.UNAUTHORIZED && retryCount < 1) { validToken = null; retryCount++; addHabitToServer(habit); } else { retryCount = 0; } console.warn('post new habit error:', error); } }; const addHabit = (habit) => { setHabits(prev => [...prev, habit]) addHabitToServer(habit); }; const addDaily = (daily) => {setDailies(prev => [...prev, daily])}; const addTodo = (todo) => {setTodos(prev => [...prev, todo]);}; const addReward = (reward) => {setRewards(prev => [...prev, reward]);}; //update an existing habit, daily, to-do, reward const createUpdater = (setter) => (updatedItem) => { setter((prevItems) => { return prevItems.map((item) => { Eif (item.id === updatedItem.id) { return updatedItem; } return item; }); }); }; const updateHabit = createUpdater(setHabits); const updateDaily = createUpdater(setDailies); const updateTodo = createUpdater(setTodos); const updateReward = createUpdater(setRewards); // delete an existing habit, daily, to-do, reward const createDeleter = (setter) => (itemId) => { setter((prevItems) => prevItems.filter((item) => item.id !== itemId)); }; const deleteHabit = createDeleter(setHabits); const deleteDaily = createDeleter(setDailies); const deleteTodo = createDeleter(setTodos); const deleteReward = createDeleter(setRewards); useEffect(() => { // save habits, dailies, todos, rewards to local storage whenever it changes localStorage.setItem('habits', JSON.stringify(habits)); localStorage.setItem('dailies', JSON.stringify(dailies)); localStorage.setItem('todos', JSON.stringify(todos)); localStorage.setItem('rewards', JSON.stringify(rewards)); }, [habits, dailies, todos, rewards]); const clearStorageAndResetStates = () => { // clear all localStorage localStorage.clear(); // update to default state setHabits([defaultHabit]); setDailies([defaultDaily]); setTodos([defaultTodo]); setRewards([defaultReward]); setHealth(100); setExperience(0); setCoin(0); setLevel(1); }; /*-Transfer for different Areas start-*/ const [showTaskArea, setShowTaskArea] = useState(true); const [showShop, setShowShop] = useState(false); const [showChallenge, setShowChallenge] = useState(false); const handleTaskClick = () => { setShowTaskArea(true); setShowShop(false); }; const handleShopClick = () => { setShowTaskArea(false); setShowShop(true); }; const handleChallengeClick = () => { setShowTaskArea(false); setShowShop(false); setShowChallenge(true); }; /*-Transfer for different Areas end-*/ const Layout = ({ showTaskArea, showShop, showChallenge, handleTaskClick, handleShopClick, handleChallengeClick }) => { return ( <div> {/* Pass handleTaskClick and handleShopClick as props to Navbar component */} <Navbar handleTaskClick={handleTaskClick} handleShopClick={handleShopClick} handleChallengeClick={handleChallengeClick} coin={coin} /> <div style={{ display: "flex", flexDirection: "column" }}> {/* pass health props to Header and TaskArea */} <Header health={health} experience={experience} level={level}/> <Popup show={showPopup} onClose={closePopup} message={popupMessage} /> {/* TaskArea and ShopArea outside Navbar */} <div> {showTaskArea ? ( <TaskArea updateHealth={updateHealth} updateLevel={updateLevel} coin={coin} updateCoin={updateCoin} decreaseCoin={decreaseCoin} habits={habits} dailies={dailies} todos={todos} rewards = {rewards} onAddHabit={addHabit} onUpdateHabit={updateHabit} onDeleteHabit={deleteHabit} onAddDaily={addDaily} onUpdateDaily={updateDaily} onDeleteDaily={deleteDaily} onAddTodo={addTodo} onUpdateTodo={updateTodo} onDeleteTodo={deleteTodo} onAddReward = {addReward} onUpdateReward = {updateReward} onDeleteReward = {deleteReward} onClear={clearStorageAndResetStates} /> ) : showShop ? ( <ShopArea coin={coin} updateCoin={updateCoin} decreaseCoin={decreaseCoin}/> ) : ( <ChallengeArea /> )} </div> </div> </div> ); }; /* -- prevent to access home page before login start -- */ /* -- 要用的时候把上面那个currentUser改成false就ok -- */ const ProtectedRoute = ({children}) =>{ Iif(!currentUser){ return <Navigate to="/login"/> } return children } /* -- prevent to access home page before login end -- */ /* -- page transfer start -- */ const router = createBrowserRouter([ { path: "/", element: <ProtectedRoute> <Layout showTaskArea={showTaskArea} showShop={showShop} showChallenge={showChallenge} handleTaskClick={handleTaskClick} handleShopClick={handleShopClick} handleChallengeClick={handleChallengeClick} /> </ProtectedRoute>, children:[ { path: "/", element: <Home/> }, { path: "/profile/:id", element: <Home/> } ] }, { path: "/login", element: <Login/> }, { path: "/register", element: <Register/> }, ]); /* -- page transfer end -- */ return ( <div> <RouterProvider router={router} /> <Popup show={showPopup} onClose={closePopup} message={popupMessage} /> </div> ); } export default App; |