Mitrofanova Natali 3 years ago
parent
commit
ecca47292d

+ 5 - 0
HW11 Redux/.idea/.gitignore

@@ -0,0 +1,5 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/

+ 1 - 0
HW11 Redux/.idea/.name

@@ -0,0 +1 @@
+script.js

+ 12 - 0
HW11 Redux/.idea/ClassWork.iml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="WEB_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$">
+      <excludeFolder url="file://$MODULE_DIR$/temp" />
+      <excludeFolder url="file://$MODULE_DIR$/.tmp" />
+      <excludeFolder url="file://$MODULE_DIR$/tmp" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 8 - 0
HW11 Redux/.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/ClassWork.iml" filepath="$PROJECT_DIR$/.idea/ClassWork.iml" />
+    </modules>
+  </component>
+</project>

BIN
HW11 Redux/auto.jpg


+ 36 - 0
HW11 Redux/index.html

@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>kiset</title>
+    <link rel="stylesheet" href="style.css">
+</head>
+<body>
+
+
+
+<div class="wrapper">
+    <div class="wrapperShowCase">
+
+    </div>
+    <div class="showcase">
+        <select id="select"></select>
+        <input id="input" placeholder="скока шт надо?" type="number">
+    </div>
+
+    <p id="cashier"> К ОПЛАТЕ :</p>
+    <p>Баблоприемник</p>  
+    
+    <div class="wrapperBablo">
+        <input id="bablo" placeholder="скока даешь?" type="number">
+        <button id="btn">Купить</button>
+    </div>
+
+    <p class="alarm">Автомат сдачу не дает!</p>
+    <div class="cashbox">КАССА: 0</div>
+    
+</div>
+
+    <script src="script.js"></script>
+</body>
+</html>

+ 132 - 0
HW11 Redux/script.js

@@ -0,0 +1,132 @@
+const select = document.getElementById("select");
+const input = document.getElementById("input");
+const btn = document.getElementById("btn");
+const cash = document.querySelector(".cashbox");
+const bablo = document.getElementById("bablo");
+const cashier = document.getElementById("cashier");
+
+
+const store = createStore(reducer);
+updateShowCase()
+store.subscribe(updateCashbox);
+store.subscribe(updateShowCase);
+const unsubscribe = store.subscribe(() => console.log(store.getState()));
+
+function reducer(state, { type, ШО, СКОКА, БАБЛО }) {
+  //объект action деструктуризируется на три переменных
+  if (!state) {
+    //начальная уборка в ларьке:
+    return {
+      stock: {
+        пиво: {
+          price: 20,
+          amount: 100,
+          img : "https://pivasik.com.ua/wp-content/uploads/2019/09/orange.png",
+          
+        },
+        чипсы: {
+          price: 25,
+          amount: 100,
+          img : "https://cdn.27.ua/499/24/05/74757_4.jpeg",
+        },
+        сиги: {
+          price: 50,
+          amount: 100,
+          img: "https://img1.liveinternet.ru/images/attach/c/8/100/745/100745087_kozak_bf_red500x500.jpg",
+        },
+      },
+      cashbox: 0,
+    };
+    //
+  }
+  if (type === "КУПИТЬ") {
+    //если тип action - КУПИТЬ, то:
+    return {
+      ...state, //берем все что было из ассортимента
+      stock: {
+          ...state.stock,
+          [ШО]: {
+            price: state.stock[ШО].price,
+            amount: state.stock[ШО].amount - СКОКА,
+            img: state.stock[ШО].img
+      }
+      }, //и уменьшаем то, что покупается на количество
+    cashbox: state.cashbox + БАБЛО,
+    };
+  }
+
+  return state; //если мы не поняли, что от нас просят в `action` - оставляем все как есть
+}
+
+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) => {
+    const newState = reducer(state, action); //пробуем запустить редьюсер
+    if (newState !== state) {
+      //проверяем, смог ли редьюсер обработать action
+      state = newState; //если смог, то обновляем state
+      for (let cb of cbs) cb(); //и запускаем подписчиков
+    }
+  };
+
+  return {
+    getState, //добавление функции getState в результирующий объект
+    dispatch,
+    subscribe, //добавление subscribe в объект
+  };
+}
+let html = "";
+for (let key in store.getState().stock) {
+  html += `<option>${key}</option>`;
+}
+select.innerHTML = html;
+
+btn.addEventListener("click", buy);
+input.addEventListener("input", counter );
+select.addEventListener("click", counter)
+
+function buy(e) {
+    if(bablo.value >= (input.value * store.getState().stock[select.value].price) ){
+  store.dispatch({
+    type: "КУПИТЬ",
+    ШО: select.value,
+    СКОКА: input.value,
+    БАБЛО: Number(bablo.value),
+  });
+  bablo.value = "";
+}else{
+    alert("Не хватает бабла");
+}
+}
+function updateCashbox(){
+    cash.innerText = `КАССА : ${store.getState().cashbox}`
+}
+function counter( ){
+    if (input.value > store.getState().stock[select.value].amount){
+      input.value = store.getState().stock[select.value].amount;
+    }
+    cashier.innerText = ` К ОПЛАТЕ : ${ (input.value * store.getState().stock[select.value].price)}`;
+}
+
+function updateShowCase(){
+  const obj = store.getState().stock;
+  const wrapperShowCase = document.querySelector(".wrapperShowCase");
+  wrapperShowCase.innerHTML = "";
+  let  html =""
+  for(const good in obj){
+    html += `<div class="showCaseBlock">`;
+    html += `<img class="img" src = ${obj[good].img}>`;
+    html += `<p class="info">ЦЕНА: ${obj[good].price} грн</p>`;
+    html += `<p class="info">в наличии: ${obj[good].amount} шт</p>`
+    html += `</div>`;
+  }
+  wrapperShowCase.innerHTML = html;
+}

