ivar_n преди 2 години
родител
ревизия
0fbfd38052
променени са 4 файла, в които са добавени 641 реда и са изтрити 37 реда
  1. 0 13
      js/18/index.html
  2. 0 24
      js/18/index.js
  3. 58 0
      js/18_redux-thunk-3/index.html
  4. 583 0
      js/18_redux-thunk-3/index.js

+ 0 - 13
js/18/index.html

@@ -1,13 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-   <meta charset="UTF-8">
-   <meta http-equiv="X-UA-Compatible" content="IE=edge">
-   <meta name="viewport" content="width=device-width, initial-scale=1.0">
-   <title>Document</title>
-</head>
-<body>
-   
-   <script src="./index.js"></script>
-</body>
-</html>

+ 0 - 24
js/18/index.js

@@ -1,24 +0,0 @@
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}

+ 58 - 0
js/18_redux-thunk-3/index.html

@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+   <meta charset="UTF-8">
+   <meta http-equiv="X-UA-Compatible" content="IE=edge">
+   <meta name="viewport" content="width=device-width, initial-scale=1.0">
+   <title>Document</title>
+   <style>
+      #mainContainer {
+          display: flex;
+      }
+      #aside {
+          width: 30%;
+      }
+      #aside > a {
+          display: block;
+      }
+      #main > a {
+          display: block;
+      }
+      #loginContainer  {
+         display: flex;
+         flex-direction: column;
+      }
+  </style>
+</head>
+   <body>
+      <header>
+          <div id="cartIcon"></div>
+      </header>
+      <div id="topContaner"></div>
+      <div id='mainContainer'>
+          <aside id='aside'>
+              Категории
+          </aside>          
+          <main id='main'>
+              Контент
+          </main>
+      </div>
+
+        <!-- <div id="regContainer"> 
+            <input id="loginReg" type="text"/>
+            <input id="passReg" type="password"/>
+            <button id="regBtn">REGISTER</button>
+        </div>
+
+        <div id="loginContainer">
+            <input id="loginInput" type="text"/>
+            <input id="passInput" type="password"/>
+            <button id="loginBtn">LOGIN</button>
+            <button id="logoutBtn">LOGOUT</button>
+        </div>
+        -->
+
+      <script src='index.js'></script>
+  </body>
+
+</html>

+ 583 - 0
js/18_redux-thunk-3/index.js

