App.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. import React, {useState, useEffect, useRef} from 'react'
  2. import logoDefault from './logo.svg';
  3. import './App.scss';
  4. import {Provider, connect} from 'react-redux';
  5. import {createStore, combineReducers, applyMiddleware} from 'redux';
  6. import thunk from 'redux-thunk';
  7. const jwtDecode = token => {
  8. try {
  9. let arrToken = token.split('.')
  10. let base64Token = atob(arrToken[1])
  11. return JSON.parse(base64Token)
  12. }
  13. catch (e) {
  14. console.log('Лажа, Бро ' + e);
  15. }
  16. }
  17. function authReducer(state, { type, token }) {
  18. if (!state) {
  19. if (localStorage.authToken) {
  20. type = 'AUTH_LOGIN'
  21. token = localStorage.authToken
  22. } else state = {}
  23. }
  24. if (type === 'AUTH_LOGIN') {
  25. localStorage.setItem('authToken', token)
  26. let payload = jwtDecode(token)
  27. if (typeof payload === 'object') {
  28. return {
  29. ...state,
  30. token,
  31. payload
  32. }
  33. } else return {}
  34. }
  35. if (type === 'AUTH_LOGOUT') {
  36. localStorage.removeItem('authToken')
  37. return {}
  38. }
  39. return state
  40. }
  41. const actionAuthLogin = token => ({ type: 'AUTH_LOGIN', token })
  42. const actionAuthLogout = () => ({ type: 'AUTH_LOGOUT' })
  43. function cartReducer(state = {}, { type, good = {}, count = 1 }) {
  44. const { _id } = good
  45. const types = {
  46. CART_ADD() {
  47. count = +count
  48. if (!count) return state
  49. return {
  50. ...state,
  51. [_id]: {
  52. good,
  53. count: count + (state[_id]?.count || 0)
  54. }
  55. }
  56. },
  57. CART_CHANGE() {
  58. count = +count
  59. if (!count) return state
  60. return {
  61. ...state,
  62. [_id]: {
  63. good,
  64. count: count
  65. }
  66. }
  67. },
  68. CART_REMOVE() {
  69. let { [_id]: remove, ...newState } = state
  70. return {
  71. ...newState
  72. }
  73. },
  74. CART_CLEAR() {
  75. return {}
  76. },
  77. }
  78. if (type in types) {
  79. return types[type]()
  80. }
  81. return state
  82. }
  83. const actionCartAdd = (good, count=1) => ({type: "CART_ADD", good, count});
  84. function promiseReducer(state = {}, { type, status, payload, error, name }) {
  85. if (type === 'PROMISE') {
  86. return {
  87. ...state,
  88. [name]: { status, payload, error }
  89. }
  90. }
  91. return state;
  92. }
  93. const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name })
  94. const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload })
  95. const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error })
  96. const actionPromise = (name, promise) =>
  97. async dispatch => {
  98. dispatch(actionPending(name))
  99. try {
  100. let data = await promise
  101. dispatch(actionResolved(name, data))
  102. return data
  103. }
  104. catch (error) {
  105. dispatch(actionRejected(name, error))
  106. }
  107. }
  108. const getGQL = url =>
  109. async (query, variables = {}) => {
  110. let obj = await fetch(url, {
  111. method: 'POST',
  112. headers: {
  113. "Content-Type": "application/json",
  114. Authorization: localStorage.authToken ? 'Bearer ' + localStorage.authToken : {},
  115. },
  116. body: JSON.stringify({ query, variables })
  117. })
  118. let a = await obj.json()
  119. if (!a.data && a.errors)
  120. throw new Error(JSON.stringify(a.errors))
  121. return a.data[Object.keys(a.data)[0]]
  122. }
  123. const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
  124. const gql = getGQL(backURL + '/graphql');
  125. const actionLogin = (login, password) => (
  126. actionPromise('login', gql(`query log($login: String, $password: String) {
  127. login(login: $login, password: $password)
  128. }`, {login, password}))
  129. )
  130. const actionFullLogin = (login, password) => (
  131. async (dispatch) => {
  132. let token = await dispatch(actionLogin(login, password))
  133. if (token) {
  134. dispatch(actionAuthLogin(token))
  135. }
  136. }
  137. )
  138. const actionRootCats = () =>
  139. actionPromise('rootCats', gql(`query {
  140. CategoryFind(query: "[{\\"parent\\":null}]"){
  141. _id name
  142. }
  143. }`))
  144. const actionCatById = (_id) =>
  145. actionPromise('catById', gql(`query catById($q: String){
  146. CategoryFindOne(query: $q){
  147. subCategories{name, _id}
  148. _id name goods {
  149. _id name price images {
  150. url
  151. }
  152. }
  153. }
  154. }`, { q: JSON.stringify([{ _id }]) }))
  155. const store = createStore(combineReducers({promise: promiseReducer,
  156. auth: authReducer,
  157. cart: cartReducer}),
  158. applyMiddleware(thunk))
  159. store.subscribe(() => console.log(store.getState()))
  160. store.dispatch(actionRootCats())
  161. store.dispatch(actionCatById('5dc49f4d5df9d670df48cc64'))
  162. const Logo = ({logo=logoDefault}) =>
  163. <a href='#' className="Logo">
  164. <img src={logo} />
  165. </a>
  166. const Koshik = ({cart}) => {
  167. let count = 0;
  168. let sum = Object.entries(cart).map(([, val]) => val.count)
  169. count = sum.reduce((a, b) => a + b, 0)
  170. //перебрать cart, посчитать суммарный count
  171. return (
  172. <div className='Koshik'>{count}</div>
  173. )
  174. }
  175. const CKoshik = connect(({cart}) => ({cart}))(Koshik)
  176. const Header = ({logo=logoDefault}) =>
  177. <header>
  178. <Logo logo={logo} />
  179. <CKoshik />
  180. </header>
  181. const Footer = ({logo=logoDefault}) =>
  182. <footer>
  183. <Logo logo={logo} />
  184. </footer>
  185. const defaultRootCats = [
  186. {
  187. "_id": "5dc49f4d5df9d670df48cc64",
  188. "name": "Airconditions"
  189. },
  190. {
  191. "_id": "5dc458985df9d670df48cc47",
  192. "name": " Smartphones"
  193. },
  194. {
  195. "_id": "5dc4b2553f23b553bf354101",
  196. "name": "Крупная бытовая техника"
  197. },
  198. {
  199. "_id": "5dcac1b56d09c45440d14cf8",
  200. "name": "Макароны"
  201. }]
  202. const RootCategory = ({cat:{_id, name}={}}) =>
  203. <li>
  204. <a href={`#/${_id}`}>{name}</a>
  205. </li>
  206. const RootCategories = ({cats=defaultRootCats}) =>
  207. <ul className='RootCategories'>
  208. {cats.map(cat => <RootCategory cat={cat} />)}
  209. </ul>
  210. const CRootCategories = connect(state => ({cats: state.promise.rootCats?.payload || []}))
  211. (RootCategories)
  212. const Aside = () =>
  213. <aside>
  214. <CRootCategories />
  215. </aside>
  216. const Content = ({children}) =>
  217. <div className='Content'>
  218. {children}
  219. </div>
  220. const defaultCat ={
  221. "subCategories": null,
  222. "_id": "5dc458985df9d670df48cc47",
  223. "name": " Smartphones",
  224. "goods": [
  225. {
  226. "_id": "61b105f9c750c12ba6ba4524",
  227. "name": "iPhone ",
  228. "price": 1200,
  229. "images": [
  230. {
  231. "url": "images/50842a3af34bfa28be037aa644910d07"
  232. }
  233. ]
  234. },
  235. {
  236. "_id": "61b1069ac750c12ba6ba4526",
  237. "name": "iPhone ",
  238. "price": 1000,
  239. "images": [
  240. {
  241. "url": "images/d12b07d983dac81ccad404582a54d8be"
  242. }
  243. ]
  244. },
  245. {
  246. "_id": "61b23f94c750c12ba6ba472a",
  247. "name": "name1",
  248. "price": 1214,
  249. "images": [
  250. {
  251. "url": null
  252. }
  253. ]
  254. },
  255. {
  256. "_id": "61b23fbac750c12ba6ba472c",
  257. "name": "smart",
  258. "price": 1222,
  259. "images": [
  260. {
  261. "url": "images/871f4e6edbf86c35f70b72dcdebcd8b2"
  262. }
  263. ]
  264. }
  265. ]
  266. }
  267. const SubCategories = ({cats}) =>
  268. <></>
  269. const GoodCard = ({good:{_id, name, price, images}={}, onCartAdd}) =>
  270. <div className='GoodCard'>
  271. <h2>{name}</h2>
  272. {images && images[0] && images[0].url && <img src={backURL + '/' + images[0].url} />}
  273. <strong>{price}</strong>
  274. <button onClick={() => onCartAdd({_id, name, price, images})}>+</button>
  275. </div>
  276. const CGoodCard = connect(null, {onCartAdd: actionCartAdd})(GoodCard)
  277. const Category = ({cat:{_id, name, goods, subCategories}=defaultCat}) =>
  278. <div className='Category'>
  279. <h1>{name}</h1>
  280. {subCategories && <SubCategories cats={subCategories} />}
  281. {(goods || []).map(good => <CGoodCard good={good}/>)}
  282. </div>
  283. const CCategory = connect(state => ({cat: state.promise.catById?.payload}))(Category)
  284. const Main = () =>
  285. <main>
  286. <Aside />
  287. <Content>
  288. <CCategory />
  289. </Content>
  290. </main>
  291. const JSONTest = ({data}) =>
  292. <pre>
  293. {JSON.stringify(data, null, 4)}
  294. {Math.random() > 0.5 && <h1>asdfasf</h1> }
  295. </pre>
  296. const ReduxJSON = connect(state => ({data:state}))(JSONTest)
  297. const ListItem = ({item}) =>
  298. <li>{item}</li>
  299. const List = ({data=["пиво", "чипсы", "сиги"]}) =>
  300. <ul>
  301. {data.map(item => <ListItem item={item} />)}
  302. </ul>
  303. const _ = React.createElement.bind(React)
  304. const List2 = ({data=["пиво", "чипсы", "сиги"]}) =>
  305. _('ul',null,
  306. data.map(item => _(ListItem,{ item }))
  307. )
  308. const LowerCase = ({children}) => (
  309. <>
  310. {children.toLowerCase()}
  311. </>
  312. )
  313. const Input = () => {
  314. const [text, setText] = useState("text")
  315. // text !== 'ДРУГОЙ ТЕКСТ' && setTimeout(() => setText('ДРУГОЙ ТЕКСТ'), 2000)
  316. return (
  317. <>
  318. <h1>{text}</h1>
  319. <h1>{text.length}</h1>
  320. <h1><LowerCase>{text}</LowerCase></h1>
  321. <input value={text} onChange={(e) => setText(e.target.value)}/>
  322. </>
  323. )
  324. }
  325. const Spoiler = ({children}) => {
  326. const [open, setOpen] = useState(false)
  327. return (
  328. <div>
  329. <h3 onClick = {e => setOpen(!open)}>{open ? 'hide' : 'show'}</h3>
  330. {open && children}
  331. </div>
  332. )
  333. }
  334. const RGBInput = () => {
  335. const [red, setRed] = useState(0)
  336. const [green, setGreen] = useState(0)
  337. const [blue, setBlue] = useState(0)
  338. const color = `rgba(${red},${green},${blue},1)`
  339. useEffect(() => {
  340. console.log('component did mount')
  341. return () => {
  342. console.log('component will unmount')
  343. }
  344. }, [])
  345. const bounds = x => x < 0 ? 0 : (x > 255 ? 255 : x)
  346. return (
  347. <div style={{backgroundColor: color}}>
  348. <input type="number" min="0" max="255"
  349. value={red} onChange={(e) => setRed(bounds(+e.target.value))}/>
  350. <input type="number" min="0" max="255"
  351. value={green} onChange={(e) => setGreen(bounds(+e.target.value))}/>
  352. <input type="number" min="0" max="255"
  353. value={blue} onChange={(e) => setBlue(bounds(+e.target.value))}/>
  354. </div>
  355. )
  356. }
  357. const Timer = ({ms=1000, onDelete}) => {
  358. const [counter, setCounter] = useState(0)
  359. const ref = useRef(0)
  360. useEffect(() => {
  361. console.log('+eff')
  362. const interval = setInterval(() => {
  363. setCounter((counter) => counter + 1)
  364. }, ms)
  365. return () => {
  366. console.log('-eff')
  367. clearInterval(interval)
  368. }
  369. }, [ms])
  370. /* console.log(ref.current++) */
  371. return (
  372. <>
  373. <div>{counter}</div>
  374. <button onClick={onDelete}>-</button>
  375. </>
  376. )
  377. }
  378. const Timers = () => {
  379. // const [timer, setTimer] = useState(0)
  380. // const arr = []
  381. // for (let i=0; i<timer; i++) {
  382. // arr.push(i)
  383. // }
  384. const [timers, setTimers] = useState([])
  385. const [ms, setMS] = useState(1000)
  386. return (
  387. <>
  388. <button onClick={() => setMS(ms + 100)}>+100</button>
  389. {ms}
  390. <button onClick={() => setMS(ms - 100)}>-100</button>
  391. <button onClick={() => setTimers([...timers, Math.random()])}>+</button>
  392. {timers.map((i) => <Timer key={i} ms={ms}
  393. onDelete={() => setTimers(timers.filter(t => t !== i))}/>)}
  394. </>
  395. )
  396. }
  397. const LoginForm = ({onLogin}) => {
  398. const [login, setLogin] = useState("")
  399. const [pass, setPass] = useState("")
  400. return (
  401. <div className='LoginForm'>
  402. <input style={ {backgroundColor: (login.length === 0) ? 'red' : '#fff'} }
  403. value={login} onChange={(e) => setLogin(e.target.value)}/>
  404. <input style={ {backgroundColor: (pass.length === 0) ? 'red' : '#fff'} }
  405. value={pass} onChange={(e) => setPass(e.target.value)}/>
  406. <button onClick={() => onLogin(login,pass)}
  407. disabled={(login.length !== 0 && pass.length !== 0) ? false : true}>Login</button>
  408. </div>
  409. )
  410. }
  411. const CLoginForm = connect(null, {onLogin: actionFullLogin})(LoginForm)
  412. function App() {
  413. const worstka = <h1>{Math.random()}</h1>
  414. const worstkaNative = React.createElement("h1", null, Math.random())
  415. const worstkaNative2 = React.createElement("h1", {children: [Math.random()]})
  416. console.log(worstkaNative2)
  417. const listQQQ = React.createElement(List2, {data:["aaaa", "uuuuuuu", "сиги"]})
  418. return (
  419. <Provider store={store}>
  420. <div className="App">
  421. {/* <LoginForm onLogin={(l,p) => console.log(l,p)}/>
  422. <CLoginForm/>
  423. <Input />
  424. {worstka}
  425. {worstkaNative}
  426. {worstkaNative2}
  427. {listQQQ} */}
  428. <Timers/>
  429. {/* <Spoiler>
  430. <Timer/>
  431. </Spoiler> */}
  432. <Spoiler>
  433. <RGBInput/>
  434. </Spoiler>
  435. <Header />
  436. <Main />
  437. <Footer />
  438. </div>
  439. </Provider>
  440. );
  441. }
  442. export default App;