+ 92 - 0
HW11 Redux/style.css

@@ -0,0 +1,92 @@
+html{
+    width: 100vw;
+    height: 100vh;
+    background-color: #E0E0E0;
+}
+body{
+    width: 100%;
+    height: 100%;
+    display: flex;
+    justify-content: center;
+    align-items: center;
+}
+.wrapper{
+    margin-top: 150px;
+    min-width: 800px;
+    min-height: 1000px;
+    position: relative;
+    display: flex;
+    flex-direction: column;
+    justify-content: center;
+    align-items: center;
+}
+.wrapper::after{
+    content: "";
+    position: absolute;
+    background: url(auto.jpg);
+    z-index: -1;
+    width: 100%;
+    height: 100%;
+    opacity: 0.6;
+    background-repeat: no-repeat no-repeat;
+    background-position: center;
+}
+
+input{
+    height: 25px;
+    text-align: center;
+    font-size: 20px;
+}
+select{
+    height: 31px;
+    font-size: 25px;
+}
+button{
+    font-size: 20px;
+    width: 100px;
+    margin-left: 10px;
+    height: 31px;
+}
+.cashbox{
+    margin-top: 50px;
+    background-color: blanchedalmond;
+}
+p{
+    padding: 3px;
+    font-size: 20px;
+    background-color: honeydew;
+}
+p.info{
+    padding: 0;
+    margin: 0;
+}
+.showcase{
+    display: flex;
+}
+.wrapperBablo{
+    display: flex;
+}
+#bablo{
+    width: 210px;    
+}
+.alarm{
+    color: red;
+}
+.wrapperShowCase{
+    width: 800px;
+    height: 200px;
+    background-color: #E0E0E0;
+    margin-top: -390px;
+    margin-bottom: 150px;
+    display: flex;
+    justify-content: space-between;
+}
+.showCaseBlock{
+    width:200px;
+    height: 200px;
+}
+.img{
+    width:200px;
+    height: 200px;
+    
+}