@@ -0,0 +1,583 @@
+
+function createStore(reducer){
+    let state       = reducer(undefined, {}) //стартовая инициализация состояния, запуск редьюсера со state === undefined
+    let cbs         = []                     //массив подписчиков
+    
+    const getState  = () => state            //функция, возвращающая переменную из замыкания
+    const subscribe = cb => (cbs.push(cb),   //запоминаем подписчиков в массиве
+                             () => cbs = cbs.filter(c => c !== cb)) //возвращаем функцию unsubscribe, которая удаляет подписчика из списка
+                             
+    const dispatch  = action => { 
+        if (typeof action === 'function'){ //если action - не объект, а функция
+            return action(dispatch, getState) //запускаем эту функцию и даем ей dispatch и getState для работы
+        }
+        const newState = reducer(state, action) //пробуем запустить редьюсер
+        if (newState !== state){ //проверяем, смог ли редьюсер обработать action
+            state = newState //если смог, то обновляем state 
+            for (let cb of cbs)  cb() //и запускаем подписчиков
+        }
+    }
+    
+    return {
+        getState, //добавление функции getState в результирующий объект
+        dispatch,
+        subscribe //добавление subscribe в объект
+    }
+}
+
+function combineReducers(reducers) {
+    return (state={}, action) => {
+        const newState = {}
+        // перебрать все редьюсеры
+        if (reducers) {
+            for (const [reducerName, reducer] of Object.entries(reducers)) {
+                const newSubState = reducer(state[reducerName], action)
+                if (newSubState !== state[reducerName]) {
+                    newState[reducerName] = newSubState
+                }
+            }
+            // если newState не пустой, то вернуть стейт в 
+            if (Object.keys(newState).length !== 0) {
+                return {...state, ...newState}
+            } else {
+                return state
+            }
+        }
+
+    }
+}
+const combinedReducer = combineReducers({promise: promiseReducer, auth: authReducer, cart: cartReducer})
+const store = createStore(combinedReducer)
+// console.log(store.getState()) // {promise: {}, auth: {}}
+store.subscribe(() => console.log(store.getState()))
+
+
+
+function jwtDecode(token) {
+    try {
+        let decoded = JSON.parse(atob(token.split('.')[1])) 
+        return decoded
+    } catch (err) {
+        console.log(err)
+    }
+}
+
+function authReducer(state, {type, token}) {
+    if (!state) {
+        if (localStorage.authToken) {
+            token = localStorage.authToken
+            type = 'AUTH_LOGIN'
+        } else {
+            return {}
+        }
+    }
+    if (type === 'AUTH_LOGIN') {
+        let payload = jwtDecode(token)
+        if (typeof payload === 'object') {
+            localStorage.authToken = token
+            return {
+                ...state,
+                token, 
+                payload
+            }
+        } else {
+            return state
+        }
+    }
+    if (type === 'AUTH_LOGOUT') {
+        delete localStorage.authToken
+        return {}
+    }
+    return state
+}
+
+const actionAuthLogin = (token) => ({type: 'AUTH_LOGIN', token})
+const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'})
+
+// const loginStore = createStore(authReducer)
+
+
+// const inputToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJsb2dpbiI6ImVxd2VxZXdldyIsImFjbCI6WyI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJ1c2VyIl19LCJpYXQiOjE2MzgxOTQ1NzZ9.Pi1GO6x7wdNrIrUKCQT-32-SsqmgFY-oFDrrXmw74-8'
+
+// loginStore.dispatch(actionAuthLogin(inputToken))
+// loginStore.dispatch(actionAuthLogout())
+// console.log(store.getState())
+
+function cartReducer (state={}, {type, good={}, count=1}) {
+    if (!state) {
+        return {}
+    }
+
+    // только если в функции задан count по умолчанию
+    count = +count
+    if (!count) {
+        return state
+    }
+
+    const {_id} = good
+
+    const types = {
+        CART_ADD() {
+            return {
+                ...state,
+                [_id]: {good, count: count + (state[_id]?.count || 0)}
+            }
+        },
+        CART_CHANGE() {
+            return {
+                ...state,
+                [_id]: {good, count}
+            }
+        },
+        CART_REMOVE() {           
+            let { [_id]: removed, ...newState }  = state
+            return newState
+        },
+        CART_CLEAR() {
+            return {}
+        },
+    }
+    if (type in types) {         
+        return types[type]()
+    }
+    return state
+}
+
+const actionCartAdd = (good) => ({type: 'CART_ADD', good})
+const actionCartChange = (good, count) => ({type: 'CART_CHANGE', good, count})
+const actionCartRemove = (good) => ({type: 'CART_REMOVE', good})
+const actionCartClear = () => ({type: 'CART_CLEAR'})
+
+
+store.dispatch(actionCartAdd({_id: '111111'}))
+store.dispatch(actionCartChange({_id: '111111'}, 10))
+
+store.dispatch(actionCartAdd({_id: '22222'}))
+store.dispatch(actionCartRemove({_id: '22222'}))
+
+store.dispatch(actionCartClear())
+
+
+
+
+function promiseReducer(state={}, {type, status, payload, error, name}) {
+    if (!state) {
+        return {}
+    }
+    if (type === 'PROMISE') {         
+        return {
+            ...state,
+            [name]: {
+                status: status,
+                payload : payload,
+                error: error,
+            }
+        }
+    }
+    return state
+}
+
+const actionPending = (name) => ({type: 'PROMISE', status: 'PENDING', name})
+const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload})
+const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error})
+
+// const promiceStore = createStore(promiseReducer)
+// store.subscribe(() => console.log(store.getState()))
+
+
+// const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms))
+
+// // store.dispatch(actionPending('delay1000'))
+// // delay(1000).then(data => store.dispatch(actionResolved('delay1000', data)),
+// //                  error => store.dispatch(actionRejected('delay1000', error)))
+
+// // store.dispatch(actionPending('delay2000'))
+// // delay(2000).then(data => store.dispatch(actionResolved('delay2000', data)),
+// //                  error => store.dispatch(actionRejected('delay2000', error)))
+
+
+
+const actionPromise = (name, promise) => 
+    async (dispatch) => {
+        dispatch(actionPending(name))
+        try { 
+            let data = await promise
+            dispatch(actionResolved(name, data))
+            return data
+        }
+        catch(error){
+            dispatch(actionRejected(name, error))
+        }
+    }
+
+const getGQL = url =>
+  async (query, variables={}) => {
+    // try {
+      let obj = await fetch(url, {
+        method: 'POST',
+        headers: {
+          "Content-Type": "application/json",
+          ...(localStorage.authToken ? {Authorization: "Bearer " + localStorage.authToken} : {})
+        },
+        body: JSON.stringify({ query, variables })
+      })
+      let a = await obj.json()
+      if (!a.data && a.errors) {
+          throw new Error(JSON.stringify(a.errors))
+      } else {
+          return a.data[Object.keys(a.data)[0]]
+      }      
+    // }
+    // catch (error) {
+    //   console.log('Что-то не так, Бро ' + error);
+    // }
+  }
+
+  const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua/'
+  const gql = getGQL(backURL + 'graphql');
+
+
+
+  const actionOrder = () => (
+  async (dispatch, getState) => {
+      let {cart} = getState()
+      //магия по созданию структуры вида
+      //let orderGoods = [{good: {_id}, count}, {good: {_id}, count} .......]
+      //из структуры вида
+          //{_id1: {good, count},
+          //_id2: {good, count}}
+      const orderGoods = Object.entries(cart)
+                          .map(([_id, {}]) => ({good: {_id}, count}))
+
+      await dispatch(actionPromise('order', gql(`
+                  mutation newOrder($order:OrderInput){
+                    OrderUpsert(order:$order)
+                      { _id total 	}
+                  }
+          `, {order: {orderGoods}})))
+    })
+
+
+  
+
+
+const actionLogin = (login, password) => (
+    actionPromise('login', gql(`query log($login: String, $password: String) {
+        login(login: $login, password: $password)
+    }`, {login, password}))
+)
+
+const actionFullLogin = (login, password) => (
+    async (dispatch) => {
+        let token = await dispatch(actionLogin(login, password))
+        if (token) {
+            // console.log(token)
+            dispatch(actionAuthLogin(token))
+        }
+    }
+)
+
+
+const actionRegister = (login, password) => (
+    actionPromise('register', gql(`mutation reg($user:UserInput) {
+        UserUpsert(user:$user) {
+        _id 
+        }
+    }
+    `, {user: {login, password}})      
+    )
+)
+
+const actionFullRegister = (login, password) => (
+    async (dispatch) => {
+        let regId = await dispatch(actionRegister(login, password))
+        if (regId) {
+            // console.log(regId)
+            dispatch(actionFullLogin(login, password))
+        }
+    }
+)
+
+
+// regBtn.onclick = () => {
+//     store.dispatch(actionFullRegister(loginReg.value, passReg.value))
+// }
+
+
+// loginBtn.onclick = () => {
+//     store.dispatch(actionFullLogin(loginInput.value, passInput.value))
+// }
+
+// logoutBtn.onclick = () => {
+//     store.dispatch(actionAuthLogout())
+// }
+
+
+
+
+const actionRootCats = () => 
+    actionPromise('rootCats', gql(`query {
+        CategoryFind(query: "[{\\"parent\\":null}]"){
+            _id name
+        }
+    }`))
+
+const actionCatById = (_id) =>  //добавить подкатегории
+    actionPromise('catById', gql(`query catById($q: String){
+        CategoryFindOne(query: $q){
+            _id name goods {
+                _id name price images {
+                    url
+                }
+            }
+            subCategories {
+                _id name 
+            }
+        }
+    }`, {q: JSON.stringify([{_id}])}))
+
+
+const actionGoodById = (_id) => 
+    actionPromise('goodById', gql(`query goodById($q: String) {
+        GoodFindOne(query: $q) {
+            _id name price description images {
+            url
+            }
+        }
+    }`, {q: JSON.stringify([{_id}])}))
+
+
+const actionGoodsByUser = () => 
+actionPromise('goodByUser', gql(`query oUser($query: String) {
+    OrderFind(query:$query){
+       _id orderGoods{
+            price count total good{
+                _id name categories{
+                name
+                }
+                images {
+                    url
+                }
+            }
+        } 
+        owner {
+           _id login
+          }
+    }
+  }`, 
+   {query: JSON.stringify([{}])}))
+
+
+  
+store.dispatch(actionRootCats())
+
+store.subscribe(() => {
+    const {promise} = store.getState()
+    const {rootCats} = promise
+    if (rootCats?.payload) {
+
+
+        aside.innerHTML = ''
+        const regBtn = document.createElement('a')
+        regBtn.href = `#/register`
+        regBtn.innerText = 'Register'
+        const loginBtn = document.createElement('a')
+        loginBtn.href = `#/login`
+        loginBtn.innerText = 'Login'
+        const logoutBtn = document.createElement('button')
+        logoutBtn.innerText = 'Logout'
+        aside.append(regBtn, loginBtn, logoutBtn)
+
+
+
+        logoutBtn.onclick = () => {
+            store.dispatch(actionAuthLogout())
+        }
+        for (const {_id, name} of rootCats?.payload) {
+            const link = document.createElement('a')
+            link.href = `#/category/${_id}`
+            link.innerText = name
+            aside.append(link)
+        }
+    }
+})
+
+
+// location.hash - адресная строка после решетки
+window.onhashchange = () => {
+    const [,route, _id] = location.hash.split('/')
+
+    const routes = {
+        category(){
+            store.dispatch(actionCatById(_id))
+            console.log('страница категорий')           
+        },
+        good(){ //задиспатчить actionGoodById
+            store.dispatch(actionGoodById(_id))
+            console.log('страница товара')                
+        },
+        register(){
+            createForm(main, 'Register')
+            btnRegister.onclick = () => {
+                store.dispatch(actionFullRegister(loginRegister.value, passRegister.value))
+            }
+        },
+        login(){
+            createForm(main, 'Login')
+            btnLogin.onclick = () => {
+                store.dispatch(actionFullLogin(loginLogin.value, passLogin.value))
+            }
+        },
+        orders(){
+            store.dispatch(actionGoodsByUser())
+        },
+        cart(){ //задиспатчить actionGoodById
+            console.log('СДЕЛАТЬ СТРАНИЦУ С ПОЗИЦИЯМИ, полями ввода количества, картинками')
+            console.log('и кнопкой, которая store.dispatch(actionOrder())')
+        },     
+    }
+    if (route in routes) {
+        routes[route]()
+    }
+}
+
+function createForm(parent, type) {
+    parent.innerHTML = ` 
+    <input id="login${type}" type="text"/>
+    <input id="pass${type}" type="password"/>
+    <button id="btn${type}">${type}</button>
+    `
+}
+
+window.onhashchange()
+
+store.subscribe(() => {
+    const {promise} = store.getState()
+    const {catById} = promise
+    const [,route, _id] = location.hash.split('/')
+    if (catById?.payload && route === 'category'){
+        const {name} = catById.payload;
+        main.innerHTML =    `<h1>${name}</h1>`
+      
+        if (catById.payload.subCategories) {
+            for(const {_id, name} of catById.payload.subCategories) {
+                const link      = document.createElement('a');
+                link.href       = `#/category/${_id}`;
+                link.innerText  = name;
+                main.append(link);
+            }
+        }
+        
+        if (catById.payload.goods) {
+            for (const good of catById.payload.goods){
+                const {_id, name, price, images} = good
+                const card      = document.createElement('div')
+                card.innerHTML = `<h2>${name}</h2>
+                                  <img src="${backURL}/${images[0].url}" />
+                                  <strong>${price}</strong>
+                                  <br>
+                                  <a href="#/good/${_id}">Перейти на страницу товара</a>
+                                `
+                const btnCart      = document.createElement('button')
+                btnCart.innerText  = 'Добавить товар'
+                btnCart.onclick = () => {
+                    store.dispatch(actionCartAdd(good))
+                }
+                card.append(btnCart)
+                main.append(card)
+            }
+        }
+    }
+})
+
+store.subscribe(() => {
+    const {promise} = store.getState()
+    const {goodById} = promise
+    const [,route, _id] = location.hash.split('/');
+    if (goodById?.payload && route === 'good') {
+        main.innerHTML = '';
+        const {_id, name, images, price, description}  = goodById.payload;
+            const card = document.createElement('div');
+            card.innerHTML = `<h2>${name}</h2>
+                            <img src="${backURL}/${images[0].url}" />
+                            <strong>${price}</strong>
+                            <h2>${description}</h2>
+                            `;
+            main.append(card);
+        }
+    }
+    //ТУТ ДОЛЖНА БЫТЬ ПРОВЕРКА НА НАЛИЧИЕ goodById в редакс
+    //и проверка на то, что сейчас в адресной строке адрес ВИДА #/good/АЙДИ
+    //в таком случае очищаем main и рисуем информацию про товар с подробностями
+)
+
+
+store.subscribe(() => {
+    const {auth} = store.getState()
+    const {payload} = auth
+    if (payload?.sub ) {
+        topContaner.innerHTML = ''
+        const {id, login}  = payload.sub
+        const name = document.createElement('div')
+        name.innerText = `ПРИВЕТ ${login}`
+        topContaner.append(name)
+        const myOrders = document.createElement('a')
+        myOrders.innerText = 'Мои заказы'
+        myOrders.href       = `#/orders/${id}`
+        topContaner.append(myOrders)
+    } else {
+        topContaner.innerHTML = ''
+    }
+})
+
+
+
+store.subscribe(() => {
+    const {promise} = store.getState()
+    const {goodByUser} = promise
+    const [,route, _id] = location.hash.split('/')
+    if (goodByUser?.payload && route === 'orders'){
+
+        main.innerHTML = ''   
+       
+        if (goodByUser.payload.orderGoods) {
+            for (const {price, count, total, good: {name, images}} of goodByUser.payload.orderGoods){
+                const card      = document.createElement('div')
+                card.innerHTML = `<h2>${name}</h2>
+                                  <img src="${backURL}/${images[0].url}" />
+                                  <strong>Куплено ${count} по ${price} грн. Итого:${total}</strong>
+                                  <br>
+                                  <a href="#/good/${_id}">Перейти на страницу товара</a>
+                                `
+                main.append(card)
+            }
+        }
+    }
+})
+
+
+
+store.subscribe(() => {
+    const {cart} = store.getState()
+    let counter = 0;
+    
+    for (const key in cart) {
+        counter += cart[key].count
+    }
+    cartIcon.innerText  = counter
+})
+// store.dispatch(actionPromise('delay1000', delay(1000)))
+// // store.dispatch(actionPromise('delay2000', delay(2000)))     
+// // store.dispatch(actionPromise('luke', fetch('https://swapi.dev/api/people/1/').then(res => res.json())))
+
+
+
+
+
+
+
+
+
+
+
+