Browse Source

done project

Illia Kozyr 1 year ago
parent
commit
924c5c74f0
100 changed files with 64360 additions and 0 deletions
  1. BIN
      Fakogram REACT project/.DS_Store
  2. BIN
      JavaScript HW/.DS_Store
  3. 54 0
      JavaScript HW/Chat/index.html
  4. 35 0
      JavaScript HW/HW 1/index.html
  5. BIN
      JavaScript HW/HW 10/.DS_Store
  6. 162 0
      JavaScript HW/HW 10/hw10.html
  7. 5 0
      JavaScript HW/HW 11/.idea/.gitignore
  8. 12 0
      JavaScript HW/HW 11/.idea/HW 11.iml
  9. 8 0
      JavaScript HW/HW 11/.idea/modules.xml
  10. 6 0
      JavaScript HW/HW 11/.idea/vcs.xml
  11. 244 0
      JavaScript HW/HW 11/index.html
  12. 5 0
      JavaScript HW/HW 12/.idea/.gitignore
  13. 12 0
      JavaScript HW/HW 12/.idea/HW 12.iml
  14. 8 0
      JavaScript HW/HW 12/.idea/modules.xml
  15. 6 0
      JavaScript HW/HW 12/.idea/vcs.xml
  16. 150 0
      JavaScript HW/HW 12/index.html
  17. BIN
      JavaScript HW/HW 13/.DS_Store
  18. 0 0
      JavaScript HW/HW 13/.idea/.gitignore
  19. 12 0
      JavaScript HW/HW 13/.idea/HW 13.iml
  20. 8 0
      JavaScript HW/HW 13/.idea/modules.xml
  21. 6 0
      JavaScript HW/HW 13/.idea/vcs.xml
  22. 45 0
      JavaScript HW/HW 13/.idea/workspace.xml
  23. 174 0
      JavaScript HW/HW 13/index.html
  24. 3 0
      JavaScript HW/HW 14/.vscode/settings.json
  25. 235 0
      JavaScript HW/HW 14/index.html
  26. BIN
      JavaScript HW/HW 15/.DS_Store
  27. 118 0
      JavaScript HW/HW 15/index.html
  28. 32 0
      JavaScript HW/HW 19/index.css
  29. 29 0
      JavaScript HW/HW 19/index.html
  30. 310 0
      JavaScript HW/HW 19/index.js
  31. 4 0
      JavaScript HW/HW 19/jquery-3.1.1.min.js
  32. 305 0
      JavaScript HW/HW 19/nb.js
  33. 6 0
      JavaScript HW/HW 19/papaparse.min.js
  34. 272 0
      JavaScript HW/HW 2/Homework2.html
  35. 378 0
      JavaScript HW/HW 3/index.html
  36. 376 0
      JavaScript HW/HW 4/homework4.html
  37. 405 0
      JavaScript HW/HW 5/index.html
  38. 149 0
      JavaScript HW/HW 6/index.html
  39. 5 0
      JavaScript HW/HW 7/.idea/.gitignore
  40. 12 0
      JavaScript HW/HW 7/.idea/HW 7.iml
  41. 8 0
      JavaScript HW/HW 7/.idea/modules.xml
  42. 6 0
      JavaScript HW/HW 7/.idea/vcs.xml
  43. 92 0
      JavaScript HW/HW 7/index.html
  44. BIN
      JavaScript HW/HW 8/.DS_Store
  45. 3 0
      JavaScript HW/HW 8/.vscode/settings.json
  46. 112 0
      JavaScript HW/HW 8/index.html
  47. 81 0
      JavaScript HW/HW 9/index.html
  48. BIN
      JavaScript HW/Крутилки/.DS_Store
  49. BIN
      JavaScript HW/Крутилки/img/1@3x.png
  50. 86 0
      JavaScript HW/Крутилки/index.js
  51. BIN
      JavaScript HW/Крутилки/media/klychko.mp3
  52. 17 0
      JavaScript HW/Крутилки/spinner.html
  53. 3 0
      Market GraphQL + Redux project/.vscode/settings.json
  54. 47 0
      Market GraphQL + Redux project/index.html
  55. 826 0
      Market GraphQL + Redux project/script.js
  56. 319 0
      Market GraphQL + Redux project/style.css
  57. BIN
      React HW/.DS_Store
  58. 23 0
      React HW/HW/.gitignore
  59. 70 0
      React HW/HW/README.md
  60. 28700 0
      React HW/HW/package-lock.json
  61. 38 0
      React HW/HW/package.json
  62. BIN
      React HW/HW/public/favicon.ico
  63. 43 0
      React HW/HW/public/index.html
  64. BIN
      React HW/HW/public/logo192.png
  65. BIN
      React HW/HW/public/logo512.png
  66. 25 0
      React HW/HW/public/manifest.json
  67. 3 0
      React HW/HW/public/robots.txt
  68. 119 0
      React HW/HW/src/App.css
  69. 26 0
      React HW/HW/src/App.js
  70. 8 0
      React HW/HW/src/App.test.js
  71. 58 0
      React HW/HW/src/components/Password.jsx
  72. 32 0
      React HW/HW/src/components/RangeInput.jsx
  73. 46 0
      React HW/HW/src/components/Spoiler.jsx
  74. 44 0
      React HW/HW/src/components/Timer.jsx
  75. 74 0
      React HW/HW/src/components/TimerControl.jsx
  76. 11 0
      React HW/HW/src/components/TimerParent.jsx
  77. 13 0
      React HW/HW/src/index.css
  78. 17 0
      React HW/HW/src/index.js
  79. 1 0
      React HW/HW/src/logo.svg
  80. 13 0
      React HW/HW/src/reportWebVitals.js
  81. 5 0
      React HW/HW/src/setupTests.js
  82. 23 0
      React HW/at a lecture/.gitignore
  83. 70 0
      React HW/at a lecture/README.md
  84. 28836 0
      React HW/at a lecture/package-lock.json
  85. 41 0
      React HW/at a lecture/package.json
  86. BIN
      React HW/at a lecture/public/favicon.ico
  87. 43 0
      React HW/at a lecture/public/index.html
  88. BIN
      React HW/at a lecture/public/logo192.png
  89. BIN
      React HW/at a lecture/public/logo512.png
  90. 25 0
      React HW/at a lecture/public/manifest.json
  91. 3 0
      React HW/at a lecture/public/robots.txt
  92. 89 0
      React HW/at a lecture/src/App.css
  93. 613 0
      React HW/at a lecture/src/App.js
  94. 8 0
      React HW/at a lecture/src/App.test.js
  95. 13 0
      React HW/at a lecture/src/index.css
  96. 17 0
      React HW/at a lecture/src/index.js
  97. 1 0
      React HW/at a lecture/src/logo.svg
  98. 13 0
      React HW/at a lecture/src/reportWebVitals.js
  99. 5 0
      React HW/at a lecture/src/setupTests.js
  100. 0 0
      React HW/Сайт A-Level React/.DS_Store

BIN
Fakogram REACT project/.DS_Store


BIN
JavaScript HW/.DS_Store


+ 54 - 0
JavaScript HW/Chat/index.html

@@ -0,0 +1,54 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>Static File Index.HTML</title>
+        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
+    </head>
+    <body>
+        <style>
+
+            .chat__header {
+              text-align: left;
+            }
+            .chat__message-content {
+              border-radius: 5px;
+              padding: 7px;
+              background-color: #ccc;
+              display: inline-block;
+              margin-left: 5px;
+            }
+            </style>
+            <body>
+                 
+            <main class="main">
+                <div class="chat"> 
+                    <h1 class="chat__header">Chat</h1>
+                <div id="content" class = "chat__header">
+                    <div class="chat__item">
+                        <h1 id = "chat__message-content" class="chat__message-content"></h1>
+                    </div>
+                    <div class="send_form">
+                        Nick :<input type="text" id = 'nick' > 
+                        Message :<input type="text" id = 'msg'>
+                        <button id="sendButton">Отправить</button>
+                    </div>
+                   
+                </div>
+            </main>
+            
+            <script>
+                const socket = io('http://socketchat.ed.asmer.org.ua')
+                socket.on('msg', msg => {
+                    console.log(msg)
+                    const my_P = document.createElement("div");
+                    my_P.innerHTML = '<b>' + msg.nick + ":" +"</b>" + msg.message
+                    document.getElementById("chat__message-content").appendChild(my_P)
+                })
+                
+                sendButton.onclick = () => {
+                    console.log(nick.value , msg.value)
+                    socket.emit('msg', {nick: nick.value, message: msg.value})
+                }
+            </script>
+    </body>
+</html>

+ 35 - 0
JavaScript HW/HW 1/index.html

@@ -0,0 +1,35 @@
+<!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>Homework 1 JavaScript</title>
+    </head>
+    <body>
+        <script> 
+            // -----
+            let CaloriesPerDay = 2000;
+            let CaloriesPerMeal = prompt(
+                "Введите, сколько калорий вы потребили:"
+            );
+            if (CaloriesPerMeal < CaloriesPerDay) {
+                let CalorieDifference = CaloriesPerDay - CaloriesPerMeal;
+                alert(
+                    "Вы ещё можете употребить: " +
+                        CalorieDifference +
+                        " калорий. Мало есть тоже плохо!"
+                );
+            } else if (CalorieDifference = CaloriesPerDay - CaloriesPerMeal){
+                alert(
+                    "Вы превысили лимит калорий в сутки на: " +
+                        CalorieDifference +
+                        "." +
+                        " Хватит жрать!"
+                );
+            } else {
+                alert ("Ошибка! Нужно вводить только цифры! Обновите страницу, чтобы попробовать снова!")
+            }
+        </script>
+    </body>
+</html>

BIN
JavaScript HW/HW 10/.DS_Store


+ 162 - 0
JavaScript HW/HW 10/hw10.html

@@ -0,0 +1,162 @@
+<!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>
+        <div id='container1'></div>
+        <div id='formContainer'></div>
+    </body>
+        <script>
+            //---------------------------------------Password
+            function Password(parent, open) {
+                let passField = document.createElement("input");
+                passField.placeholder = "введите пароль";
+                let checkBox = document.createElement("input");
+                checkBox.setAttribute("type", "checkbox");
+                parent.append(passField, checkBox);
+
+                this.setValue = (newValue) => {
+                    passField.value = newValue;
+                };
+                this.getValue = () => passField.value;
+
+                this.setOpen = (newOpen) => {
+                    open = newOpen;
+                    if (open === true) {
+                        checkBox.setAttribute("checked", "true");
+                        passField.setAttribute("type", "text");
+                    } else if (open === false) {
+                        checkBox.setAttribute("checked", "false");
+                        passField.setAttribute("type", "password");
+                    }
+                };
+                this.setOpen(open);
+                this.getOpen = () => checkBox.checked;
+
+                passField.oninput = () => {
+                    if (typeof this.onChange === "function") {
+                        this.onChange(this.getValue());
+                    }
+                };
+
+                checkBox.oninput = () => {
+                    if (this.getOpen() === true) {
+                        this.setOpen(true);
+                    } else {
+                        this.setOpen(false);
+                    }
+                    if (typeof this.onOpenChange === "function") {
+                        this.onOpenChange(this.getOpen());
+                    }
+                };
+            }
+            // let p = new Password(document.body, true);
+            // p.onchange = (data) => console.log(data);
+            // p.onopenchange = (open) => console.log(open);
+            // p.setValue("qwerty");
+            // console.log(p.getValue());
+            // p.setOpen(false);
+            // console.log(p.getOpen());
+
+            // //---------------------------------------LoginForm
+            //     let passwordInput = new Password(document.body, true)
+            //     let loginInput = document.createElement('input')
+            //     let loginButton = document.createElement('input')
+            //     loginInput.placeholder = 'введите логин'
+            //     loginButton.type = 'button'
+            //     loginButton.value = 'Войти'
+            //     loginButton.disabled = true
+            //     loginInput.setAttribute('oninput','f()')
+            //     formContainer.append(loginInput,loginButton)
+            //     passwordInput.onChange = data => console.log(data)
+            
+            // function f(){
+            //     if ((loginInput.value === '' ) || (passwordInput.getValue() === '')) {
+            //     loginButton.disabled=true
+            // } else
+            //      loginButton.disabled=false
+            // }
+            // passwordInput.onChange = f
+
+            // //---------------------------------------LoginForm constructor
+            // function Login(parent) {
+            //     this.parent = parent;
+            //     let login = document.createElement('input')
+            //     login.placeholder = 'введите логин'
+            //     let button = document.createElement('button')
+            //     button.innerText = 'Войти'
+            //     button.disabled = true
+            //     let password = new Password(this.parent, true);
+            //     parent.append(login,button)
+            
+            
+            //     this.setActive = (value) => {
+            //         if (value === true) {
+            //             button.disabled = true;
+            //         } else {
+            //             button.disabled = false;
+            //         }
+            //     }
+
+            //     this.getPassword = () => {
+            //         return this.passwordInput
+            //     }
+            
+            //     password.onChange = (data) => {
+            //         if(login.value === '' || data === '' ) {
+            //             this.setActive(true)
+            //         } else {
+            //             this.setActive(false)
+            //         }
+            //     }
+            
+            //     login.oninput = () => {
+            //         login.innerHTML = login.value;
+            //         console.log(login.value)
+            //         if(login.value === '') {
+            //             this.setActive(true)
+            //         } else {
+            //             this.setActive(false)
+            //         }
+            //     }
+            // }
+            // let login = new Login(formContainer)
+
+            //---------------------------------------Password verify
+            let p = new Password(formContainer, true)
+            let p2 = document.createElement('input')
+            p2.type = 'password'
+            p2.style.display = 'none'
+            p2.placeholder = 'повторите пароль'
+            p2.setAttribute('oninput','f()')
+            let button = document.createElement('button')
+            button.innerText = 'Войти'
+            button.disabled = true
+            p.onChange = data => console.log(data)
+            
+            formContainer.append(p2,button)
+            
+            function f () {
+                if (p.getOpen() === true) {
+                    p2.style.display = 'none'
+            
+                    if (p.getValue() != '') {
+                        button.disabled = false
+                    } else {button.disabled = true}
+            
+                } else {
+                    if (p.getValue() != '' && (p.getValue() === p2.value)) {
+                        button.disabled = false
+                    } else {button.disabled = true}
+                    p2.style.display = ''}
+            }
+            p.onOpenChange = f
+            p.onChange = f
+            console.log(p.getValue())
+        </script>
+    </body>
+</html>

+ 5 - 0
JavaScript HW/HW 11/.idea/.gitignore

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

+ 12 - 0
JavaScript HW/HW 11/.idea/HW 11.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
JavaScript HW/HW 11/.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/HW 11.iml" filepath="$PROJECT_DIR$/.idea/HW 11.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
JavaScript HW/HW 11/.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
+  </component>
+</project>

File diff suppressed because it is too large
+ 244 - 0
JavaScript HW/HW 11/index.html


+ 5 - 0
JavaScript HW/HW 12/.idea/.gitignore

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

+ 12 - 0
JavaScript HW/HW 12/.idea/HW 12.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
JavaScript HW/HW 12/.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/HW 12.iml" filepath="$PROJECT_DIR$/.idea/HW 12.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
JavaScript HW/HW 12/.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
+  </component>
+</project>

+ 150 - 0
JavaScript HW/HW 12/index.html

@@ -0,0 +1,150 @@
+<!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">
+</head>
+<body>
+    <script>
+//-------------------fetch basic
+
+// let DOM = document.body;
+// fetch('https://swapi.py4e.com/api/people/1/')
+//   .then(res => res.json(),
+//         err => console.log("ERROR"))
+//     .then(luke => createTable(DOM, luke));
+
+// function createTable(DOM, JSON) {
+//     console.log(DOM, JSON);
+//     const tableEl = document.createElement("table");
+//     tableEl.border = 1;
+
+//     for(let [key, value] of Object.entries(JSON)) {
+//         createTr(key,value);
+//     }
+
+//     DOM.append(tableEl);
+
+//     function createTr(td1,td2) {
+//         const trEl = document.createElement("tr");
+//         const td1El = document.createElement("td");
+//         const td2El = document.createElement("td");
+//         td1El.innerHTML = td1;
+//         if(typeof td2 ==="object") {
+//             const ulEl = document.createElement("ul");
+//             for(let value of td2) {
+//                 const liEl = document.createElement("li");
+//                 liEl.innerText = value;
+//                 ulEl.appendChild(liEl);
+//             }
+//             td2El.appendChild(ulEl);
+//         } else {
+//             td2El.innerHTML = td2;  
+//         }
+//         trEl.append(td1El,td2El);
+//         tableEl.append(trEl);
+//     }
+
+// }
+
+//-------------------fetch improved
+// let DOM = document.body;
+// myFetch(DOM);
+
+// function myFetch(dom) {
+// fetch('https://swapi.py4e.com/api/people/1/')
+//   .then(res => res.json(),
+//         err => console.log("ERROR"))
+//     .then(luke => createTable(dom, luke));
+// }
+
+// function createTable(DOM, JSON) {
+//     console.log(DOM, JSON);
+//     const tableEl = document.createElement("table");
+//     tableEl.border = 1;
+//     for(let [key, value] of Object.entries(JSON)) {
+//         createTr(key,value);
+//     }
+//     DOM.append(tableEl);
+
+//     function createTr(td1,td2) {
+//         const trEl = document.createElement("tr");
+//         const td1El = document.createElement("td");
+//         const td2El = document.createElement("td");
+//         td1El.innerHTML = td1;
+//         if(typeof td2 ==="number") td2 = td2.toString();
+//         if(typeof td2!=="object"&&!td2.indexOf("https://swapi.py4e.com/api/")) td2 = [td2];
+//         if(typeof td2 ==="object") {
+//             const ulEl = document.createElement("ul");
+//             for(let value of td2) {
+//                 const liEl = document.createElement("li");
+//                 const buttonEl = document.createElement("button");
+//                 buttonEl.innerText = value;
+//                 buttonEl.onclick = () => {
+//                     buttonEl.hidden = true;
+//                     myFetch(buttonEl.parentElement);
+//                 }
+//                 liEl.appendChild(buttonEl);
+//                 ulEl.appendChild(liEl);
+//             }
+//             td2El.appendChild(ulEl);
+//         } else {
+//             td2El.innerHTML = td2;
+//         }
+//         trEl.append(td1El,td2El);
+//         tableEl.append(trEl);
+//     }
+// }
+//-------------------myfetch
+
+// myfetch('https://swapi.py4e.com/api/people/1/').then(luke => console.log(luke));
+
+// function myfetch(url){
+//     return new Promise(function (resolve, reject){
+//         const xhr = new XMLHttpRequest();
+//         xhr.open('GET', url, true);
+//         xhr.responseType = "json";
+//         xhr.onload = function(){
+//             if (xhr.status == 200){
+//                 resolve(xhr.response);
+//             }
+//             else {
+//                 reject(`ERROR ${xhr.status} - ${xhr.statusText}`);
+//             }
+//         }
+//         xhr.onerror = () => reject(`ERROR ${xhr.status} - ${xhr.statusText}`);
+//         xhr.send();
+//     })
+// }
+//-------------------race
+
+Promise.race([myfetch('https://swapi.py4e.com/api/people/1/'),delay(30)]).then((value) => console.log(value));
+
+
+function myfetch(url){
+    return new Promise(function (resolve, reject){
+        const xhr = new XMLHttpRequest();
+        xhr.open('GET', url, true);
+        xhr.responseType = "json";
+        xhr.onload = function(){
+            if (xhr.status == 200){
+                resolve(xhr.response);
+            }
+            else {
+                reject(`ERROR ${xhr.status} - ${xhr.statusText}`);
+            }
+        }
+        xhr.onerror = () => reject(`ERROR ${xhr.status} - ${xhr.statusText}`);
+        xhr.send();
+    })
+}
+
+function delay(ms) {
+    return new Promise(function(resolve,reject) {
+        setTimeout(resolve,ms,"delay");
+    })
+}
+    </script>
+</body>
+</html>

BIN
JavaScript HW/HW 13/.DS_Store


+ 0 - 0
JavaScript HW/HW 13/.idea/.gitignore


+ 12 - 0
JavaScript HW/HW 13/.idea/HW 13.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
JavaScript HW/HW 13/.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/HW 13.iml" filepath="$PROJECT_DIR$/.idea/HW 13.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
JavaScript HW/HW 13/.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
+  </component>
+</project>

+ 45 - 0
JavaScript HW/HW 13/.idea/workspace.xml

@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ChangeListManager">
+    <list default="true" id="51dfd18f-7a47-49ce-9801-57632f89f3f0" name="Changes" comment="" />
+    <option name="SHOW_DIALOG" value="false" />
+    <option name="HIGHLIGHT_CONFLICTS" value="true" />
+    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
+    <option name="LAST_RESOLUTION" value="IGNORE" />
+  </component>
+  <component name="Git.Settings">
+    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
+  </component>
+  <component name="MarkdownSettingsMigration">
+    <option name="stateVersion" value="1" />
+  </component>
+  <component name="ProjectId" id="2C4dFDaIZFOQvMLSnWmCVOeXWSQ" />
+  <component name="ProjectLevelVcsManager" settingsEditedManually="true" />
+  <component name="ProjectViewState">
+    <option name="hideEmptyMiddlePackages" value="true" />
+    <option name="showLibraryContents" value="true" />
+  </component>
+  <component name="PropertiesComponent"><![CDATA[{
+  "keyToString": {
+    "RunOnceActivity.OpenProjectViewOnStart": "true",
+    "RunOnceActivity.ShowReadmeOnStart": "true",
+    "WebServerToolWindowFactoryState": "false",
+    "vue.rearranger.settings.migration": "true"
+  }
+}]]></component>
+  <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
+  <component name="TaskManager">
+    <task active="true" id="Default" summary="Default task">
+      <changelist id="51dfd18f-7a47-49ce-9801-57632f89f3f0" name="Changes" comment="" />
+      <created>1658065684510</created>
+      <option name="number" value="Default" />
+      <option name="presentableId" value="Default" />
+      <updated>1658065684510</updated>
+      <workItem from="1658065685740" duration="9000" />
+    </task>
+    <servers />
+  </component>
+  <component name="TypeScriptGeneratedFilesManager">
+    <option name="version" value="3" />
+  </component>
+</project>

+ 174 - 0
JavaScript HW/HW 13/index.html

@@ -0,0 +1,174 @@
+<!DOCTYPE html>
+<html lang="en">
+    
+    <head>
+        <meta charset="UTF-8" />
+        <meta
+            name="viewport"
+            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
+        />
+        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+        <title>Not Telegram</title>
+        <style>
+            body {
+                background-color: aqua;
+                margin: 0;
+            }
+            .logo {
+                background-color: blueviolet;
+            }
+            h1 {
+                text-align: center;
+                color: aqua;
+                height: 60px;
+                margin: 0;
+                padding-top: 20px;
+            }
+            input {
+                padding-left: 10px;
+                font-size: 20px;
+                width: 500px;
+                height: 50px;
+            }
+            #chat {
+                padding-left: 20px;
+                font-size: 25px;
+                color: aqua;
+                width: 1250px;
+                height: 600px;
+                background-color: blueviolet;
+            }
+            .inputBlock {
+                padding-left: 20px;
+            }
+            #button {
+                margin-top: 30px;
+                height: 50px;
+                width: 120px;
+                background-color: blueviolet;
+            }
+            #button:hover {
+                opacity: 0.8;
+            }
+            .buttonText {
+                margin: 0;
+                font-size: 20px;
+                color: aqua;
+            }
+            .chat {
+                max-width: 1250px;
+                margin: 0 auto;
+            }
+            .block {
+                max-width: 1200px;
+                border: 1px solid aqua;
+                border-radius: 2%;
+                padding: 0 30px;
+                margin: 7px 20px;
+                box-shadow: 7px 3px 3px black;
+                color: aqua;
+            }
+            #container{
+                padding-top: 15px;
+                background-color: blueviolet;
+            }
+        </style>
+    </head>
+
+    <body>
+
+        <div class="chat">
+            <div class="logo">
+                <h1>Чат "Not Telegram"</h1>
+            </div>
+
+            <div class="">
+                <div class="inputBlock">
+                    <h2>Ваш ник:</h2>
+                    <input
+                        type="text"
+                        name="nickname"
+                        id="nick"
+                        value="illiaKozyr"
+                    />
+                    <h2>Ваше сообщение:</h2>
+                    <input
+                        type="text"
+                        name=""
+                        id="message"
+                        value="test message"
+                    />
+                    <br />
+                    <button id="button">
+                        <p class="buttonText">Отправить</p>
+                    </button>
+                    <h2>Чат:</h2>
+                </div>
+                <div id="container"></div>
+            </div>
+        </div>
+
+        <script>
+
+            const url = "http://students.a-level.com.ua:10012";
+            const nick = document.getElementById("nick");
+            const message = document.getElementById("message");
+            const btnSendMessage = document.getElementById("button");
+            const container = document.getElementById("container");
+            let nextMessageId = 1;
+            let delay = 2000;
+            setInterval(getMessages, delay);
+
+            function getMessages() {
+                jsonPost(url, { func: "getMessages", messageId: nextMessageId })
+                    .then((response) => response.json())
+                    .then((data) => {
+                        nextMessageId = data.nextMessageId;
+                        updateMessages(data.data);
+                    });
+            }
+
+            function jsonPost(url, data) {
+                return fetch(url, {
+                    method: "POST",
+                    body: JSON.stringify(data),
+                });
+            }
+
+            function updateMessages(messageList) {
+                messageList.forEach((msg) => {
+                    newGotMessage(msg);
+                });
+            }
+
+            function newGotMessage({ nick, message, timestamp }) {
+                const newBlock = document.createElement("div");
+                newBlock.classList.add("block");
+
+                const time = new Date(timestamp);
+                let html = "";
+                html += `<p>${nick}<p>`;
+                html += `<p class="message">"${message}"</p>`;
+                html += `<p>${time.toString().substring(16, 24)}</p>`;
+                newBlock.innerHTML = html;
+                container.prepend(newBlock);
+            }
+
+            btnSendMessage.addEventListener("click", sendAndCheck);
+
+            async function sendAndCheck() {
+                await sendMessage();
+                getMessages();
+                message.value = "";
+            }
+
+            async function sendMessage() {
+                jsonPost(url, {
+                    func: "addMessage",
+                    nick: nick.value,
+                    message: message.value,
+                });
+            }
+        </script>
+    </body>
+</html>

+ 3 - 0
JavaScript HW/HW 14/.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+    "liveServer.settings.port": 5501
+}

+ 235 - 0
JavaScript HW/HW 14/index.html

@@ -0,0 +1,235 @@
+<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <meta charset="UTF-8" />
+        <meta
+            name="viewport"
+            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
+        />
+        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+        <title>Светофор</title>
+        <style>
+            .container {
+                padding-top: 30px;
+                display: flex;
+                justify-content: center;
+            }
+            #trafficLightBlock {
+                background-color: black;
+                max-width: 200px;
+                height: 660px;
+                padding: 30px;
+            }
+            #trafficLightPedestrian {
+                margin-left: 100px;
+                background-color: black;
+                max-width: 200px;
+                height: 430px;
+                padding: 30px;
+            }
+            #red,
+            #Red {
+                width: 200px;
+                height: 200px;
+                border-radius: 50%;
+                background-color: gray;
+                margin: 0;
+                margin-bottom: 30px;
+            }
+            #yellow {
+                width: 200px;
+                height: 200px;
+                border-radius: 50%;
+                background-color: gray;
+                margin: 0;
+                margin-bottom: 30px;
+            }
+            #green,
+            #Green {
+                width: 200px;
+                height: 200px;
+                border-radius: 50%;
+                background-color: gray;
+                margin: 0;
+            }
+            h1 {
+                font-size: 80px;
+                color: white;
+                text-align: center;
+                margin: 0;
+                padding-top: 50px;
+            }
+            #knopka {
+                margin-top: 50px;
+                width: 200px;
+                height: 50px;
+                background-color: grey;
+                color: white;
+                font-size: 20px;
+            }
+        </style>
+    </head>
+    <body>
+        <div class="container">
+            <div id="trafficLightBlock">
+                <div id="red">
+                    <h1 id="redTimer"></h1>
+                </div>
+                <div id="yellow">
+                    <h1 id="yellowTimer"></h1>
+                </div>
+                <div id="green">
+                    <h1 id="greenTimer"></h1>
+                </div>
+            </div>
+            <div id="trafficLightPedestrian">
+                <div id="Red">
+                    <h1 id="RedTimer"></h1>
+                </div>
+                <div id="Green">
+                    <h1 id="GreenTimer"></h1>
+                </div>
+                <button id="knopka">Click to go</button>
+            </div>
+        </div>
+
+        <script>
+            const delay = (ms) =>
+                new Promise((ok) => setTimeout(() => ok(ms), ms));
+
+            async function timerShow(sec, id) {
+                for (sec; sec > 0; sec--) {
+                    id.innerHTML = sec;
+                    a = await delay(1000);
+                    id.innerHTML = "";
+                }
+            }
+
+            async function trafficLight() {
+                while (true) {
+                    // delay(1000).then(() => (document.getElementById("red").style.background = "red"))
+                    // delay(2000).then(() => (document.getElementById("red").style.background = "grey"))
+                    // delay(3000).then(() => (document.getElementById("yellow").style.background = "orange"))
+                    // delay(4000).then(() => (document.getElementById("yellow").style.background = "grey"))
+                    // delay(5000).then(() => (document.getElementById("green").style.background = "green"))
+                    // delay(6000).then(() => (document.getElementById("green").style.background = "grey"))
+
+                    let styleRed = (document.getElementById(
+                        "red"
+                    ).style.background = "red");
+
+                    timerShow(4, redTimer);
+
+                    var awaitRedGrey = await delay(5000);
+                    var styleGrey = (document.getElementById(
+                        "red"
+                    ).style.background = "grey");
+                    let styleYellow = (document.getElementById(
+                        "yellow"
+                    ).style.background = "yellow");
+
+                    var awaitRedGrey = await delay(2000);
+                    var styleGrey = (document.getElementById(
+                        "yellow"
+                    ).style.background = "grey");
+                    let styleGreen = (document.getElementById(
+                        "green"
+                    ).style.background = "green");
+
+                    timerShow(4, greenTimer);
+
+                    var awaitRedGrey = await delay(5000);
+                    var styleGrey = (document.getElementById(
+                        "green"
+                    ).style.background = "grey");
+                    let styleYelloww = (document.getElementById(
+                        "yellow"
+                    ).style.background = "orange");
+
+                    var awaitRedGrey = await delay(2000);
+                    var styleGrey = (document.getElementById(
+                        "yellow"
+                    ).style.background = "grey");
+                }
+            }
+
+            function domEventPromise(btn, eventName) {
+                return new Promise((resolve, reject) => {
+                    btn.addEventListener(eventName, (event) => {
+                        resolve(event);
+                    });
+                    btn.removeEventListener(eventName, (event) => {
+                        resolve(event);
+                    });
+                });
+            }
+
+            async function pedestrianTrafficLight() {
+                while (true) {
+                    if (true) {
+                        Red.style.background = "red";
+                        Green.style.background = "grey";
+                        knopka.disabled = true;
+                        await delay(3000);
+                        knopka.disabled = false;
+                        await Promise.race([
+                            delay(4000),
+                            domEventPromise(knopka, "click").then((e) =>
+                                console.log("event click happens", e)
+                            ),
+                        ]);
+                    }
+                    if (true) {
+                        knopka.disabled = true;
+                        Green.style.background = "green";
+                        Red.style.background = "grey";
+                        await delay(5000);
+                    }
+                }
+            }
+
+            trafficLight();
+            pedestrianTrafficLight();
+
+
+
+
+            async function speedtest(getPromise, count, parallel = 1) {
+                let duration = performance.now();
+                let initParallel = parallel;
+                let promisArray = [];
+                for (let i = 0; i < count; i++) {
+                    promisArray[i] = getPromise();
+                    parallel -= 1;
+                    await Promise.all(promisArray);
+                }
+
+                console.log(promisArray);
+
+                duration = performance.now() - duration;
+                console.log(duration);
+                console.log(initParallel * count);
+
+                return {
+                    duration: duration,
+                    querySpeed: count / duration,
+                    queryDuration: duration / count,
+                    parallelSpeed: (count / duration) * initParallel,
+                    parallelDuration: duration / (initParallel * count),
+                };
+            }
+
+            speedtest(() => delay(1000), 10, 10).then((result) =>
+                console.log(result)
+            );
+            speedtest(
+                () =>
+                    fetch("http://swapi.dev/api/people/1").then((res) =>
+                        res.json()
+                    ),
+                1,
+                2
+            );
+        </script>
+    </body>
+</html>

BIN
JavaScript HW/HW 15/.DS_Store


+ 118 - 0
JavaScript HW/HW 15/index.html

@@ -0,0 +1,118 @@
+<!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>GraphQL</title>
+        <style></style>
+    </head>
+    <body>
+        <script>
+            const backendURL = "http://shop-roles.node.ed.asmer.org.ua/graphql";
+
+            let gql = (url, query, variables = {}) =>
+                fetch(url, {
+                    method: "POST",
+                    headers: {
+                        Accept: "application/json",
+                        "Content-Type": "application/json",
+                    },
+                    body: JSON.stringify({ query, variables }),
+                }).then((res) => res.json());
+
+            const categoryFind = () =>
+                gql(
+                    backendURL,
+                    `
+                    query catz{
+                        CategoryFind(query:"[{}]") {
+                            name
+                        }
+                    }
+                    `
+                );
+
+            const registerUser = (login, password) =>
+                gql(
+                    backendURL,
+                    `
+                    mutation register($login:String, $password:String){
+                        UserUpsert(user: {login:$login, password:$password}){
+                            _id login createdAt
+                        }
+                    }
+                `,
+                    { login, password }
+                );
+
+            const login = (login, password) =>
+                gql(
+                    backendURL,
+                    `
+                    query login($login:String, $password:String){
+                        login(login:$login, password:$password)
+                    }
+                `,
+                    { login, password }
+                );
+
+            const categories = () =>
+                gql(
+                    backendURL,
+                    `
+                        query categoryFind{
+                            CategoryFind(query:"[{}]"){
+                            _id name goods {
+                                _id
+                                createdAt
+                                name
+                                description
+                                price
+                            }
+                        }
+                    }`
+                );
+
+            const productSearchByIdImgDiscr = (id) => {
+                let a = `\\"_id\\":\\"${id}\\"`;
+                return gql(
+                    backendURL,
+                    `
+                    query searchId{
+                            GoodFind(query:"[{${a}}]"){
+                                name description images {
+                                  _id
+                                  createdAt
+                                  text
+                                  url
+                                  originalFileName
+                                }
+                            }
+                        }`
+                );
+                
+            };
+
+            (async () => {
+                console.log("all category:", await categoryFind());
+                console.log(
+                    "register user:",
+                    await registerUser("illiaKozyr", "qwerty123456")
+                );
+                console.log(
+                    "user login:",
+                    await login("illiaKozyr", "qwerty123456")
+                );
+                console.log(
+                    "category by id with products:",
+                    await categories()
+                );
+                console.log(
+                    "product search by id:",
+                    await productSearchByIdImgDiscr("62c9472cb74e1f5f2ec1a0d3")
+                );
+            })();
+        </script>
+    </body>
+</html>

+ 32 - 0
JavaScript HW/HW 19/index.css

@@ -0,0 +1,32 @@
+* {
+    box-sizing: border-box;   
+    margin: 0;
+    padding: 0;
+}
+
+body {
+    margin: 0;
+    padding: 0;
+}
+
+ button{
+    width: 100%;
+    font-size: 2em;
+}
+input, button, select{
+    width: 100%;
+    font-size: 2em;
+}
+
+table {
+    border: 1px;
+    border-collapse: collapse;
+}
+
+td,th {
+    border: 1px solid black;
+}
+
+/*div#content {*/
+    /*display: none;*/
+/*}*/

+ 29 - 0
JavaScript HW/HW 19/index.html

@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <meta name="viewport" content="width=device-width">
+        <title>eval</title>
+        <link href="index.css" rel="stylesheet" type="text/css" />
+        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
+        <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.3/papaparse.min.js"></script>
+        <script src="http://gitlab.a-level.com.ua/gitgod/nanobind/raw/master/static/nb.js"></script>
+    </head>
+    <body>
+        <canvas id='canvas' width=400 height=400></canvas> 
+        <button id='undo'>UNDO</button>
+        <input type='color' id='color'>
+        <select id='tool'>
+            <option value='ellipse'>Ellipse</option>
+            <option value='line'>Line</option>
+            <option value='rectangle'>Rectangle</option>
+            <option value='graffity'>Graffity</option>
+            <option value='circle'>Circle</option>
+            <option value='select'>Select</option>
+        </select>
+        <input type='number' id='size' value=10>
+        <button id='delete'>Delete...</button>
+        <script src="index.js"></script>
+    </body>
+</html>
+

+ 310 - 0
JavaScript HW/HW 19/index.js

@@ -0,0 +1,310 @@
+const canvas = document.getElementById('canvas')
+const ctx    = canvas.getContext('2d')
+
+const width  = canvas.width;
+const height = canvas.height;
+
+let current;
+let selection = []
+
+const tools = {
+    graffity: {
+        mousemove(e){ //e.buttons 0b00000x11 & 0b00000100 == x
+            (e.buttons & 0b001) && new Circle(e.layerX, e.layerY, +size.value, color.value)
+        }
+    },
+    circle: {
+        mousedown(e){
+            current = new Circle(e.layerX,e.layerY, 1, color.value)
+        },
+        mousemove(e){
+            if (!current) return;
+
+            current.radius = current.distanceTo(e.layerX, e.layerY)
+            Drawable.drawAll()
+        },
+
+        mouseup(e){
+            current = null
+        }
+    },
+    line: { //ctrl-c ctrl-v в rectangle. Так же добавьте его в <select id='tool'>
+        mousedown(e){
+            current = new Line(e.layerX, e.layerY, 0, 0, color.value, +size.value)
+        },
+        mousemove(e){
+            if (!current) return;
+
+            current.width = e.layerX - current.x
+            current.height = e.layerY - current.y
+
+            Drawable.drawAll()
+        },
+
+        mouseup(e){
+            current = null
+        }
+    },
+    rectangle: { //ctrl-c ctrl-v в rectangle. Так же добавьте его в <select id='tool'>
+        mousedown(e){
+            current = new Rectangle(e.layerX, e.layerY, 0, 0, color.value)
+        },
+        mousemove(e){
+            if (!current) return;
+
+            current.width = e.layerX - current.x
+            current.height = e.layerY - current.y
+
+            Drawable.drawAll()
+        },
+
+        mouseup(e){
+            current = null
+        }
+    },
+    ellipse: { //ctrl-c ctrl-v в rectangle. Так же добавьте его в <select id='tool'>
+        mousedown(e){
+            current = new Ellipse(e.layerX, e.layerY, 0, 0, color.value, +size.value)
+        },
+        mousemove(e){
+            if (!current) return;
+
+            current.width = e.layerX - current.x
+            current.height = e.layerY - current.y
+
+            Drawable.drawAll()
+        },
+
+        mouseup(e){
+            current = null
+        }
+    },
+    select: {
+        click(e){
+            console.log(e)
+            let found = Drawable.instances.filter(c => c.in && c.in(e.layerX, e.layerY))
+            if (found.length){
+                if (e.ctrlKey){
+                    selection.push(found.pop())
+                }
+                else {
+                    selection = [found.pop()]
+                }
+            }
+            else {
+                if (!e.ctrlKey) selection = []
+            }
+
+            console.log('selection', selection)
+
+            Drawable.drawAll(selection)
+        },
+        mousedown(e){
+            //
+        },
+        mousemove(e){
+
+        },
+
+        mouseup(e){
+            //x,y, w, h прямоугольника
+            //selection - только те элеменеты Drawable.instances которые в границах прямоугольника.
+        },
+    }
+}
+
+
+
+function superHandler(evt){
+    let t = tools[tool.value]
+    if (typeof t[evt.type] === 'function')
+        t[evt.type].call(this, evt)
+}
+
+canvas.onmousemove = superHandler
+canvas.onmouseup   = superHandler
+canvas.onmousedown = superHandler
+canvas.onclick = superHandler
+
+////
+
+
+function Drawable(){
+    Drawable.addInstance(this);
+}
+
+const distance = (x1,y1, x2, y2) => ((x1-x2)**2 + (y1-y2)**2)**0.5
+
+Drawable.prototype.draw = function(){};
+Drawable.prototype.distanceTo = function(x,y){
+    if (typeof this.x !== 'number' ||
+        typeof this.y !== 'number'){
+        return NaN
+    }
+    return distance(this.x, this.y, x, y)
+};
+Drawable.instances = [];
+Drawable.addInstance = function(item){
+    Drawable.instances.push(item);
+}
+
+Drawable.drawAll = function(selection=[]){
+    ctx.clearRect(0,0,width,height);
+    Drawable.forAll(item => item.draw())
+    selection.forEach(item  => item.draw(true))
+}
+
+Drawable.forAll = function(callback){
+    for(var i = 0; i<Drawable.instances.length;i++){
+        callback(Drawable.instances[i])
+    }
+}
+
+class Circle extends Drawable {
+    //__proto__: Drawable.prototype
+    constructor(x,y,radius, color){
+        super()
+        this.x      = x;
+        this.y      = y;
+        this.radius = radius;
+        this.color  = color;
+
+        this.draw();
+    }
+
+    draw(selected){
+        ctx.beginPath();
+        ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
+        ctx.closePath();
+        ctx.fillStyle = this.color;
+        if (selected){
+            ctx.lineWidth = 2
+            ctx.stroke();
+        }
+        ctx.fill();
+    }
+
+    in(x,y){
+        return this.distanceTo(x,y) < this.radius
+    }
+
+    inBounds(x,y,w,h){ // x = 100, this.x = 102, w = 5
+        return this.x >= x && this.x <= x + w &&
+            this.y >= y && this.y <= y + h
+    }
+}
+
+
+class Line extends Drawable { //смочь скопировать в Rectangle и поменять отприсовку
+    constructor(x,y, width, height, color, lineWidth){
+        super()
+        this.x      = x;
+        this.y      = y;
+        this.width  = width;
+        this.height = height;
+        this.color  = color;
+        this.lineWidth  = lineWidth;
+
+
+        this.draw();
+    }
+
+
+    draw(selected){
+        ctx.beginPath();
+        ctx.moveTo(this.x, this.y);
+        ctx.lineTo(this.x + this.width, this.y + this.height);
+        ctx.closePath();
+        ctx.strokeStyle = this.color;
+        ctx.lineWidth   = this.lineWidth
+        ctx.stroke();
+    }
+}
+
+class Rectangle extends Drawable { //смочь скопировать в Rectangle и поменять отрисовку
+    constructor(x,y, width, height, color){
+        super()
+        this.x      = x;
+        this.y      = y;
+        this.width  = width;
+        this.height = height;
+        this.color  = color;
+
+
+        this.draw();
+    }
+
+    draw(selected){
+		ctx.beginPath();
+        ctx.rect(this.x,this.y,this.width,this.height);
+		ctx.closePath();
+		ctx.fillStyle = this.color;
+		if (selected){
+            ctx.lineWidth = 2
+            ctx.stroke();
+        }
+        ctx.fill();
+    }
+    
+	in(x,y){
+        return x > this.x && x < this.x+this.width &&
+			y > this.y && y < this.y+this.height;//условие попадания x,y в прямоугольник
+    }
+}
+//Ellipse по аналогии
+//
+class Ellipse extends Drawable { //смочь скопировать в Ellipse и поменять отрисовку
+    constructor(x,y, width, height, color){
+        super()
+        this.x      = x;
+        this.y      = y;
+        this.width  = width;
+        this.height = height;
+        this.color  = color;
+
+
+        this.draw();
+    }
+	
+    draw(selected){
+        ctx.beginPath()
+        ctx.ellipse(this.x,this.y, Math.abs(this.width), Math.abs(this.height), 0, 0, 2 * Math.PI)
+		ctx.closePath();
+        ctx.fillStyle = this.color;
+		if (selected){
+            ctx.lineWidth = 2
+            ctx.stroke();
+        }
+        ctx.fill();
+    }    
+	
+	in(x,y){
+        return (Math.pow(x-this.x,2)/Math.pow(this.width,2)+
+			Math.pow(y-this.y,2)/Math.pow(this.height,2))<=1; //условие попадания x,y в ellipse
+    }
+}
+
+color.onchange = () => {
+    selection.forEach(c => c.color = color.value)
+    Drawable.drawAll(selection)
+}
+
+document.getElementById('delete').onclick = () =>{
+    Drawable.instances = Drawable.instances.filter(item => !selection.includes(item))
+    selection = []
+    Drawable.drawAll()
+}
+
+
+
+//new Line(0,0,100,100, "red")
+////new Circle(30,30,10, "red")
+
+////canvas.onmousemove = function(e){
+////}
+
+//undo.onclick = function(){
+    //Drawable.instances.pop()
+    ////Drawable.instances = []
+    //Drawable.drawAll()
+//}

File diff suppressed because it is too large
+ 4 - 0
JavaScript HW/HW 19/jquery-3.1.1.min.js


+ 305 - 0
JavaScript HW/HW 19/nb.js

@@ -0,0 +1,305 @@
+/*
+Copyright 2016-100500 Ivan Grynkin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
+to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
+and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+DEALINGS IN THE SOFTWARE. 
+*/
+
+function nbInit(a,b){
+    var root=document, $s=a;
+
+    var dom = null;
+    var closure = null;
+
+    function searchElement(root, selector){
+        if ((selector.indexOf('|dom') === selector.length - 4) && (selector.length > 4)){
+            selector = selector.slice(0,selector.length - 4)
+            dom      = true;
+        }
+        if ((selector.indexOf('|closure') === selector.length - 8) && (selector.length > 8)){
+            selector = selector.slice(0,selector.length - 8)
+            closure  = true;
+        }
+        if (root === document){
+            var items = [root.getElementById(selector)]; 
+        }
+        else {
+            items = root.querySelectorAll("#" + selector); 
+        }
+        items     = items[0]     ? items :  root.querySelectorAll(selector);
+        items     = items.length ? items :  root === document ? root.getElementsByName(selector) : root.querySelectorAll("[name='" + selector + "']"); 
+        items     = items.length ? items :  root.getElementsByClassName(selector); 
+        return items;
+    }
+
+    if (a instanceof HTMLElement){
+        root = a;
+        $s   = b;
+    }
+    else if (typeof a === "string"){
+        root = searchElement(document, a)[0];
+        $s   = b;
+    }
+    if (b instanceof HTMLElement){
+        root = b;
+    }
+    else if (typeof b === "string"){
+        root = searchElement(document, a)[0];
+    }
+    if (typeof $s === "undefined"){
+        $s = {}
+    }
+
+    function nBind(callback, prop, direction){
+        direction = direction || "write";
+        for (var selector in $s){
+            var result = [];
+            selector = prop || selector; //change selector to passed if it
+
+            var items = searchElement(root, selector);
+            for (var i=0,item=items[i];i<items.length;i++,item=items[i]){
+                if (direction == "write" &&  Array.isArray($s[selector]) && (item.children.length == 0 || (items.length == $s[selector].length && items.length > 1))){
+                    if (closure){
+                        callback(item, $s, selector, $s[selector]);
+                    }
+                    else {
+                        callback(item, $s, selector, $s[selector][i]);
+                    }
+                }
+                else {
+                    var res = callback(item, $s, selector);
+                    if (typeof res !== "undefined"){
+                        result.push(res)
+                    }
+                }
+            }
+
+            
+            $s[selector] = result.length ? (result.length == 1 ? result[0] : result) : $s[selector];
+
+            if (prop) return;  //exit if selector passed, no iteration
+        }
+    }
+
+    function recursiveObjectSet(item, value){
+        if (typeof item === 'undefined'){
+            return;
+        }
+        for (var key in value){
+            if (typeof value[key] !== 'object'){
+                item[key] = value[key];
+            }
+            else {
+                recursiveObjectSet(item[key], value[key]);
+            }
+        }
+    }
+
+    function syncToDOM(prop){
+        nBind(function (item, $s, selector, value, key, thisByClass){
+            value = typeof value === 'undefined' ? $s[selector] : value;
+            var keyExists = typeof key !== 'undefined';
+            if (closure){
+                item.nbData = value[0].apply(item, value.slice(1))
+                return;
+            }
+            if ((!item.children.length && !Array.isArray(value) && typeof value === 'object') || thisByClass || dom){ //hash array on single leaf node -> set attrs on the tag
+                recursiveObjectSet(item,value);
+                if (!thisByClass && !dom){
+                    item.nbData = value;
+                }
+                return;
+            }
+            if (keyExists && "value" in item){ //if hash key-value pair. Usable for select > option
+                item.value = key;
+            }
+            if (typeof value === "boolean" && item.type !== 'checkbox'){ //boolean means visibility, except checkbox
+                if (value){
+                    item.style.display = "originalDisplay" in item ? item.originalDisplay : "";
+                }
+                else {
+                    item.originalDisplay = "originalDisplay" in item ? item.originalDisplay : item.style.display;
+                    item.style.display   = "none";
+                }
+                return;
+            }
+            if (item.type === 'radio' && !keyExists){ //radiogroup set
+                if (item.value === value){ //only item with right value to set
+                    item.checked = true;
+                }
+                return;
+            }
+            if (item.type === 'checkbox' && !keyExists){ //checkbox setting by boolean
+                item.checked = !!value;
+                return;
+            }
+            if (item.children.length && typeof value === "object"){ //recursive fill
+                item.copy = item.copy || item.cloneNode(true); //original node
+                item.nbData = value;
+                var originalChildren = item.copy.children;
+                var i = 0;
+                var isArray = Array.isArray(value);      //different logic for array and objects
+                if (!isArray){ // if first key in array find as class name in one of subnodes
+                    var classFound = false;
+                    for (var key in value){
+                        if (item.getElementsByClassName(key).length){
+                            classFound = true;
+                            break;
+                        }
+                    }
+                    if (classFound){
+                        for (var key in value){
+                            var classSubnodes = item.getElementsByClassName(key);
+                            for (var i=0;i<classSubnodes.length;i++){
+                                arguments.callee(classSubnodes[i], $s, selector, value[key]); // recursively fill subnode with that data. No reason to pass a key, because key are class selector, not value for option
+                            }
+                            if (item.classList.contains(key)){
+                                arguments.callee(item, $s, selector, value[key], undefined, true); // recursively fill subnode with that data. No reason to pass a key, because key are class selector, not value for option
+                            }
+                        }
+                        return;
+                    }
+                }
+                item.innerHTML = "";                     //remove sub nodes
+                for (var key in value){ //otherwise iterate over array or object
+                    var newNode = originalChildren[i].cloneNode(true);
+                    item.appendChild(newNode);
+                    if (isArray){
+                        arguments.callee(newNode, $s, selector, value[key]);
+                    }
+                    else {
+                        arguments.callee(newNode, $s, selector, value[key], key);
+                    }
+                    i = (i +1) % originalChildren.length;
+                }
+                return;
+            }
+            if (!keyExists){ //default logic: set text or value to data value
+                item[("value" in item) && item.tagName !== 'LI' ? "value" : "innerText"] = value;
+            }
+            else {
+                item.innerText = value; // do not try to overwrite value on option nodes
+            }
+        },prop, "write");
+    }
+
+    function syncFromDOM(prop){
+        nBind(function(item, $s, selector){
+            if (closure){
+                return item.nbData()
+            }
+            if (item.type === 'radio'){
+                if (item.checked) 
+                    return item.value; 
+                return;
+            }
+            if (item.type === 'checkbox'){
+                return item.checked;
+            }
+            if (item.tagName === 'SELECT'){
+                return item.value;
+            }
+            if ("nbData" in item){
+                var value = item.nbData;
+                var isArray = Array.isArray(value);      //different logic for array and objects
+                if (item.children.length && typeof value === "object"){ //recursive fill
+                    if (!isArray){ // if first key in array find as class name in one of subnodes
+                        var classFound = false;
+                        for (var key in value){
+                            if (item.getElementsByClassName(key).length){
+                                classFound = true;
+                                break;
+                            }
+                        }
+                        if (classFound){
+                            for (var key in value){
+                                var classSubnodes = item.getElementsByClassName(key);
+                                for (var i=0;i<classSubnodes.length;i++){
+                                    value[key] = arguments.callee(classSubnodes[i], $s, selector); // recursively fill subnode with that data. No reason to pass a key, because key are class selector, not value for option
+                                }
+                            }
+                            return value;
+                        }
+                    }
+                    else{
+                        value.length = 0;
+                        for (var key=0;key<item.children.length;key++){ //otherwise iterate over array or object
+                            value[key] = arguments.callee(item.children[key], $s, selector);
+                        }
+                        return value;
+                    }
+                    //else {
+                        //for (var key in value){
+                            //value[key] = arguments.callee(item.children[key], $s, selector);
+                        //}
+                    //}
+                }
+                if (!isArray && typeof value === 'object' && item.children.length === 0){ //hash array on single leaf node -> set attrs on the tag
+                    for (var key in value){
+                        value[key] = item[key];
+                    }
+                    return value;
+                }
+                if (!isArray && typeof value === 'object'){ //hash array on single leaf node -> set attrs on the tag
+                    value = {};
+                    for (var i=0;i<item.children.length;i++){
+                        var childItem = item.children[i];
+                        value[childItem.value] = childItem.innerText;
+                    }
+                    return value;
+                }
+            }
+            if ("value" in item){
+                return item.value;
+            }
+            return item.innerText; 
+        },prop, "read");
+    }
+
+    syncToDOM();
+
+    var scopeProxy = new Proxy($s,{
+        get(target, prop){
+            //if (!(prop in target) && (document.getElementById(prop) || 
+                                      //document.querySelectorAll(prop).length || 
+                                      //document.getElementsByName(prop).length ||
+                                      //document.getElementsByClassName(prop).length)){
+                target[prop] = null;
+            //}
+            syncFromDOM(prop);
+            dom = null;
+            closure = null;
+            return target[prop];
+        },
+        set(target, prop, value){
+            //syncFromDOM();
+            target[prop] = value
+            syncToDOM(prop);
+            dom = null;
+            closure = null;
+            return true;
+        },
+    })
+
+    return scopeProxy;
+}
+
+function nbGetData(el){
+    while (!('nbData' in el)){
+        if (el.parentElement){
+            el = el.parentElement;
+        }
+        else {
+            return null;
+        }
+    }
+    return el.nbData;
+}

File diff suppressed because it is too large
+ 6 - 0
JavaScript HW/HW 19/papaparse.min.js


+ 272 - 0
JavaScript HW/HW 2/Homework2.html

@@ -0,0 +1,272 @@
+<!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>
+            // --------------assign: evaluation
+
+            // var a = 5;
+            // var b, c;
+
+            // b = a * 5;
+            // b = c = b / 2;
+
+            // --------------semicolon: error
+
+            // if (a = 5) {
+            //     concole.log("Ты молодец")
+            // } else {
+            //     concole.log("Ты не молодец")
+            // }
+
+            // ----------------semicolon: mistake
+
+            // b = a * 5; -2;
+            // c = b - 2; +5;
+            // console.log(c, b);
+
+            // ----------------Number: age
+
+            // let aGe = prompt("Введите свой возраст:");
+            // alert(
+            //     2022 - aGe + " Ваш год рождения, наверное, ну плюс минус год"
+            // );
+
+            // ----------------Number: temperature
+
+            // let temperatureInCelsius = prompt('Введите температуру которую хотите конвертировать в Фарангейты:');
+            // let temperatureInFahrenheit = (temperatureInCelsius * (9/5)) + 32;
+            // alert(temperatureInFahrenheit + " градусов по Фарангейту");
+
+            // ----------------Number: divide
+
+            // let integerDivision1 = prompt("Введите первое число");
+            // let integerDivision2 = prompt("Введите второе число");
+            // let divisionOfTwoNumbers = Math.floor(integerDivision1 / integerDivision2);
+
+            // alert(divisionOfTwoNumbers);
+
+            // ----------------Number: odd  Нужно доднлать
+
+            // let numberFromUser = prompt("Введите ваше число;");
+            // if (numberFromUser == +numberFromUser) {
+            //     if (numberFromUser % 2 == 0) {
+            //         alert("Ты молодец, ввёл чётное число!");
+            //     } else {
+            //         alert("Ты ввёл нечётное число!")
+            //     }
+
+            // } else {
+            //     alert("Ты не молодец, вывожу тебе ошибку!")
+            // }
+
+            // ------------------String: greeting
+
+            // let userName = prompt("Как вас зовут?")
+            // alert(userName + ", приветствую вас!")
+
+            // ------------------String: lexics
+
+            // let userText = prompt('Введите какой-нибудь текст:');
+            // let includesUserText = userText.includes('какой-нибудь текст');
+            // if (includesUserText) {
+            //     alert ("ха-ха-ха, молодец шаришь!")
+            // } else {
+            //     alert ("Обнови страницу и введи какой-нибудь текст!")
+            // }
+
+            // -------------------confirm
+
+            // let userСhoice = confirm("Выбери красную либо синюю таблетку! Красная - Отмена, синяя - ОК")
+            // if(userСhoice != true) {
+            //     alert('Ты хреновый программист!')
+            // } else {
+            //     alert('Ты сможешь научится писать код сложнее IF ELSE')
+            // }
+
+            // -------------------Boolean
+
+            // let userAge = confirm('Вам больше 18?');
+            // let question = confirm("Да или нет?");
+            // let userGender = confirm("Вы женщина?");
+
+            // -------------------Boolean: if
+
+            // if (userGender) {
+            //     let woman = 'Вы женщина получается!';
+            //     alert (woman);
+            // } else {
+            //     let male = 'Вы не женщина. Тогда скорее всего мужчина';
+            //     alert (male);
+            // }
+
+            // --------------------Array: real
+
+            // --------------------Array: booleans
+
+            // let questionsToTheUsers = [userAge, question, userGender];
+
+            // --------------------Array: plus
+
+            // let arrayOfNumbers = [1, 2, 3, 4, 5];
+            // arrayOfNumbers[2] = arrayOfNumbers[3] + arrayOfNumbers[4];
+            // console.log(arrayOfNumbers);
+
+            // --------------------Array: plus string
+
+            // let arrayOfString = ["one", "two", "three", "four", "five"];
+            // arrayOfString[2] = arrayOfString[0] + arrayOfString[1] + arrayOfString[3];
+            // console.log(arrayOfString);
+
+            // --------------------Object: real
+
+            // let object = {
+            //     name: "Bitcoin",
+            //     price: "29538 dollars for 1 bitcoin",
+            //     capitalization: "685 million"
+            // };
+
+            // --------------------Object: change
+
+            // let object = {
+            //     name: "Bitcoin",
+            //     price: "29538 dollars for 1 bitcoin",
+            //     capitalization: "685 million"
+            // };
+
+            // object.price = "30000 dollars for 1 bitcoin";
+            // object["capitalization"] = "700 million dollars";
+
+            // --------------------Comparison if
+            var age = +prompt("Сколько вам лет?", "");
+            if (age < 0) {
+                alert("ещё не родился");
+            } else {
+                if (age <= 18) {
+                    alert("школьник");
+                } else {
+                    if (age <= 30) {
+                        alert("молодеж");
+                    } else {
+                        if (age <= 45) {
+                            alert("зрелость");
+                        } else {
+                            if (age <= 60) {
+                                alert("закат");
+                            } else {
+                                if (age > 60) {
+                                    alert("как пенсия?");
+                                } else {
+                                    alert("то ли киборг, то ли KERNESS");
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            // --------------------Comparison: sizes
+
+            // let clothingSizeIn = prompt(
+            //     "Введите название страны, в размер которой вы хотите конвертировать свой размер. На выбор есть: Европа, Великобритания, США"
+            // );
+            // let userSize = prompt(
+            //     "Введите свой размер обуви, который хотите конверитировать. От 40-45"
+            // );
+
+            // let _40 = userSize.includes("40");
+            // let _41 = userSize.includes("41");
+            // let _42 = userSize.includes("42");
+            // let _43 = userSize.includes("43");
+            // let _44 = userSize.includes("44");
+            // let _45 = userSize.includes("45");
+
+            // let europe = clothingSizeIn.includes("Европа");
+            // let british = clothingSizeIn.includes("Великобритания");
+            // let usa = clothingSizeIn.includes("США");
+
+            // if (europe) {
+            //     if (_40) {
+            //         alert("41.5");
+            //     } else if (_41 == true) {
+            //         alert("42.5");
+            //     } else if (_42 == true) {
+            //         alert("43.5");
+            //     } else if (_43 == true) {
+            //         alert("44.5");
+            //     } else if (_44 == true) {
+            //         alert("45.5");
+            //     } else if (_45 == true) {
+            //         alert("46.5");
+            //     }
+            // } else {
+            // if (british) {
+            //     if (_40) {
+            //         alert("7.5");
+            //     } else if (_41) {
+            //         alert("8.5");
+            //     } else if (_42) {
+            //         alert("9");
+            //     } else if (_43) {
+            //         alert("9.5");
+            //     } else if (_44) {
+            //         alert("10.5");
+            //     } else if (_45) {
+            //         alert("11.5");
+            //     }
+            // } else {
+            //         if (usa) {
+            //             if (_40) {
+            //             alert("8");
+            //         } else if (_41) {
+            //             alert("9");
+            //         } else if (_42) {
+            //             alert("9.5");
+            //         } else if (_43) {
+            //             alert("10");
+            //         } else if (_44) {
+            //             alert("11");
+            //         } else if (_45) {
+            //             alert("12");
+            //         }
+            //         }
+            //     }
+            // }
+
+            // --------------------Comparison: object
+            // --------------------Ternary
+
+            // let genderUser = confirm("Вы мужчина?") ? "Я конечно вам не особо верю, но вы скорее всего мужчина!" : "Ну тогда вы женщина!";
+            // alert(genderUser);
+
+            // --------------------Синий пояс Number: flats
+
+            let numberApartments = prompt("Введите номер квартиры");
+            let numberOfFloorsInTheHouse = prompt(
+                "Введите количество этажей в доме"
+            );
+            let numberOfApartmentsPerFloor = prompt(
+                "Введите количество квартир на этаже"
+            );
+            let apartmentsInTheHallway =
+                numberOfFloorsInTheHouse * numberOfApartmentsPerFloor;
+            let entranceOfThisApartmentNumber =
+                (numberApartments - 1) / apartmentsInTheHallway + 1;
+            let floorOfTheApartmentByItsNumber =
+                ((numberApartments - 1) % apartmentsInTheHallway) /
+                    numberOfApartmentsPerFloor +
+                1;
+            alert(
+                Math.floor(entranceOfThisApartmentNumber) +
+                    " подьезд" +
+                    " " +
+                    Math.floor(floorOfTheApartmentByItsNumber) +
+                    " этаж"
+            );
+        </script>
+    </body>
+</html>

+ 378 - 0
JavaScript HW/HW 3/index.html

@@ -0,0 +1,378 @@
+<!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>Homework3</title>
+    </head>
+    <body>
+        <script>
+            let taskName = prompt("Введите название задания");
+            switch (taskName) {
+                case "switch: sizes":
+                    let clothingSizeIn = prompt(
+                        "Введите название страны, в размер которой вы хотите конвертировать свой размер. На выбор есть: Европа, Великобритания, США"
+                    );
+                    let userSize = prompt(
+                        "Введите свой размер обуви, который хотите конверитировать. От 40-45"
+                    );
+                    switch (clothingSizeIn) {
+                        case "США":
+                            switch (userSize) {
+                                case "40":
+                                    alert("8");
+                                    break;
+                                case "41":
+                                    alert("9");
+                                    break;
+                                case "42":
+                                    alert("9.5");
+                                    break;
+                                case "43":
+                                    alert("10");
+                                    break;
+                                case "44":
+                                    alert("11");
+                                    break;
+                                case "45":
+                                    alert("12");
+                                    break;
+                                default:
+                                    alert(
+                                        "Вы ввели неправильную информацию, обновите страницу и попробуйте ещё раз"
+                                    );
+                            }
+                            break;
+                        case "Великобритания":
+                            switch (userSize) {
+                                case "40":
+                                    alert("7.5");
+                                    break;
+                                case "41":
+                                    alert("8.5");
+                                    break;
+                                case "42":
+                                    alert("9");
+                                    break;
+                                case "43":
+                                    alert("9.5");
+                                    break;
+                                case "44":
+                                    alert("10.5");
+                                    break;
+                                case "45":
+                                    alert("11");
+                                    break;
+                                default:
+                                    alert(
+                                        "Вы ввели неправильную информацию, обновите страницу и попробуйте ещё раз"
+                                    );
+                            }
+                            break;
+                        case "Европа":
+                            switch (userSize) {
+                                case "40":
+                                    alert("41.5");
+                                    break;
+                                case "41":
+                                    alert("42.5");
+                                    break;
+                                case "42":
+                                    alert("43.5");
+                                    break;
+                                case "43":
+                                    alert("44.5");
+                                    break;
+                                case "44":
+                                    alert("45.5");
+                                    break;
+                                case "45":
+                                    alert("46.5");
+                                    break;
+                                default:
+                                    alert(
+                                        "Вы ввели неправильную информацию, обновите страницу и попробуйте ещё раз"
+                                    );
+                            }
+                            break;
+                    }
+                    break;
+                case "switch: if":
+                    let color = prompt("Введите цвет", "");
+                    if (color == "red") {
+                        document.write(
+                            "<div style='background-color: red;'>красный</div>",
+                            "<div style='background-color: black; color: white;'>черный</div>"
+                        );
+                    } else if (color == "black") {
+                        document.write(
+                            "<div style='background-color: black; color: white;'>черный</div>"
+                        );
+                    } else if (color == "blue") {
+                        document.write(
+                            "<div style='background-color: blue;'>синий</div>",
+                            "<div style='background-color: green;'>зеленый</div>"
+                        );
+                    } else if (color == "green") {
+                        document.write(
+                            "<div style='background-color: green;'>зеленый</div>"
+                        );
+                    } else {
+                        document.write(
+                            "<div style='background-color: gray;'>Я не понял</div>"
+                        );
+                    }
+                    break;
+                case "prompt: or":
+                    let aGe = +prompt("Введите свой возраст:");
+                    if (aGe) {
+                        alert("Вы родились в " + (2022 - aGe));
+                    } else if (aGe == null || aGe == "") {
+                        alert("Ошибка");
+                    } else {
+                        alert("Ошибка");
+                    }
+                    break;
+                case "or this days":
+                    let shoping1 = confirm("Шопинг?");
+                    alert(shoping1 || "Ты бяка!");
+                    break;
+                case "confirm: if this days":
+                    let shoping = confirm("Шопинг?");
+                    if (shoping) {
+                        alert("Let's go!");
+                    } else {
+                        alert("Ты бяка!");
+                    }
+                    break;
+                case "triple prompt":
+                    let userName1 = prompt("Введите ваше имя");
+                    let userSurname1 = prompt("Введите вашу фамилию");
+                    let userPatronymic1 = prompt("Введите ваше отчество");
+                    alert(
+                        userSurname1 + " " + userName1 + " " + userPatronymic1
+                    );
+                    break;
+                case "default: or":
+                    let userName2 = prompt("Введите ваше имя") || "Иван";
+                    let userSurname2 =
+                        prompt("Введите вашу фамилию") || "Иванов";
+                    let userPatronymic2 =
+                        prompt("Введите ваше отчество") || "Иванович";
+                    alert(
+                        userSurname2 + " " + userName2 + " " + userPatronymic2
+                    );
+                    break;
+                case "default: if":
+                    let userName3 = prompt("Введите ваше имя");
+                    let userSurname3 = prompt("Введите вашу фамилию");
+                    let userPatronymic3 = prompt("Введите ваше отчество");
+                    if (userName3 == null || " ") {
+                        userName3 = "Иван";
+                    }
+                    if (userSurname3 == null || " ") {
+                        userSurname3 = "Иванов";
+                    }
+                    if (userPatronymic3 == null || " ") {
+                        userPatronymic3 = "Иванович";
+                    }
+
+                    alert(
+                        userSurname3 + " " + userName3 + " " + userPatronymic3
+                    );
+                    break;
+                case "login and password":
+                    let login = prompt("Введите логин");
+                    if (login === "admin") {
+                        let password = prompt("Введите пароль");
+                        if (password === "qwerty") {
+                            alert("Поздравляю!");
+                        } else {
+                            alert("Ошибка");
+                        }
+                    } else {
+                        alert("Ошибка");
+                    }
+                    break;
+                case "currency calc":
+                    let userChoice1 = prompt(
+                        "В какую валюту хотите конвертировать? На выбор USD и EUR"
+                    );
+                    let UAH1 = +prompt("Введите вашу суму в гривнах");
+                    let USD1 = 29.2;
+                    let EUR1 = 31.4;
+                    switch (userChoice1) {
+                        case "USD":
+                            alert(UAH1 / USD1);
+                            break;
+                        case "EUR":
+                            alert(UAH1 / EUR1);
+                            break;
+                    }
+                    break;
+                case "currency calc: improved":
+                    let userChoice2 = prompt(
+                        "В какую валюту хотите конвертировать? На выбор USD и EUR"
+                    ).toLowerCase();
+                    let UAH2 = prompt("Введите вашу суму в гривнах");
+                    let usd = 29.2;
+                    let eur = 31.4;
+                    switch (userChoice2) {
+                        case "usd":
+                            alert(UAH2 / usd);
+                            break;
+                        case "eur":
+                            alert(UAH2 / eur);
+                            break;
+                    }
+                    break;
+                case "currency calc: two rates":
+                    let userChoice4 = prompt(
+                        "В какую валюту хотите конвертировать? На выбор USD и EUR"
+                    ).toLowerCase();
+                    let UAH6 = prompt("Введите вашу суму в гривнах");
+
+                    let usdPurchase1 = 29.2;
+                    let usdSale1 = 29.5;
+                    let eurPurchase1 = 31.4;
+                    let eurSale1 = 32.2;
+
+                    switch (userChoice4) {
+                        case "usd":
+                            let exchangeRateSelectionDollar = confirm(
+                                "Курс продажа или покупка? ок - покупка, Отмена - продажа"
+                            )
+                                ? UAH6 / usdPurchase1
+                                : UAH6 / usdSale1;
+                            alert(exchangeRateSelectionDollar);
+                            break;
+                        case "eur":
+                            let exchangeRateSelectionEuro = confirm(
+                                "Курс продажа или покупка? ок - покупка, Отмена - продажа"
+                            )
+                                ? UAH / eurPurchase1
+                                : UAH / eurSale1;
+                            alert(exchangeRateSelectionEuro);
+                            break;
+                    }
+                    break;
+                case "currency calc: if":
+                    let userChoice = prompt(
+                        "В какую валюту хотите конвертировать? На выбор USD и EUR"
+                    ).toLowerCase();
+                    let UAH = prompt("Введите вашу суму в гривнах");
+
+                    let usdPurchase = 29.2;
+                    let usdSale = 29.5;
+                    let eurPurchase = 31.4;
+                    let eurSale = 32.2;
+
+                    if (userChoice === "usd") {
+                        let exchangeRateSelectionDollar = confirm(
+                            "Курс продажа или покупка? ок - покупка, Отмена - продажа"
+                        )
+                            ? UAH / usdPurchase
+                            : UAH / usdSale;
+                        alert(exchangeRateSelectionDollar);
+                    } else if (userChoice === "eur") {
+                        let exchangeRateSelectionEuro = confirm(
+                            "Курс продажа или покупка? ок - покупка, Отмена - продажа"
+                        )
+                            ? UAH / eurPurchase
+                            : UAH / eurSale;
+                        alert(exchangeRateSelectionEuro);
+                    } else {
+                        alert("Ошибка");
+                    }
+                    break;
+                case "scissors":
+                    let userOption = prompt(
+                        "Введите камень, ножницы либо бумага"
+                    );
+                    if (userOption === "ножницы") {
+                        userOption = 1;
+                    } else if (userOption === "камень") {
+                        userOption = 2;
+                    } else if (userOption === "бумага") {
+                        userOption = 3;
+                    } else {
+                        alert("");
+                    }
+
+                    let randomТumber = Math.random() * 3;
+                    let randomTumberRound = Math.ceil(Math.round(randomТumber));
+
+                    if (randomTumberRound <= 1) {
+                        alert("Компьютер показывает Ножницы");
+                    } else if (randomTumberRound === 2) {
+                        alert("Компьютер показывает Камень");
+                    } else if (randomTumberRound === 3) {
+                        alert("Компьютер показывает Бумагу");
+                    } else {
+                        alert("");
+                    }
+
+                    if (randomTumberRound === 3 && userOption === 1) {
+                        alert("Поздравляю, вы выиграли!");
+                    } else if (
+                        userOption < randomTumberRound ||
+                        (randomTumberRound == 1 && userOption == 3)
+                    ) {
+                        alert("Выиграл компьютер!");
+                    } else if (userOption > randomTumberRound) {
+                        alert("Поздравляю, вы выиграли!");
+                    } else if (
+                        userOption === 1 &&
+                        (randomTumberRound === 1 || randomTumberRound === 0)
+                    ) {
+                        alert("Ничья!");
+                    }
+                    break;
+                case "Задание на синий пояс":
+                    let userCurrencySelection1 = prompt(
+                        "В какую валюту хотите конвертировать? На выбор USD и EUR"
+                    ).toLowerCase();
+                    let howManyHryvnias1 = prompt(
+                        "Введите сумму какую хотите конверировать в валюту"
+                    );
+                    let ratios = {
+                        usd: "25.6",
+                        eur: "29",
+                    };
+
+                    if (userCurrencySelection1 === "usd") {
+                        alert(howManyHryvnias1 / ratios["usd"]);
+                    } else if (userCurrencySelection1 === "eur") {
+                        alert(howManyHryvnias1 / ratios["eur"]);
+                    } else {
+                        alert("Ошибка");
+                    }
+                    break;
+                case "real data":
+                    let userCurrencySelection = prompt(
+                        "В какую валюту хотите конвертировать? На выбор USD и EUR"
+                    ).toLowerCase();
+                    let howManyHryvnias = prompt(
+                        "Введите сумму какую хотите конверировать в валюту"
+                    );
+                    if (userCurrencySelection === "usd") {
+                        fetch("https://open.er-api.com/v6/latest/USD")
+                            .then((res) => res.json())
+                            .then((data) => {
+                                alert(howManyHryvnias / data.rates.UAH);
+                            });
+                    } else if (userCurrencySelection === "eur") {
+                        fetch("https://open.er-api.com/v6/latest/EUR")
+                            .then((res) => res.json())
+                            .then((data) => {
+                                alert(howManyHryvnias / data.rates.UAH);
+                            });
+                    } else {
+                        alert("Ошибка");
+                    }
+                    break;
+            }
+        </script>
+    </body>
+</html>

+ 376 - 0
JavaScript HW/HW 4/homework4.html

@@ -0,0 +1,376 @@
+<!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>Homework 4</title>
+    </head>
+    <body>
+        <table width="100%" border="1" cellspacing="0" cellpadding="4">
+            <caption>
+                Таблица Пифагора
+            </caption>
+            <tr>
+                <th></th>
+                <th>1</th>
+                <th>2</th>
+                <th>3</th>
+                <th>4</th>
+                <th>5</th>
+                <th>6</th>
+                <th>7</th>
+                <th>8</th>
+                <th>9</th>
+                <th>10</th>
+            </tr>
+        </table>
+        <script>
+            // -------------------------html tree
+            // let body = {
+            //     tagName: "body",
+            //     subTags: [
+            //         {
+            //             tagName: "div",
+            //             subTags: [
+            //                 {
+            //                     tagName: "span",
+            //                     text: "Enter a data please:",
+            //                 },
+            //                 {
+            //                     tagName: "br",
+            //                 },
+            //                 {
+            //                     tagName: "input",
+            //                     attrs: {
+            //                         type: "text",
+            //                         id: "name",
+            //                     },
+            //                 },
+            //                 {
+            //                     tagName: "input",
+            //                     attrs: {
+            //                         type: "text",
+            //                         id: "surname",
+            //                     },
+            //                 },
+            //             ],
+            //         },
+            //         {
+            //             tagName: "div",
+            //             subTags: [
+            //                 {
+            //                     tagName: "buttom",
+            //                     text: "OK",
+            //                     attrs: {
+            //                         id: "ok",
+            //                     },
+            //                 },
+            //                 {
+            //                     tagName: "buttom",
+            //                     text: "Cancel",
+            //                     attrs: {
+            //                         id: "cancel",
+            //                     },
+            //                 },
+            //             ],
+            //         },
+            //     ],
+            // };
+
+            // console.log(body.subTags[1].subTags[1].text);
+            // console.log(body.subTags[0].subTags[3].attrs.id);
+
+            // -------------------------declarative fields
+
+            // var notebook = {
+            //     brand: prompt('Какая модель ноутбука?'),
+            //     type:  prompt("Какая модель нотбука?"),
+            //     model: prompt("Введите серийный номер"),
+            //     ram: prompt("Введите оперативную память"),
+            //     size: +prompt("Сколько дюймов экран?"),
+            //     weight: +prompt("какой вес вашей модели?"),
+            //     resolution: {
+            //             width: prompt("Какая ширина экрана?"),
+            //             height: prompt("Какая высота экрана?"),
+            //      },
+            // };
+
+            // var phone = {
+            //     brand: prompt("Введите производителя телефона"),
+            //     model: prompt("введите модель телефона"),
+            //     ram: +prompt("Сколько оперативной памяти в вашем телефоне?"),
+            //     color: prompt("Какой цвет вашего телефона?"),
+            // };
+
+            // var person = {
+            //     name: prompt("Введите имя"),
+            //     surname: prompt("Введите фамилию"),
+            //     married: confirm("Вы замужем либо женаты?"),
+            // };
+
+            // -------------------------object links
+            
+            // var person = {
+            //     name: prompt("Введите имя"),
+            //     surname: prompt("Введите фамилию"),
+            //     married: confirm("Вы замужем либо женаты?"),
+            //     smartphone: phone,
+            //     laptop: notebook,
+            // };
+
+            // var notebook = {
+            //     brand: prompt("Какая модель ноутбука?"),
+            //     type: prompt("Какая модель нотбука?"),
+            //     model: prompt("Введите серийный номер"),
+            //     ram: prompt("Введите оперативную память"),
+            //     size: +prompt("Сколько дюймов экран?"),
+            //     weight: +prompt("какой вес вашей модели?"),
+            //     resolution: {
+            //         width: prompt("Какая ширина экрана?"),
+            //         height: prompt("Какая высота экрана?"),
+            //     },
+            //     owner: person,
+            // };
+
+            // var phone = {
+            //     brand: prompt("Введите производителя телефона"),
+            //     model: prompt("введите модель телефона"),
+            //     ram: +prompt("Сколько оперативной памяти в вашем телефоне?"),
+            //     color: prompt("Какой цвет вашего телефона?"),
+            //     owner: person,
+            // };
+
+            // -------------------------imperative array fill 3
+
+            // let arr = [prompt("Введите элемент 1"), prompt("Введите элемент 2"), prompt("Введите элемент 3"),];
+            // console.log(arr);
+
+            // -------------------------while confirm
+
+            // let cycleWhile = confirm();
+            // while (!cycleWhile) {
+            //     cycleWhile = confirm();
+            // }
+
+            // -------------------------array fill
+
+            // let emptyArray = [];
+            // let emptyArray2 = [];
+            // while (emptyArray) {
+            //     emptyArray2.push(emptyArray = prompt("Введите что-то"));
+            //     if (emptyArray == null || false) {
+            //         emptyArray2.splice(-1,1);
+            //       break;
+            //     }
+            // }
+
+            // -------------------------array fill nopush
+
+            // let emptyArrayNoPush = [];
+            // for (let i = 0; i != null; i++) {
+            //     emptyArrayNoPush[i] = prompt("Введите что-то");
+            //     if (emptyArrayNoPush[i] === null){
+            //         emptyArrayNoPush.splice(-1,1);
+            //         break;
+            //     }
+            // }
+
+            // -------------------------infinite probability
+
+            // let randomNumber = Math.random();
+            // let numberOfIterations = 0;
+            // while (randomNumber) {
+            //     randomNumber = Math.random();
+            //     numberOfIterations += 1;
+            //     if (randomNumber > 0.9) {
+            //         alert(randomNumber);
+            //         alert("Количество итераций: " + numberOfIterations)
+            //         break;
+            //     }
+            // }
+
+            // -------------------------empty loop
+
+            // do {
+            // } while (prompt() == null);
+
+            // -------------------------progression sum
+
+            // for (var arr = [1]; arr.push((arr[arr.length - 1]) + 3); (arr[arr.length - 1]) < 20) {
+            //     if ((arr[arr.length - 1]) <= 20) {
+            //     } else {
+            //         arr.splice(-1,1);
+            //         let result = arr.reduce(function (sum, elem) {
+            //             return sum + elem;
+            //         }, 0);
+
+            //         console.log(result);
+            //         break;
+            //     }
+            // }
+
+            // -------------------------chess one line
+
+            // let lineWithResult = " ";
+            // for(i = 0; i < 10; i++) {
+
+            //         lineWithResult = lineWithResult + " ";
+            //      if(i % 2 === 1) {
+            //         lineWithResult = lineWithResult + "#";
+            //     }
+            // } console.log (lineWithResult);
+
+            // -------------------------numbers
+
+            // var c = "";
+            // for (let a = 0; a < 10; a++) {
+            //     for (b = 0; b < 10; b++) {
+            //         c = c + b;
+            //         if (b == 9) {
+            //             c = c + "\n";
+            //         }
+            //     }
+            // }console.log(c);
+
+            // -------------------------chess
+
+            // var latticeOrDot = "";
+            // for (let chessBoard = 0; chessBoard >= 0; chessBoard++) {
+            //     for (i = 0; i < 13; i++) {
+            //         if (i == 12) {
+            //         latticeOrDot = latticeOrDot + "\n";
+            //         } else if (i % 2) {
+            //             latticeOrDot = latticeOrDot + "#";
+            //         } else {
+            //             latticeOrDot = latticeOrDot + ".";
+            //         }
+            //     }
+            //     for (i = 0; i < 13; i++) {
+            //         if (i == 12) {
+            //         latticeOrDot = latticeOrDot + "\n";
+            //         } else if (i % 2) {
+            //             latticeOrDot = latticeOrDot + ".";
+            //         } else {
+            //             latticeOrDot = latticeOrDot + "#";
+            //         }
+            //     }
+            //     if (chessBoard == 4) {
+            //         console.log(latticeOrDot);
+            //     }
+            // }
+
+            // -------------------------cubes
+
+            // for (let indexСubes = []; ; ) {
+            //     let indexToPower = indexСubes.length;
+            //     let exponentiation = indexToPower ** 3;
+            //     indexСubes.push(exponentiation);
+            //     if (indexСubes.length == 20) {
+            //         console.log(indexСubes);
+            //         break;
+            //     }
+            // }
+
+            // -------------------------multiply table
+
+            let arr = Array(10);
+            for (let i = 1; i < 10; i++) {
+                arr[i] = [...Array(10)].map((arr, j) => i * j);
+            }
+            console.log(arr[6][5]);
+
+            // -------------------------matrix to html table
+
+            var string = "";
+            for (var i = 1; i <= 10; i++) {
+                string += "<tr>";
+                string += "<td><b>" + i + "</b></td>";
+                for (var j = 1; j <= 10; j++)
+                    string += "<td>" + i * j + "</td>";
+                string += "</tr>";
+            }
+            document.querySelector("table").innerHTML += string;
+
+            // -------------------------Задание на синий пояс: Треугольник
+            // debugger;
+            // var str = "";
+            // for (a = 0; a < 10; a++) {
+            //     for (let i = 0; i < 12; i++) {
+            //         if (i == "11") {
+            //             str = str + "\n";
+            //         } else if (i === 5) {
+            //             str = str + "#";
+            //         } else {
+            //             str = str + ".";
+            //         }
+            //     }
+            //     for (let i = 0; i < 12; i++) {
+            //         if (i == "11") {
+            //             str = str + "\n";
+            //         } else if (i === 4 || i === 5 || i === 6) {
+            //             str = str + "#";
+            //         } else {
+            //             str = str + ".";
+            //         }
+            //     }
+            //     for (let i = 0; i < 12; i++) {
+            //         if (i == "11") {
+            //             str = str + "\n";
+            //         } else if (
+            //             i === 3 ||
+            //             i === 4 ||
+            //             i === 5 ||
+            //             i === 6 ||
+            //             i === 7
+            //         ) {
+            //             str = str + "#";
+            //         } else {
+            //             str = str + ".";
+            //         }
+            //     }
+            //     for (let i = 0; i < 12; i++) {
+            //         if (i == "11") {
+            //             str = str + "\n";
+            //         } else if (
+            //             i === 0 ||
+            //             i === 1 ||
+            //             i === 9 ||
+            //             i === 10
+            //         ) {
+            //             str = str + ".";
+            //         } else {
+            //             str = str + "#";
+            //         }
+            //     }
+            //     for (let i = 0; i < 12; i++) {
+            //         if (i == "11") {
+            //             str = str + "\n";
+            //         } else if (
+            //             i === 0 ||
+            //             i === 10
+            //         ) {
+            //             str = str + ".";
+            //         } else {
+            //             str = str + "#";
+            //         }
+            //     }
+            //     for (let i = 0; i < 11; i++) {
+            //         str = str + "#";
+            //     }
+            //     if (a == 0) {
+            //         console.log(str);
+            //     }
+            // }
+
+            // -------------------------Задание на черный пояс: Электронная гадалка
+
+            // let predictArray = prompt("Введите 0 или 1");;
+            // let history = [1, 1, 1, 1];
+            // history.push(predictArray);
+            // history.shift();
+            // console.log(history);
+            // дальше я не смог придумать что делать((((
+        </script>
+    </body>
+</html>

+ 405 - 0
JavaScript HW/HW 5/index.html

@@ -0,0 +1,405 @@
+<!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>
+            // -------------------3 persons
+
+            // let a = {
+            //     name: "Andrey",
+            //     surname: "Petroff"
+            // }
+
+            // let b = {
+            //     name: "Anton",
+            //     surname: "Nikitin"
+            // }
+
+            // let c = {
+            //     name: "Artem",
+            //     surname: "Kozyr"
+            // }
+
+            // -------------------different fields
+
+            // let a = {
+            //     name: "Andrey,
+            //     surname: "Petroff",
+            //     age: "100",
+            //     fathername: "Akakiyovich",
+            //     sex: "Male"
+            // }
+
+            // let b = {
+            //     name: "Anton",
+            //     surname: "Nikitin",
+            //     age: "23",
+            //     fathername: "Ronaldovich",
+
+            // }
+
+            // let c = {
+            //     name: "Artem",
+            //     surname: "Kozyr",
+            //     fathername: "Messiyovich"
+            // }
+
+            // -------------------fields check
+
+            // let a = {
+            //     name: "Andrey",
+            //     surname: "Petroff",
+            //     sex: "Male",
+            //     age: "100",
+            //     fathername: "Akakiyovich",
+            // };
+
+            // let b = {
+            //     name: "Anton",
+            //     surname: "Nikitin",
+            //     age: "23",
+            //     fathername: "Ronaldovich",
+            // };
+
+            // let c = {
+            //     name: "Artem",
+            //     surname: "Kozyr",
+            //     fathername: "Messiyovich",
+            // };
+
+            // if  ("age" in a) {
+            //     alert(a.age);
+            // } if ("sex" in a){
+            //     alert(a.sex);
+            // } if ("age" in b) {
+            //     alert(b.age);
+            // } if ("sex" in b){
+            //     alert(b.sex);
+            // } if  ("age" in c) {
+            //     alert(c.age);
+            // } if ("sex" in c){
+            //     alert(c.sex);
+            // }
+
+            // -------------------array of persons
+
+            // var persons = [
+            //     (a = {
+            //         name: "Andrey",
+            //         surname: "Petroff",
+            //         sex: "Male",
+            //         age: "100",
+            //         fathername: "Akakiyovich",
+            //     }),
+            //     (b = {
+            //         name: "Anton",
+            //         surname: "Nikitin",
+            //         age: "23",
+            //         fathername: "Ronaldovich",
+            //     }),
+            //     (c = {
+            //         name: "Artem",
+            //         surname: "Kozyr",
+            //         fathername: "Messiyovich",
+            //     }),
+            //     (d = {
+            //         "name": "Illia",
+            //         "surname": "Kozyr",
+            //         "fathername": "Sergeevych",
+            //     }),
+            // ];
+
+            // -------------------loop of persons
+
+            // var persons = [
+            //     (a = {
+            //         name: "Andrey",
+            //         surname: "Petroff",
+            //         sex: "Male",
+            //         age: "100",
+            //         fathername: "Akakiyovich",
+            //     }),
+            //     (b = {
+            //         name: "Anton",
+            //         surname: "Nikitin",
+            //         age: "23",
+            //         fathername: "Ronaldovich",
+            //     }),
+            //     (c = {
+            //         name: "Artem",
+            //         surname: "Kozyr",
+            //         fathername: "Messiyovich",
+            //     }),
+            //     (d = {
+            //         "name": "Illia",
+            //         "surname": "Kozyr",
+            //         "fathername": "Sergeevych",
+            //     }),
+            // ];
+
+            // var index;
+            // for (index = 0; index < persons.length; ++index) {
+            //     console.log(persons[index])
+            // }
+
+            // -------------------loop of name and surname
+
+            // var persons = [
+            //     (a = {
+            //         name: "Andrey",
+            //         surname: "Petroff",
+            //         sex: "Male",
+            //         age: "100",
+            //         fathername: "Akakiyovich",
+            //     }),
+            //     (b = {
+            //         name: "Anton",
+            //         surname: "Nikitin",
+            //         age: "23",
+            //         fathername: "Ronaldovich",
+            //     }),
+            //     (c = {
+            //         name: "Artem",
+            //         surname: "Kozyr",
+            //         fathername: "Messiyovich",
+            //     }),
+            //     (d = {
+            //         "name": "Illia",
+            //         "surname": "Kozyr",
+            //         "fathername": "Sergeevych",
+            //     }),
+            // ];
+
+            // var index;
+            // for (index = 0; index < persons.length; ++index) {
+            //     console.log(persons[index].name + " " + persons[index].surname);
+            // }
+
+            // -------------------loop of loop of values
+
+            // var persons = [
+            //     (a = {
+            //         name: "Andrey",
+            //         surname: "Petroff",
+            //         sex: "Male",
+            //         age: "100",
+            //         fathername: "Akakiyovich",
+            //     }),
+            //     (b = {
+            //         name: "Anton",
+            //         surname: "Nikitin",
+            //         age: "23",
+            //         fathername: "Ronaldovich",
+            //     }),
+            //     (c = {
+            //         name: "Artem",
+            //         surname: "Kozyr",
+            //         fathername: "Messiyovich",
+            //     }),
+            //     (d = {
+            //         name: "Illia",
+            //         surname: "Kozyr",
+            //         fathername: "Sergeevych",
+            //     }),
+            // ];
+
+            // for (let index = 0; index < persons.length; index++) {
+            //     for (let key in persons[index]) {
+            //         console.log(persons[index][key]);
+            //     }
+            // }
+
+            // -------------------fullName
+
+            // var persons = [
+            //     (a = {
+            //         name: "Andrey",
+            //         surname: "Petroff",
+            //         sex: "Male",
+            //         fathername: "Akakiyovich",
+            //     }),
+            //     (b = {
+            //         name: "Anton",
+            //         surname: "Nikitin",
+            //         age: "23",
+            //         fathername: "Ronaldovich",
+            //     }),
+            //     (c = {
+            //         name: "Artem",
+            //         surname: "Kozyr",
+            //         fathername: "Messiyovich",
+            //     }),
+            //     (d = {
+            //         name: "Illia",
+            //         surname: "Kozyr",
+            //         fathername: "Sergeevych",
+            //     }),
+            // ];
+
+            // for (let object of persons) {
+            //     if (object.name && object.surname) {
+            //         object.fullName = object.name + " " + object.surname;
+            //     }
+            // }
+            // console.log(persons);
+
+            // -------------------serialize
+
+            // console.log(JSON.stringify(persons));
+
+            // -------------------deserialize
+
+            // const obj = JSON.parse('d: {"name":"John", "surname": "Ivanoff", "city" : "New York"}');
+            // let resoultObject = Object.assign(persons, obj);
+            // console.log(resoultObject)
+
+            // -------------------HTML
+
+            // var persons = [
+            //     (a = {
+            //         name: "Andrey",
+            //         surname: "Petroff",
+
+            //     }),
+            //     (b = {
+            //         name: "Anton",
+            //         surname: "Nikitin",
+
+            //     }),
+            //     (c = {
+            //         name: "Artem",
+            //         surname: "Kozyr",
+
+            //     }),
+            //     (d = {
+            //         name: "Illia",
+            //         surname: "Kozyr",
+
+            //     }),
+            // ];
+
+            // var str = "<table border='1'>";
+            // for (let i = 0; i < 4; i++) {
+            //     for (let key in persons[i]) {
+            //         str += `<tr><td>${[key]}</td><td>${persons[i][key]}</td></tr>`;
+            //     }
+
+            // }
+            // str += "</table>";
+            // console.log(str);
+            // document.write(str);
+
+            // ---------------HTML optional fields
+
+            // var persons = [
+            //     (a = {
+            //         name: "Andrey",
+            //         surname: "Petroff",
+            //         sex: "Male",
+            //         fathername: "Akakiyovich",
+            //     }),
+            //     (b = {
+            //         name: "Anton",
+            //         surname: "Nikitin",
+            //         age: "23",
+            //         fathername: "Ronaldovich",
+            //     }),
+            //     (c = {
+            //         name: "Artem",
+            //         surname: "Kozyr",
+            //         fathername: "Messiyovich",
+            //     }),
+            //     (d = {
+            //         name: "Illia",
+            //         surname: "Kozyr",
+            //         fathername: "Sergeevych",
+            //     }),
+            // ];
+
+            // var str = "<table border='1'>";
+            // for (let i = 0; i < 4; i++) {
+            //     for (let key in persons[i]) {
+            //         str += `<tr><td>${[key]}</td><td>${persons[i][key]}</td></tr>`;
+            //     }
+
+            // }
+            // str += "</table>";
+            // console.log(str);
+            // document.write(str);
+
+            // -------------------HTML tr color
+
+            var persons = [
+                (a = {
+                    name: "Andrey",
+                    surname: "Petroff",
+                    sex: "Male",
+                    fathername: "Akakiyovich",
+                }),
+                (b = {
+                    name: "Anton",
+                    surname: "Nikitin",
+                    age: "23",
+                    fathername: "Ronaldovich",
+                }),
+                (c = {
+                    name: "Artem",
+                    surname: "Kozyr",
+                    fathername: "Messiyovich",
+                }),
+                (d = {
+                    name: "Illia",
+                    surname: "Kozyr",
+                    fathername: "Sergeevych",
+                }),
+            ];
+
+            var str = "<table border='1'>";
+            for (let i = 0; i < 4; i++) {
+                for (let key in persons[i]) {
+                    str += `<tr style="color: red;><td>${[key]}</td><td>${
+                        persons[i][key]
+                    }</td></tr>`;
+                }
+            }
+            str += "</table>";
+            console.log(str);
+            document.write(str);
+            
+
+            // -------------------destruct array
+
+            // let arr = [1,2,3,4,5, "a", "b", "c"]
+            // let [odd1=1%2, even1, odd2, even2, odd3, ...arrr] = [1,2,3,4,5, "a", "b", "c"];
+
+            //--------------------destruct string
+
+            // let arr = [1, "abc"];
+            // let [number, [s1, s2, s3]] = arr;
+
+            // --------------------destruct 2
+
+            // let obj = {
+            //     name: "Ivan",
+            //     surname: "Petrov",
+            //     children: [{ name: "Maria" }, { name: "Nikolay" }],
+            // };
+
+            // let {
+            //     children: [{ name: name1 }, { name: name2 }],
+            // } = obj;
+
+            // --------------------destruct 3
+
+            let arr = [1,2,3,4, 5,6,7,10]
+
+            let [a, b, {length = arr.length}] = arr;
+
+        </script>
+    </body>
+</html>

+ 149 - 0
JavaScript HW/HW 6/index.html

@@ -0,0 +1,149 @@
+<!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>
+            // -----------------------Анализ
+            
+            function a(text) {
+                alert(text);
+            }
+
+            // -----------------------cube
+
+            function cube(number) {
+                number = number ** 3;
+                return number;
+            }
+
+            // -----------------------avg2
+
+            function avg2(a, b) {
+                let average = (a + b) / 2;
+                return average;
+            }
+
+            // -----------------------sum3
+
+            function sum3(a = 0, b = 0, c = 0) {
+                let sumsNumbers = a + b + c;
+                return sumsNumbers;
+            }
+
+            // -----------------------intRandom
+
+            function intRandom(a = 0, b = 0) {
+                let randomNumber = Math.random() * (b - a) + a;
+                return Math.round(randomNumber);
+            }
+
+            // -----------------------greetAll
+
+            function greetAll() {
+                let arr = "";
+                if (arr != "") {
+                    arr = "";
+                }
+                for (let i = 0; i < arguments.length; i++) {
+                    arr += arguments[i] + "," + " ";
+                }
+                
+                arr = arr.slice(0, -2);
+                console.log(arr);
+                alert("Hello " + arr + "!");
+            }
+
+            // ------------------------sum
+
+            function sum(array) {
+                var sum = 0;
+                for (var i = 0; i < arguments.length; i++) {
+                    sum += arguments[i];
+                }
+                return sum;
+            }
+
+            // ------------------------Union
+
+            function aSample() {
+                return a("Hello");
+            }
+            function cubeSample() {
+                return cube(10);
+            }
+            function avg2Sample() {
+                return avg2(20, 30);
+            }
+            function sum3Sample() {
+                return sum3(1, 2);
+            }
+            function intRandomSample() {
+                return intRandom(1, 10);
+            }
+            function greetAllSample() {
+                return greetAll("Anton", "Illia", "Andrey");
+            }
+            function sumSample() {
+                return sum(1, 2, 3, 4, 5, 6, 7, 8, 9);
+            }
+
+            // let taskByName = prompt("Введите название задания");
+            // switch (taskByName.toLowerCase()) {
+            //     case "a":
+            //         aSample();
+            //         break;
+            //     case "cube":
+            //         cubeSample();
+            //         break;
+            //     case "avg2":
+            //         avg2Sample();
+            //         break;
+            //     case "sum3":
+            //         sum3Sample();
+            //         break;
+            //     case "intRandom":
+            //         intRandomSample();
+            //         break;
+            //     case "greetAll":
+            //         greetAllSample();
+            //         break;
+            //     case "sum":
+            //         sumSample();
+            //         break;
+            // }
+
+            // ------------------------Union declarative
+
+            let union = {
+                a () {
+                    a("Hello") 
+                },
+                cube () {
+                    cube(10)
+                },
+                avg2 () {
+                    avg2(20, 30)
+                },
+                sum3 () {
+                    sum3(1, 2)
+                },
+                intRandom () {
+                    intRandom(1, 10)
+                },
+                greetAll () {
+                    greetAll("Anton", "Illia", "Andrey")
+                },
+                sum () {
+                    sum(1, 2, 3, 4, 5, 6, 7, 8, 9)
+                },
+            };
+
+            console.log(union[prompt("Введите название задания")]());
+        </script>
+    </body>
+</html>

+ 5 - 0
JavaScript HW/HW 7/.idea/.gitignore

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

+ 12 - 0
JavaScript HW/HW 7/.idea/HW 7.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
JavaScript HW/HW 7/.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/HW 7.iml" filepath="$PROJECT_DIR$/.idea/HW 7.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
JavaScript HW/HW 7/.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
+  </component>
+</project>

+ 92 - 0
JavaScript HW/HW 7/index.html

@@ -0,0 +1,92 @@
+<!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>
+        <div>
+            <input type="number" id="number1" />
+            <input type="number" id="number2" />
+            <button id="calc">Посчитать</button>
+            <input type="text" name="" id="result" />
+        </div>
+
+        <script>
+            // -------------------Таблица умножения, Подсветить ячейку, Подсветить строку и столбец
+
+            let table = document.createElement("table");
+            document.body.append(table);
+
+            for (let i = 1; i < 10; i++) {
+                let tr = document.createElement("tr");
+                table.append(tr);
+                tr.style.border = "1px solid black";
+                for (let a = 1; a < 10; a++) {
+                    let td = document.createElement("td");
+                    tr.append(td);
+                    td.innerText = i * a;
+                    td.style.border = "2px solid black";
+                    td.style.padding = "10px";
+                    td.style.margin = "0px";
+                }
+            }
+
+            let tdarr = document.querySelectorAll("td");
+
+            tdarr.forEach(
+                (tdOn) =>
+                    (tdOn.onmousemove = function () {
+                        this.style.backgroundColor = "cyan";
+                        this.parentElement.style.backgroundColor = "cyan";
+                        let index = this.cellIndex;
+                        let column = document.querySelectorAll("tr");
+                        column.forEach(
+                            (columns) =>
+                                (columns.children[index].style.backgroundColor =
+                                    "cyan")
+                        );
+                    })
+            );
+
+            
+
+            tdarr.forEach(
+                (tdOut) =>
+                    (tdOut.onmouseout = function () {
+                        this.style.backgroundColor = "transparent";
+                        this.parentElement.style.backgroundColor =
+                            "transparent";
+                        let index = this.cellIndex;
+                        let column = document.querySelectorAll("tr");
+                        column.forEach(
+                            (columns) =>
+                                (columns.children[index].style.backgroundColor =
+                                    "transparent")
+                        );
+                    })
+            );
+
+            // ------------------------ Calc
+
+            let number1 = document.getElementById("number1");
+            let number2 = document.getElementById("number2");
+
+            calc.onclick = function () {
+                alert(+number1.value + +number2.value);
+            };
+
+            // ------------------------ Calc Live
+
+            function calc() {
+                result.value = +number1.value + +number2.value;
+            }
+
+            number1.oninput = calc;
+            number2.oninput = calc;
+            
+        </script>
+    </body>
+</html>

BIN
JavaScript HW/HW 8/.DS_Store


+ 3 - 0
JavaScript HW/HW 8/.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+    "liveServer.settings.port": 5501
+}

+ 112 - 0
JavaScript HW/HW 8/index.html

@@ -0,0 +1,112 @@
+<!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>
+			// -----------------------sort
+
+			var persons = [
+				{ name: "Иван", age: 17 },
+				{ name: "Мария", age: 35 },
+				{ name: "Алексей", age: 73 },
+				{ name: "Яков", age: 12 },
+			];
+
+			function sort(array, objectKey, boolean) {
+				if (boolean) {
+					array.sort((a, b) =>
+						a[objectKey] < b[objectKey] ? 1 : -1
+					);
+				} else {
+					array.sort((a, b) =>
+						a[objectKey] > b[objectKey] ? 1 : -1
+					);
+				}
+			}
+
+			// sort(persons, "age")
+			sort(persons, "name", false);
+
+			// ------------------------array map
+
+			var array = ["1", {}, null, undefined, "500", 700];
+
+			// array.map( a => (a === Number ? +a : a))
+
+			let b = array.map((a) => {
+				let number = Number(a);
+				return isNaN(a) ? a : number;
+			});
+			console.log(b);
+
+			// ------------------------array reduce
+
+			var array2 = ["0", 5, 3, "string", null];
+			let productNumber = array2.reduce(function (a, b) {
+				if (typeof b === "number") {
+					a *= b;
+				}
+				return a;
+			}, 1);
+			console.log(productNumber);
+
+			// ------------------------object filter
+
+			var phone = {
+				brand: "meizu",
+				model: "m2",
+				ram: 2,
+				color: "black",
+			};
+
+			function filter(obj, callback) {
+				let newObj = {};
+				for (let key in obj) {
+					if (callback(key, obj[key])) {
+						newObj = { ...newObj, [key]: obj[key] };
+					}
+				}
+				return newObj;
+			}
+
+			filter(phone, (key, value) => key === "color" || value === 2);
+
+			//-----------------------object map
+
+			function map(obj, callBack) {
+				let result = {};
+				for (let key in obj) {
+					result = { ...result, ...callBack(key, obj[key]) };
+					return result;
+				}
+			}
+
+			map({ name: "Иван", age: 17 }, function (key, value) {
+				var result = {};
+				result[key + "_"] = value + "$";
+				return result;
+			}); //должен вернуть {name_: "Иван$", age_: "17$"}
+
+			//-----------------------Рекурсия
+
+			function progression_sum(max_num_in_progressian) {
+				if (max_num_in_progressian === 1) return 1;
+
+				console.log(max_num_in_progressian);
+				let result =
+					progression_sum(max_num_in_progressian - 1) +
+					max_num_in_progressian;
+				console.log(max_num_in_progressian, result);
+
+				return result;
+			}
+
+			console.log(progression_sum(5));
+		</script>
+	</body>
+</html>

+ 81 - 0
JavaScript HW/HW 9/index.html

@@ -0,0 +1,81 @@
+<!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>
+            // -------------------------------makeProfileTimer-------------------------------
+
+            function makeProfileTimer() {
+                let t0 = performance.now();
+                return function tn() {
+                    let t1 = performance.now();
+                    return t1 - t0;
+                };
+            }
+
+            let timer = makeProfileTimer();
+            alert("Замеряем время работы этого alert");
+            alert(timer());
+
+            // -------------------------------------makeSaver---------------------------------
+
+            function makeSaver(name) {
+                let promptNotCalled = true;
+                let nameAgain;
+                return function () {
+                    if (promptNotCalled) {
+                        nameAgain = name();
+                        promptNotCalled = false;
+                    }
+                    return nameAgain;
+                };
+            }
+
+            var saver = makeSaver(Math.random); //создает функцию-хранилище результата переданной в качестве параметра функции (Math.random
+            // в примере). На этом этапе Math.random НЕ вызывается
+            var value1 = saver(); //saver вызывает переданную в makeSaver функцию, запоминает результат и возвращает его
+            var value2 = saver(); //saver в дальнейшем просто хранит результат функции, и более НЕ вызывает переданную
+            //в makeSaver функцию;
+            value1 === value2; // всегда true
+
+            var saver2 = makeSaver(
+                () =>
+                    console.log("saved function called") ||
+                    [null, undefined, false, "", 0, Math.random()][
+                        Math.ceil(Math.random() * 6)
+                    ]
+            );
+            var value3 = saver2();
+            var value4 = saver2();
+
+            value3 === value4; // тоже должно быть true
+
+            let namePrompt = prompt.bind(window, "Как тебя зовут?");
+            let nameSaver = makeSaver(namePrompt);
+            alert(`Привет! Prompt еще не было!`);
+            alert(
+                `Привет ${nameSaver()}. Только что запустился prompt, первый и последний раз`
+            );
+            alert(
+                `Слушай, ${nameSaver()}, го пить пиво. Ведь prompt был только один раз`
+            );
+
+            //-----------------------------------------Final Countdown--------------------------------------
+
+            (function finalCountdown(sec = 0) {
+                for (let i = 5; i >= 0; i--) {
+                    setTimeout(() => {
+                        i ? console.log(i) : console.log("поехали");
+                    }, sec++ * 1000);
+                }
+            })();
+
+            //----------------------------------------------myBind--------------------------------------
+        </script>
+    </body>
+</html>

BIN
JavaScript HW/Крутилки/.DS_Store


BIN
JavaScript HW/Крутилки/img/1@3x.png


+ 86 - 0
JavaScript HW/Крутилки/index.js

@@ -0,0 +1,86 @@
+function Control(
+	el,
+	{
+		value = 10,
+		min = 0,
+		max = 100,
+		minAngle = -90,
+		maxAngle = 90,
+		wheelSpeed = 0.01,
+		step = 1,
+	} = {}
+) {
+	const img = document.createElement("img");
+	img.src = "img/1@3x.png";
+	el.append(img);
+
+	const ratio = (maxAngle - minAngle) / (max - min);
+	const getAngle = () => (value - min) * ratio + minAngle;
+
+	this.setValue = (newValue) => {
+		if (newValue < min) {
+			newValue = min;
+		}
+
+		if (newValue > max) {
+			newValue = max;
+		}
+
+		value = newValue;
+
+		if (typeof this.onchange === "function") {
+			this.onchange(value);
+		}
+
+		img.style.transform = `rotate(${getAngle()}deg)`;
+	};
+
+	this.getValue = () => value;
+
+	img.onmousewheel = (e) => {
+		const { deltaY } = e;
+		e.preventDefault();
+		this.setValue(value + deltaY * wheelSpeed);
+	};
+
+	img.onclick = (e) => {
+		const { layerX } = e;
+		console.log(e, layerX);
+		if (layerX > img.width / 2) this.setValue(value + step);
+		else this.setValue(value - step);
+	};
+
+	this.setValue(value);
+}
+
+function setRGB() {
+	let a = red.getValue(value * wheelSpeed);
+	let b = green.getValue(value * wheelSpeed);
+	let c = blue.getValue(value * wheelSpeed);
+
+	let rgbDone = (div.style.background = `rgb(${a}, ${b}, ${c})`);
+	return console.log(rgbDone);
+}
+
+const red = new Control(container1, { min: 0, max: 255 });
+red.onchange = setRGB();
+const green = new Control(container1, { min: 0, max: 255 });
+green.onchange = setRGB();
+const blue = new Control(container1, { min: 0, max: 255 });
+blue.onchange = setRGB();
+
+const volumeControl = new Control(container1, { value: 50 });
+volumeControl.onchange = (value) => {
+	audio.volume = value / 100;
+	console.log("ON CHANGE", value);
+};
+
+const audio = document.createElement("audio");
+audio.setAttribute("controls", "");
+audio.src = "/media/klychko.mp3";
+document.body.append(audio);
+
+const div = document.createElement("div");
+div.style.width = "300px";
+div.style.height = "300px";
+document.body.append(div);

BIN
JavaScript HW/Крутилки/media/klychko.mp3


+ 17 - 0
JavaScript HW/Крутилки/spinner.html

@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html>
+	<head>
+		<meta charset="utf-8" />
+		<meta name="viewport" content="width=device-width" />
+		<title>Другой тайтл ПРИВЕТ 17й</title>
+		<style>
+			body {
+				padding: 400px;
+			}
+		</style>
+	</head>
+	<body>
+		<div id="container1"></div>
+		<script src="index.js"></script>
+	</body>
+</html>

+ 3 - 0
Market GraphQL + Redux project/.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+    "liveServer.settings.port": 5501
+}

+ 47 - 0
Market GraphQL + Redux project/index.html

@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>GQL</title>
+        <meta charset="utf8" />
+        <link rel="stylesheet" href="style.css" />
+    </head>
+    <body>
+        <header id="header">
+            <div id="cartIcon">
+                <a href="#/category/6262ca7dbf8b206433f5b3d1">
+                    <img
+                        class="cartIcon"
+                        src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Amazon_logo.svg/1200px-Amazon_logo.svg.png"
+                        alt=""
+                    />
+                </a>
+            </div>
+            <div class="qwer" id="qwer">
+                <div>
+                    <button id="shoppingCart">Cart</button>
+                </div>
+                <div>
+                    <button id="reg">Registration</button>
+                </div>
+                <div>
+                    <button id="login">Login</button>
+                </div>
+                <div>
+                    <button id="purchaseHistory">Purchase History</button>
+                </div>
+            </div>
+        </header>
+        <main id="mainContainer">
+            <aside id="aside">Категории</aside>
+            <div class="mainBlock" id="mainBlock">
+                <div id="categoryName"></div>
+
+                <div id="productBlock"></div>
+            </div>
+        </main>
+        <footer class="footer">
+            <h2 class="footerText">illiaKozyr &#8482;</h2>
+        </footer>
+        <script src="script.js"></script>
+    </body>
+</html>

+ 826 - 0
Market GraphQL + Redux project/script.js

@@ -0,0 +1,826 @@
+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 jwtDecode(token) {
+    try {
+        return JSON.parse(atob(token.split(".")[1]));
+    } catch (e) {}
+}
+
+function authReducer(state, { type, token }) {
+    if (state === undefined) {
+        if (localStorage.authToken) {
+            type = "AUTH_LOGIN";
+            token = localStorage.authToken;
+        }
+    }
+    if (type === "AUTH_LOGIN") {
+        let payload = jwtDecode(token);
+        if (payload) {
+            localStorage.authToken = token;
+            return { token, payload };
+        }
+    }
+    if (type === "AUTH_LOGOUT") {
+        localStorage.removeItem("authToken");
+        return {};
+    }
+    return state || {};
+}
+
+const actionAuthLogin = (token) => ({ type: "AUTH_LOGIN", token });
+
+const actionAuthLogout = () => (dispatch) => {
+    dispatch({ type: "AUTH_LOGOUT" });
+    localStorage.removeItem("authToken");
+};
+
+function promiseReducer(state = {}, { type, name, status, payload, error }) {
+    if (type === "PROMISE") {
+        return {
+            ...state,
+            [name]: { status, payload, error },
+        };
+    }
+    return state;
+}
+
+const actionPending = (name) => ({
+    type: "PROMISE",
+    status: "PENDING",
+    name,
+});
+const actionFulfilled = (name, payload) => ({
+    type: "PROMISE",
+    status: "FULFILLED",
+    name,
+    payload,
+});
+const actionRejected = (name, error) => ({
+    type: "PROMISE",
+    status: "REJECTED",
+    name,
+    error,
+});
+
+const actionPromise = (name, promise) => async (dispatch) => {
+    try {
+        dispatch(actionPending(name));
+        let payload = await promise;
+        dispatch(actionFulfilled(name, payload));
+        return payload;
+    } catch (e) {
+        dispatch(actionRejected(name, e));
+    }
+};
+
+function cartReducer(state = {}, { type, count = 1, good }) {
+    // type CART_ADD CART_REMOVE CART_CLEAR CART_DEL
+    // {
+    //  id1: {count: 1, good: {name, price, images, id}}
+    // }
+    if (type === "CART_ADD") {
+        return {
+            ...state,
+            [good._id]: { count: count + (state[good._id]?.count || 0), good },
+        };
+    }
+
+    if (type === "CART_DELETE") {
+        if (state[good._id].count > 1) {
+            return {
+                ...state,
+                [good._id]: {
+                    count: -count + (state[good._id]?.count || 0),
+                    good,
+                },
+            };
+        }
+
+        if (state[good._id].count === 1) {
+            let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
+            //delete newState[good._id]
+            return newState;
+        }
+    }
+
+    if (type === "CART_CLEAR") {
+        return {};
+    }
+    if (type === "CART_REMOVE") {
+        // let newState = {...state}
+        let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
+        //delete newState[good._id]
+        return newState;
+    }
+
+    return state;
+}
+
+const actionCartAdd = (good, count = 1) => ({ type: "CART_ADD", good, count });
+const actionCartDelete = (good) => ({ type: "CART_DELETE", good });
+const actionCartClear = () => ({ type: "CART_CLEAR" });
+const actionCartRemove = (good) => ({ type: "CART_REMOVE", good });
+
+function localStoreReducer(reducer, localStorageKey) {
+    function localStoredReducer(state, action) {
+        // Если state === undefined, то достать старый state из local storage
+        if (state === undefined) {
+            try {
+                return JSON.parse(localStorage[localStorageKey]);
+            } catch (e) {}
+        }
+        const newState = reducer(state, action);
+        // Сохранить newState в local storage
+        localStorage[localStorageKey] = JSON.stringify(newState);
+        return newState;
+    }
+    return localStoredReducer;
+}
+
+const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
+
+function combineReducers(reducers) {
+    //пачку редьюсеров как объект {auth: authReducer, promise: promiseReducer}
+    function combinedReducer(combinedState = {}, action) {
+        //combinedState - типа {auth: {...}, promise: {....}}
+        const newCombinedState = {};
+        for (const [reducerName, reducer] of Object.entries(reducers)) {
+            const newSubState = reducer(combinedState[reducerName], action);
+            if (newSubState !== combinedState[reducerName]) {
+                newCombinedState[reducerName] = newSubState;
+            }
+        }
+        if (Object.keys(newCombinedState).length === 0) {
+            return combinedState;
+        }
+        return { ...combinedState, ...newCombinedState };
+    }
+
+    return combinedReducer; //нам возвращают один редьюсер, который имеет стейт вида {auth: {...стейт authReducer-а}, promise: {...стейт promiseReducer-а}}
+}
+
+const getGQL = (url) => (query, variables) =>
+    fetch(url, {
+        method: "POST",
+        headers: {
+            "Content-Type": "application/json",
+            // 'Accept' : 'application/json',
+            ...(localStorage.authToken
+                ? { Authorization: "Bearer " + localStorage.authToken }
+                : {}),
+        },
+        body: JSON.stringify({ query, variables }),
+    })
+        .then((res) => res.json())
+        .then((data) => {
+            if (data.data) {
+                return Object.values(data.data)[0];
+            } else throw new Error(JSON.stringify(data.errors));
+        });
+
+const backendURL = "http://shop-roles.node.ed.asmer.org.ua";
+const gql = getGQL(backendURL + "/graphql");
+
+const store = createStore(
+    combineReducers({
+        auth: authReducer,
+        promise: promiseReducer,
+        cart: localStoreReducer(cartReducer, "cart"),
+    })
+); //не забудьте combineReducers если он у вас уже есть
+if (localStorage.authToken) {
+    store.dispatch(actionAuthLogin(localStorage.authToken));
+}
+
+store.subscribe(() => console.log(store.getState()));
+
+
+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 subCategories {
+    name _id
+}
+goods {
+    _id name price images {
+        url
+    }
+}
+}
+}`,
+            { q: JSON.stringify([{ _id }]) }
+        )
+    );
+
+const actionLogin = (login, password) =>
+    actionPromise(
+        "actionLogin",
+        gql(
+            `query log($login:String, $password:String){
+                                  login(login:$login, password:$password)
+                                }`,
+            { login, password }
+        )
+    );
+
+const actionGoodById = (_id) =>
+    actionPromise(
+        "GoodFineOne",
+        gql(
+            `query goodByid($goodId: String) {
+        GoodFindOne(query: $goodId) {
+            _id
+          name
+          price
+          description
+          images {
+            url
+          }
+        }
+      }`,
+            { goodId: JSON.stringify([{ _id }]) }
+        )
+    );
+
+store.dispatch(actionRootCats());
+
+const actionFullLogin = (log, pass) => async (dispatch) => {
+    let token = await dispatch(
+        actionPromise(
+            "login",
+            gql(
+                `query login($login: String, $password: String) {
+            login(login: $login, password: $password)
+            }`,
+                { login: log, password: pass }
+            )
+        )
+    );
+    if (token) {
+        dispatch(actionAuthLogin(token));
+    }
+};
+
+const actionFullRegister = (login, password) => async (dispatch) => {
+    let user = await dispatch(
+        actionPromise(
+            "register",
+            gql(
+                `mutation register($login: String, $password: String) {
+                UserUpsert(user: {login: $login, password: $password}) {
+                   _id
+                   login
+                 }
+               }`,
+                { login: login, password: password }
+            )
+        )
+    );
+    if (user) {
+        dispatch(actionFullLogin(login, password));
+    }
+};
+
+const actionOrder = () => async (dispatch, getState) => {
+    let { cart } = getState();
+    const orderGoods = Object.entries(cart).map(([_id, { count }]) => ({
+        good: { _id },
+        count,
+    }));
+
+    let result = await dispatch(
+        actionPromise(
+            "order",
+            gql(
+                `
+                    mutation newOrder($order:OrderInput){
+                    OrderUpsert(order:$order)
+                        { _id total 	}
+                    }
+            `,
+                { order: { orderGoods } }
+            )
+        )
+    );
+    if (result?._id) {
+        dispatch(actionCartClear());
+        document.location.hash = "#/cart/";
+        alert("Purchase completed")
+    }
+
+};
+
+const orderHistory = () =>
+    actionPromise(
+        "history",
+        gql(` query OrderFind{
+        OrderFind(query:"[{}]"){
+            _id total createdAt orderGoods{
+                count good{
+                    _id name price images{
+                        url
+                    }
+                }
+                owner{
+                    _id login 
+                }
+            }
+        }
+    }
+    `)
+    );
+
+store.subscribe(() => {
+    const { rootCats } = store.getState().promise;
+    if (rootCats?.payload) {
+        aside.innerHTML = "";
+        for (let { _id, name } of rootCats?.payload) {
+            const a = document.createElement("a");
+            a.href = `#/category/${_id}`;
+            a.innerHTML = name;
+            aside.append(a);
+        }
+    }
+});
+
+store.subscribe(() => {
+    const { catById } = store.getState().promise;
+    const [, route] = location.hash.split("/");
+
+    if (catById?.payload && route === "category") {
+        const { name, goods, subCategories } = catById?.payload;
+        categoryName.innerHTML = `<h1>${name}</h1>`;
+        var element = document.getElementById("productBlock");
+        while (element.firstChild) {
+            element.removeChild(element.firstChild);
+        }
+
+        
+
+        if (subCategories) {
+            for (let { name, _id } of subCategories) {
+                const link = document.createElement("a");
+                link.id = "subCategories";
+                link.href = `#/category/${_id}`;
+                link.innerText = name;
+                productBlock.append(link);
+            }
+        }
+        
+        for (let { _id, name, price, images, } of goods) {
+            // console.log()
+            const description = document.createElement("div");
+            const textBlock = document.createElement("div");
+            const imgProduct = document.createElement("img");
+            const a = document.createElement("p");
+            const productPrice = document.createElement("p");
+            const linkCard = document.createElement("a");
+            const addToCartButton = document.createElement('button')
+            
+            addToCartButton.innerHTML = "add to cart"
+            addToCartButton.id = "addToCartButtonn"
+
+            linkCard.innerHTML = "About the product"
+            linkCard.href = `#/good/${_id}`;
+            
+            linkCard.className = "linkCard"
+
+            productBlock.append(description);
+            description.setAttribute("class", "card");
+            description.id = "card";
+
+            description.append(imgProduct);
+            
+
+            imgProduct.src = `${backendURL}/${images[0].url}`;
+
+            description.append(textBlock);
+
+            a.innerHTML = name;
+            textBlock.append(a);
+
+            productPrice.innerHTML = "price: " + price;
+            textBlock.append(productPrice);
+
+            textBlock.append(linkCard);
+            textBlock.append(addToCartButton)
+
+
+            addToCartButton.onclick = () => {
+            store.dispatch(actionCartAdd({_id, name, price, images,}));
+        };
+           
+        }
+    }
+});
+
+const flexBlockForGFO = document.createElement("div");
+flexBlockForGFO.id = "flexBlockForGFO";
+const goodFineOneImgBlock = document.createElement("div");
+const goodFineOneTextBlock = document.createElement("div");
+const goodFineOneName = document.createElement("h2");
+const goodFineOneImg = document.createElement("img");
+const goodFineOnePrice = document.createElement("p");
+const goodFineOneDescription = document.createElement("p");
+const goodFineOneAddToCartButton = document.createElement("button");
+
+const buttonPlus = document.createElement("button");
+const buttonMinus = document.createElement("button");
+buttonPlus.innerHTML = "+";
+buttonMinus.innerHTML = "-";
+
+store.subscribe(() => {
+    const { GoodFineOne } = store.getState().promise;
+    const [, route, _id] = location.hash.split("/");
+    if (GoodFineOne?.payload && route === "good") {
+        productBlock.innerHTML = "";
+        const { name, images, price, description } = GoodFineOne?.payload;
+        productBlock.append(flexBlockForGFO);
+
+        flexBlockForGFO.append(goodFineOneImgBlock);
+        goodFineOneImg.src = `${backendURL}/${images[0].url}`;
+        goodFineOneImg.id = "goodOneImg";
+        goodFineOneImgBlock.append(goodFineOneImg);
+
+        flexBlockForGFO.append(goodFineOneTextBlock);
+
+        goodFineOneName.innerHTML = name;
+        goodFineOneTextBlock.append(goodFineOneName);
+
+        goodFineOnePrice.innerHTML = "price: " + price;
+        goodFineOneTextBlock.append(goodFineOnePrice);
+        goodFineOneDescription.innerHTML = description;
+        goodFineOneTextBlock.append(goodFineOneDescription);
+        goodFineOneAddToCartButton.innerHTML = "add to cart";
+        goodFineOneTextBlock.append(goodFineOneAddToCartButton);
+
+        goodFineOneAddToCartButton.onclick = () => {
+            store.dispatch(actionCartAdd(GoodFineOne.payload));
+        };
+        
+        // const a = document.getElementById(addToCartButtonn)
+        // a.onclick = () => {
+        //     store.dispatch(actionCartAdd(GoodFineOne.payload));
+        // };
+
+    }
+});
+
+const bPoputDeleteBlock = document.createElement("div");
+const bPoput = document.createElement("div");
+bPoput.className = "b-popup";
+bPoput.id = "b-popup";
+const bPoputContainer = document.createElement("div");
+bPoputContainer.className = "b-popup-content";
+bPoputContainer.id = "bPopupContent";
+const buttonGoodDeleteBlock = document.createElement("div");
+buttonGoodDeleteBlock.id = "buttonGoodDeleteBlock";
+
+const buttonCloseCart = document.createElement("button");
+buttonCloseCart.innerText = `×`;
+buttonCloseCart.id = "buttonCloseCartId";
+const buttonGoodDelete = document.createElement("button");
+buttonGoodDelete.innerText = "delete";
+buttonGoodDelete.id = "buttonDelete";
+
+shoppingCart.onclick = () => {
+    header.append(bPoput);
+    bPoput.append(bPoputContainer);
+};
+
+bPoputContainer.append(buttonGoodDeleteBlock);
+buttonGoodDeleteBlock.append(buttonGoodDelete);
+bPoputContainer.append(buttonCloseCart);
+
+const divToCardBlock = document.createElement("div");
+const goodByIdPrice = document.createElement("h2");
+const buyBlock = document.createElement("div");
+buyBlock.className = "buyBlock";
+const buttonBuy = document.createElement("button");
+buttonBuy.className = "buttonBuy";
+buttonBuy.id = "buttonBuy";
+
+const a = document.createElement('p')
+a.innerHTML = "clear"
+store.subscribe(() => {
+    divToCardBlock.innerHTML = "";
+    goodByIdPrice.innerHTML = "";
+    const toCartById = store.getState().cart;
+    
+    
+    let countSum = 0;
+    let priceSum = 0;
+    for (let value of Object.values(toCartById)) {
+        const { count, good, price } = value;
+
+        countSum += count;
+        priceSum += good.price * count;
+
+        divToCardBlock.id = "divToCartBlock";
+        const divToCart = document.createElement("div");
+        const goodByIdImage = document.createElement("img");
+        const goodByIdName = document.createElement("h2");
+        const goodByIdCount = document.createElement("h2");
+        const buttonPlus = document.createElement("button");
+        const buttonMinus = document.createElement("button");
+        const removePosition = document.createElement("button")
+
+        buttonBuy.style.display = "block";
+        buttonBuy.innerHTML = "Buy";
+
+        goodByIdPrice.innerHTML = "Total: " + priceSum;
+
+        removePosition.innerHTML = "Remove"
+        removePosition.id = "removePosition"
+        buttonPlus.innerHTML = "+";
+        buttonMinus.innerHTML = "-";
+        buttonPlus.id = "buttonPlus";
+        buttonMinus.id = "buttonMinus";
+
+        divToCart.id = "divToCart";
+        bPoputContainer.append(divToCardBlock);
+        divToCardBlock.append(divToCart);
+        divToCart.append(goodByIdImage);
+        divToCart.append(goodByIdName);
+        divToCart.append(goodByIdCount);
+        divToCart.append(buttonPlus);
+        divToCart.append(buttonMinus);
+        divToCart.append(removePosition)
+        bPoputContainer.append(buyBlock);
+        buyBlock.append(goodByIdPrice);
+        buyBlock.append(buttonBuy);
+
+        goodByIdImage.src = `${backendURL}/${value.good.images[0].url}`;
+        goodByIdName.innerText = good.name;
+        goodByIdCount.innerText = count;
+
+        buttonBuy.onclick = () => {
+            store.dispatch(actionOrder());
+            store.dispatch(orderHistory());
+
+        };
+
+        buttonPlus.onclick = () => store.dispatch(actionCartAdd(value.good));
+        buttonMinus.onclick = () => {
+            store.dispatch(actionCartDelete(value.good));
+            console.log(value.good, "this");
+        };
+
+        removePosition.onclick = () => store.dispatch(actionCartRemove(value.good))
+    }
+
+    shoppingCart.innerHTML = "Cart: " + countSum;
+
+    buttonCloseCart.onclick = () => {
+        var parent = document.getElementById("header");
+        var child = document.getElementById("b-popup");
+        parent.removeChild(child);
+    };
+
+    const payload = store.getState().auth.token;
+    if (payload) {
+        shoppingCart.style.display = "block";
+    } else {
+        shoppingCart.style.display = "none";
+    }
+});
+
+buttonGoodDelete.onclick = () => {
+    store.dispatch(actionCartClear());
+    let a = document.getElementById("divToCartBlock");
+    a.innerHTML = "";
+    let b = document.getElementById("shoppingCart");
+    b.innerHTML = "Cart";
+    let c = document.getElementById("buttonBuy");
+    c.style.display = "none";
+};
+
+const goodByIdName = document.createElement("div");
+
+const h2text = document.createElement("h2");
+h2text.id = "h2text";
+qwer.append(h2text);
+const logoutButton = document.createElement("button");
+logoutButton.id = "logoutButton";
+qwer.append(logoutButton);
+
+store.subscribe(() => {
+    const payload = store.getState().auth.token;
+    if (payload) {
+        logoutButton.style.display = "block";
+        logoutButton.innerHTML = "Logout";
+        login.style.display = "none";
+        reg.style.display = "none";
+
+        h2text.style.display = "block";
+
+        h2text.innerText = jwtDecode(payload).sub.login;
+    } else {
+        h2text.style.display = "none";
+        logoutButton.style.display = "none";
+    }
+});
+
+// store.subscribe(() => {
+//     const orders = store.dispatch()
+
+// })
+
+const buttonLogin = document.createElement("button");
+buttonLogin.id = "loginInputt";
+buttonLogin.innerText = "Login";
+
+const buttonReg = document.createElement("button");
+buttonReg.id = "regInput";
+buttonReg.innerText = "Registration";
+
+function bPopupCreate(text) {
+    const bPopup = document.createElement("div");
+    const bPopupContent = document.createElement("div");
+    bPopup.id = "b-popup";
+    bPopup.className = "b-popup";
+    bPopupContent.className = "b-popup-content b-poput-container-flex";
+    header.append(bPopup);
+    bPopup.append(bPopupContent);
+    const buttonCloseCart = document.createElement("button");
+    buttonCloseCart.innerText = `×`;
+    buttonCloseCart.id = "buttonCloseCartId";
+    bPopupContent.append(buttonCloseCart);
+
+    const loginText = document.createElement("h2");
+    const passwordText = document.createElement("h2");
+    loginText.innerText = "Enter Login:";
+    bPopupContent.append(loginText);
+    const loginInput = document.createElement("input");
+    loginInput.type = "text";
+    bPopupContent.append(loginInput);
+    loginInput.id = "loginInput";
+    loginInput.value = "illiaKozyr";
+    passwordText.innerText = "Enter Password:";
+    bPopupContent.append(passwordText);
+    const loginInputPassword = document.createElement("input");
+    loginInputPassword.type = "password";
+    bPopupContent.append(loginInputPassword);
+    loginInputPassword.id = "passwordInput";
+    loginInputPassword.value = "qwerty123456";
+    bPopupContent.append(text);
+
+    buttonCloseCart.onclick = () => {
+        var parent = document.getElementById("header");
+        var child = document.getElementById("b-popup");
+        parent.removeChild(child);
+    };
+}
+
+window.onhashchange = () => {
+    const [, route, _id] = location.hash.split("/");
+
+    const routes = {
+        category() {
+            store.dispatch(actionCatById(_id));
+        },
+        good() {
+            store.dispatch(actionGoodById(_id));
+        },
+        dashboard() {
+            store.dispatch(orderHistory());
+        },
+    };
+
+    if (route in routes) {
+        routes[route]();
+    }
+};
+
+window.onhashchange();
+
+store.dispatch(orderHistory());
+const h2 = document.createElement("h2");
+store.subscribe(() => {
+    const { history } = store.getState().promise;
+    const [, route] = location.hash.split("/");
+    purchaseHistory.onclick = () => {
+        const bPopup = document.createElement("div");
+        const bPopupContent = document.createElement("div");
+        bPopup.id = "b-popup";
+        bPopup.className = "b-popup";
+        bPopupContent.className = "b-popup-content b-poput-container-flex";
+        header.append(bPopup);
+        bPopup.append(bPopupContent);
+        const buttonCloseCart = document.createElement("button");
+        buttonCloseCart.innerText = `×`;
+        buttonCloseCart.id = "buttonCloseCartId";
+        bPopupContent.append(buttonCloseCart);
+
+        for (let [key, value] of Object.entries(history.payload)) {
+            const { _id, createdAt, total, orderGoods } = value;
+            const historyDiv = document.createElement("div")
+            historyDiv.style = 'padding-right: 100px'
+            bPopupContent.append(historyDiv)
+            const card      = document.createElement('div')
+            card.style     = 'width: 100%;border-style: groove;border-color: #black;padding: 10px;border-radius: 10px;margin: 5px;' 
+            card.innerHTML = `<h3>Order: ${createdAt}</h3>`
+            for (const {count, good} of orderGoods){{ _id, name, price, images }}
+                const divGood      = document.createElement('div')
+                divGood.style= "display:flex;margin-bottom: 20px;"
+                
+                divGood.innerHTML += `<div>Product: <b>${good.name}</b><br> Price: <b>${good.price}</b><br> Count: <b>${count} </b></b></div><img style="max-width: 80px;margin-right: 20px;display: block;margin-left: auto;" src="http://shop-roles.node.ed.asmer.org.ua/${good.images[0].url}"/><br><br>`
+                card.append(divGood)
+            }
+            card.innerHTML += 'Date: <b>'+new Date(+createdAt).toLocaleString().replace(/\//g, '.')+'</b>'
+            card.innerHTML += `<br>Total: <b style="color:red;">${total}</b>`
+            historyDiv.append(card)
+            
+        }
+
+        if (Object.keys(history.payload).length == 0) {
+            const p = document.createElement("p");
+            p.innerHTML = "<p>No purchases made yet</p>";
+            card.append(p);
+        }
+
+        buttonCloseCart.onclick = () => {
+            var parent = document.getElementById("header");
+            var child = document.getElementById("b-popup");
+            parent.removeChild(child);
+        };
+    });
+
+login.onclick = () => {
+    bPopupCreate(buttonLogin);
+    buttonLogin.onclick = () => {
+        store.dispatch(actionFullLogin(loginInput.value, passwordInput.value));
+        logoutButton.style.display = "block";
+
+        var parent = document.getElementById("header");
+        var child = document.getElementById("b-popup");
+        parent.removeChild(child);
+        purchaseHistory.style.display = "block";
+    };
+};
+
+reg.onclick = () => {
+    bPopupCreate(buttonReg);
+    buttonReg.onclick = () => {
+        store.dispatch(
+            actionFullRegister(loginInput.value, passwordInput.value),
+            store.dispatch(actionCartClear())
+        );
+        var parent = document.getElementById("header");
+        var child = document.getElementById("b-popup");
+        parent.removeChild(child);
+    };
+};
+
+logoutButton.onclick = () => {
+    store.dispatch(actionAuthLogout());
+    login.style.display = "block";
+    reg.style.display = "block";
+    purchaseHistory.style.display = "none";
+};
+
+

+ 319 - 0
Market GraphQL + Redux project/style.css

@@ -0,0 +1,319 @@
+body {
+    margin: 0;
+    background-color: aqua;
+}
+header {
+    display: flex;
+    justify-content: space-between;
+    background-color: yellow;
+    height: 100px;
+    max-width: 1800px;
+}
+.qwer {
+    display: flex;
+    align-items: center;
+}
+button {
+    height: 50px;
+    width: 150px;
+    margin-right: 30px;
+    background-color: aqua;
+    border-radius: 15px;
+    color: darkblue;
+    font-size: 20px;
+}
+
+button:hover {
+    transition: 300ms;
+    background-color: aliceblue;
+}
+
+input {
+    height: 20px;
+    width: 100px;
+    margin-right: 30px;
+    border-radius: 15px;
+    padding-left: 10px;
+}
+.mainBlock {
+    background-color: aquamarine;
+    width: 1500px;
+    min-height: 2000px;
+    padding-left: 30px;
+}
+#mainContainer {
+    display: flex;
+}
+#aside {
+    padding: 20px 20px 20px 20px;
+    width: 30%;
+    width: 300px;
+}
+#aside > a {
+    display: block;
+}
+a,
+p {
+    font-size: 30px;
+    text-decoration: none;
+}
+a {
+    color: black;
+}
+a:hover {
+    opacity: 0.5;
+}
+
+#main {
+    font-size: 30px;
+}
+
+.cartIcon {
+    padding: 10px 0 0 20px;
+    height: 80px;
+}
+
+#productPicture {
+    width: 200px;
+}
+
+#productBlock {
+    display: flex;
+    flex-wrap: wrap;
+}
+
+#productBlock img {
+    width: 300px;
+    height: 300px;
+}
+
+#productBlock h2 {
+    margin-top: 60px;
+}
+
+#flexBlockForGFO div button {
+    margin-left: 30px;
+}
+
+#productBlock p,
+#productBlock h2{
+    
+    margin-left:  30px;
+}
+
+#productBlock #goodOneImg {
+    padding-top: 30px;
+    width: 500px;
+    height: 500px;
+}
+
+#flexBlockForGFO { 
+    display: flex;
+}
+
+#productBlock a:hover {
+    opacity: 0.8;
+}
+
+#subCategories {
+    margin: 0 30px 30px 0
+}
+
+.card {
+    display: flex;
+    margin-bottom: 30px;
+}
+
+.card div {
+    padding: 40px;
+    border-bottom: 2px solid black;
+    border-right: 2px solid black;
+    border-top: 2px solid black;
+    min-width: 1030px;
+}
+
+#flexBlock {
+    display: flex;
+    padding-top: 30px;
+}
+
+#textBlock {
+    padding-left: 30px;
+}
+
+flexBlock img {
+    height: 400px;
+    width: 400px;
+}
+
+#h2text {
+    padding-right: 30px;
+}
+
+.b-container {
+    width: 200px;
+    height: 150px;
+    background-color: #ccc;
+    margin: 0px auto;
+    padding: 10px;
+    font-size: 30px;
+    color: #fff;
+    
+}
+.b-popup {
+    width: 100%;
+    min-height: 100%;
+    background-color: rgba(0, 0, 0, 0.5);
+    overflow: hidden;
+    position: fixed;
+    top: 0px;
+}
+.b-popup .b-popup-content {
+    margin: 40px auto 0px auto;
+    width: 1000px;
+    min-height: 500px;
+    padding: 10px;
+    background-color: yellow;
+    border-radius: 5px;
+    box-shadow: 0px 0px 10px #000;
+}
+
+.b-popup-content {
+    padding: 300px;
+    display: flex;
+
+    flex-direction: column;
+}
+
+#divToCart {
+    align-items: center;
+    padding: 30px;
+    display: flex;
+    width: 700px;
+}
+
+#divToCart img {
+    max-width: 100px;
+    max-height: 100px;
+}
+
+#divToCart img,
+#divToCart h2 {
+    margin-right: 30px;
+}
+#divToCart h2 {
+    align-items: center;
+}
+
+.b-popup-content button {
+    width: 30px;
+    height: 30px;
+    margin: 0;
+}
+
+#buttonCloseCartId {
+    position: absolute;
+    top: 70px;
+    right: 420px;
+}
+
+#buttonDelete {
+    width: 100px;
+    position: absolute;
+    top: 70px;
+    right: 500px;
+}
+
+.b-poput-container-flex {
+    justify-content: center;
+}
+
+.b-poput-container-flex input {
+    margin-bottom: 30px;
+    width: 300px;
+    height: 40px;
+    font-size: 20px;
+    margin: 20px auto;
+    text-align: center;
+}
+
+.b-poput-container-flex h2 {
+    margin: 10px auto;
+}
+
+.b-poput-container-flex #buttonCloseCartId {
+    bottom: 910px;
+}
+
+#regInput,
+#loginInputt {
+    width: 150px;
+    height: 50px;
+    margin: 10px auto;
+}
+
+.addToCartButton {
+    font-size: 14px;
+}
+
+#buttonPlus,
+#buttonMinus {
+    margin-right: 10px;
+}
+
+#pCount {
+    border-radius: 50%;
+    background-color: red;
+    width: 10px;
+    height: 10px;
+    font-size: 14px;
+}
+
+.buyBlock {
+    display: flex;
+    align-items: center;
+    justify-content: end;
+}
+
+.buyBlock button {
+    width: 150px;
+    height: 50px;
+    margin: 0 30px 0 30px;
+}
+.h2History {
+    font-size: 14px;
+}
+
+.linkCard { 
+    border: 2px solid darkblue;
+    background-color: aqua;
+    color: darkblue;
+    border-radius: 15px;
+    padding: 12px;
+    margin-left: 30px;
+    font-size: 20px;
+}
+
+.card div button {
+    margin-left: 20px;
+    border-radius: 15px;
+}
+
+.footer {
+    padding-top: 20px;
+    color: white;
+    min-height: 80px;
+    background-color: tomato;
+    text-align: center;
+
+
+}
+
+.b-popup-content::-webkit-scrollbar{
+    width: 0px;
+    height: 0px;
+  }
+
+#removePosition {
+    width: 100px;
+}

BIN
React HW/.DS_Store


+ 23 - 0
React HW/HW/.gitignore

@@ -0,0 +1,23 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*

+ 70 - 0
React HW/HW/README.md

@@ -0,0 +1,70 @@
+# Getting Started with Create React App
+
+This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
+
+## Available Scripts
+
+In the project directory, you can run:
+
+### `npm start`
+
+Runs the app in the development mode.\
+Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
+
+The page will reload when you make changes.\
+You may also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.\
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
+
+### `npm run build`
+
+Builds the app for production to the `build` folder.\
+It correctly bundles React in production mode and optimizes the build for the best performance.
+
+The build is minified and the filenames include the hashes.\
+Your app is ready to be deployed!
+
+See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can't go back!**
+
+If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
+
+Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
+
+You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
+
+## Learn More
+
+You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
+
+To learn React, check out the [React documentation](https://reactjs.org/).
+
+### Code Splitting
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
+
+### Analyzing the Bundle Size
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
+
+### Making a Progressive Web App
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
+
+### Advanced Configuration
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
+
+### Deployment
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
+
+### `npm run build` fails to minify
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

File diff suppressed because it is too large
+ 28700 - 0
React HW/HW/package-lock.json


+ 38 - 0
React HW/HW/package.json

@@ -0,0 +1,38 @@
+{
+  "name": "hw",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.16.5",
+    "@testing-library/react": "^13.3.0",
+    "@testing-library/user-event": "^13.5.0",
+    "react": "^18.2.0",
+    "react-dom": "^18.2.0",
+    "react-scripts": "5.0.1",
+    "web-vitals": "^2.1.4"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": [
+      "react-app",
+      "react-app/jest"
+    ]
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  }
+}

BIN
React HW/HW/public/favicon.ico


+ 43 - 0
React HW/HW/public/index.html

@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="theme-color" content="#000000" />
+    <meta
+      name="description"
+      content="Web site created using create-react-app"
+    />
+    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+    <!--
+      manifest.json provides metadata used when your web app is installed on a
+      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
+    -->
+    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+    <!--
+      Notice the use of %PUBLIC_URL% in the tags above.
+      It will be replaced with the URL of the `public` folder during the build.
+      Only files inside the `public` folder can be referenced from the HTML.
+
+      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+      work correctly both with client-side routing and a non-root public URL.
+      Learn how to configure a non-root public URL by running `npm run build`.
+    -->
+    <title>React App</title>
+  </head>
+  <body>
+    <noscript>You need to enable JavaScript to run this app.</noscript>
+    <div id="root"></div>
+    <!--
+      This HTML file is a template.
+      If you open it directly in the browser, you will see an empty page.
+
+      You can add webfonts, meta tags, or analytics to this file.
+      The build step will place the bundled scripts into the <body> tag.
+
+      To begin the development, run `npm start` or `yarn start`.
+      To create a production bundle, use `npm run build` or `yarn build`.
+    -->
+  </body>
+</html>

BIN
React HW/HW/public/logo192.png


BIN
React HW/HW/public/logo512.png


+ 25 - 0
React HW/HW/public/manifest.json

@@ -0,0 +1,25 @@
+{
+  "short_name": "React App",
+  "name": "Create React App Sample",
+  "icons": [
+    {
+      "src": "favicon.ico",
+      "sizes": "64x64 32x32 24x24 16x16",
+      "type": "image/x-icon"
+    },
+    {
+      "src": "logo192.png",
+      "type": "image/png",
+      "sizes": "192x192"
+    },
+    {
+      "src": "logo512.png",
+      "type": "image/png",
+      "sizes": "512x512"
+    }
+  ],
+  "start_url": ".",
+  "display": "standalone",
+  "theme_color": "#000000",
+  "background_color": "#ffffff"
+}

+ 3 - 0
React HW/HW/public/robots.txt

@@ -0,0 +1,3 @@
+# https://www.robotstxt.org/robotstxt.html
+User-agent: *
+Disallow:

+ 119 - 0
React HW/HW/src/App.css

@@ -0,0 +1,119 @@
+.App {
+  display: flex;
+  flex-wrap: wrap;
+  max-width: 1250px;
+  margin: 0 auto;
+}
+
+.formBlock {
+    max-width: 2000px;
+    padding: 20px;
+    display: flex;
+    align-items: center;
+    flex-direction: column;
+    padding: 40px;
+}
+
+#aside,
+.cardBlock {
+  padding: 40px;
+}
+
+input {
+    width: 300px;
+    margin-bottom: 20px;
+    border-radius: 15px;
+    padding: 15px;
+    background-color: orange;
+    color: black;
+}
+
+button  {
+    width: 150px;
+    border-radius: 15px;
+    padding: 15px;
+    color: black;
+    cursor: pointer;
+}
+
+
+
+h2 {
+  color: orange;
+}
+
+.card h3,
+.card h4 {
+  color: olivedrab;
+}
+
+.Spoiler  {
+  text-align: center;
+}
+
+
+.Spoiler {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.Spoiler {
+  color: #61dafb;
+}
+
+
+.error{
+    background-color: red;
+}
+
+input{
+  outline: none;
+}
+
+.PasswordConfirmWrapper{
+  display: flex;
+  flex-direction: column;
+  width: 25%;
+}
+
+h3 {
+  width: 100%;
+}
+
+
+
+input{
+  outline: none;
+}
+
+span {
+  border: 2px solid black;
+  margin: 50px 0 50px 0;;
+  width: 50px;
+  height: 50px;
+  padding: 5px 10px;
+  background-color: #61dafb;
+}
+
+.block{
+  margin: 30px 0 30px 0;
+}
+
+.spoilerBlock {
+  margin: 30px 0;
+}
+
+.blockTimer{
+  margin: 40px;
+}
+
+button {
+  margin-bottom: 30px;
+}
+

+ 26 - 0
React HW/HW/src/App.js

@@ -0,0 +1,26 @@
+import logo from "./logo.svg";
+import "./App.css";
+import SpoilerParent from "./components/Spoiler";
+import RangeInputParent from "./components/RangeInput";
+import PasswordConfirmParent from "./components/Password";
+
+import TimerParent from "./components/TimerParent";
+import TimerControl from './components/TimerControl'
+
+function App() {
+    return (
+        <div className="App">
+            <SpoilerParent></SpoilerParent>
+            <div className="block">
+                <RangeInputParent></RangeInputParent>
+                <PasswordConfirmParent></PasswordConfirmParent>
+            </div>
+            <div className="blockTimer">
+                <TimerParent></TimerParent>
+                <TimerControl></TimerControl>
+            </div>
+        </div>
+    );
+}
+
+export default App;

+ 8 - 0
React HW/HW/src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

+ 58 - 0
React HW/HW/src/components/Password.jsx

@@ -0,0 +1,58 @@
+import React from "react";
+
+class PasswordConfirm extends React.Component {
+    constructor(props) {
+        super(props);
+        this.state = {
+            password: "",
+            passwordConfirm: "",
+        };
+    }
+
+    inputChange = (e) => {
+        this.setState({ [e.target.name]: e.target.value });
+    };
+
+    render() {
+        const { min } = this.props;
+        const arePasswordsEqual =
+            this.state.password === this.state.passwordConfirm;
+        const hasErrorPsw =
+            this.state.password.length < min || !arePasswordsEqual;
+        const hasErrorPswConfirm =
+            this.state.passwordConfirm.length < min || !arePasswordsEqual;
+
+        return (
+            <div className="PasswordConfirmWrapper">
+                <h3>Enter Password:</h3>
+                <input
+                    placeholder={"password"}
+                    name={"password"}
+                    type={"password"}
+                    className={hasErrorPsw ? "error" : ""}
+                    onChange={this.inputChange}
+                />
+                <h3>Enter Password Again:</h3>
+                <input
+                    placeholder={"confirm password"}
+                    name={"passwordConfirm"}
+                    type={"password"}
+                    className={hasErrorPswConfirm ? "error" : ""}
+                    onChange={this.inputChange}
+                />
+            </div>
+        );
+    }
+}
+
+class PasswordConfirmParent extends React.Component {
+    render() {
+        return (
+            <div>
+                <PasswordConfirm min={2} />
+            </div>
+        );
+    }
+}
+
+export default PasswordConfirmParent;

+ 32 - 0
React HW/HW/src/components/RangeInput.jsx

@@ -0,0 +1,32 @@
+import React from "react";
+
+class RangeInput extends React.Component {
+    constructor(props) {
+        super(props);
+        this.state = {
+            value: '',
+        };
+    }
+
+    inputChange = (e) => {
+        this.setState({value: e.target.value});
+    };
+
+    render() {
+        const {min, max} = this.props;
+        const hasError = this.state.value.length > max || this.state.value.length < min;
+        return (
+            <div>
+                <input onChange={this.inputChange} className={hasError ? 'error' : ''}/>
+            </div>
+        );
+    }
+}
+
+const RangeInputParent = () => {
+    return(
+        <RangeInput min={2} max={10} />
+    )
+ }
+
+export default RangeInputParent

+ 46 - 0
React HW/HW/src/components/Spoiler.jsx

@@ -0,0 +1,46 @@
+import React, { useState } from "react";
+
+const Spoiler = ({ header = "click me", open, children }) => {
+    const [isOpen, setIsOpen] = useState(open);
+
+    return (
+        <div>
+            <div
+                onClick={() => {
+                    setIsOpen(!isOpen);
+                }}
+            >
+                <span>{header}</span>
+                {isOpen && <div>{children}</div>}
+            </div>
+        </div>
+    );
+};
+
+const SpoilerParent = () => {
+    return (
+        <div>
+            <div className="header">
+                Контент 1
+                <p>
+                    лорем ипсум траливали и тп.лорем ипсум траливали и тп.лорем
+                    ипсум траливали и тп.лорем ипсум траливали и тп.лорем ипсум
+                    траливали и тп.
+                </p>
+            </div>
+
+            <Spoiler>
+                <div className="spoilerBlock">
+                    Контент 2
+                    <p>
+                        лорем ипсум траливали и тп.лорем ипсум траливали и
+                        тп.лорем ипсум траливали и тп.лорем ипсум траливали и
+                        тп.лорем ипсум траливали и тп.
+                    </p>
+                </div>
+            </Spoiler>
+        </div>
+    );
+};
+
+export default SpoilerParent;

+ 44 - 0
React HW/HW/src/components/Timer.jsx

@@ -0,0 +1,44 @@
+import {useState, useEffect} from 'react';
+
+function Timer({sec}) {
+    const [count, setCount] = useState(sec);
+    const [isPaused, setIsPaused] = useState(false);
+    useEffect(() => {
+        let timer;
+
+        if (count > 0 && isPaused === false) {
+            timer = setTimeout(() => setCount(count - 1), 1000);
+        }
+
+        return () => {
+            clearTimeout(timer);
+        };
+    }, [count, isPaused]);
+
+    useEffect(() => {
+        setCount(sec);
+    }, [sec]);
+
+    const onBtnPauseClick = () => {
+        setIsPaused(!isPaused);
+    };
+
+    const h = Math.floor(count / 3600);
+    const s = count % 60;
+    const min = Math.floor(count % 3600 / 60);
+
+    return (
+        <div>
+            <div>{h < 10 ? '0' + h : h}:{min < 10 ? '0' + min : min}:{s < 10 ? '0' + s : s}</div>
+            <button
+                className="buttonForTimer"
+                onClick={onBtnPauseClick}>
+                {isPaused ? 'Resume' : 'Pause'}
+            </button>
+        </div>
+    );
+
+
+}
+
+export default Timer;

+ 74 - 0
React HW/HW/src/components/TimerControl.jsx

@@ -0,0 +1,74 @@
+import { useState, useEffect } from "react";
+
+function Timer({sec}) {
+    const [count, setCount] = useState(sec);
+    const [isPaused, setIsPaused] = useState(false);
+    useEffect(() => {
+        let timer;
+
+        if (count > 0 && isPaused === true) {
+            timer = setTimeout(() => setCount(count - 1), 1000);
+        }
+
+        return () => {
+            clearTimeout(timer);
+        };
+    }, [count, isPaused]);
+
+    useEffect(() => {
+        setCount(sec);
+    }, [sec]);
+
+    const onBtnPauseClick = () => {
+        setIsPaused(!isPaused);
+    };
+
+    const h = Math.floor(count / 3600);
+    const s = count % 60;
+    const min = Math.floor(count % 3600 / 60);
+
+    return (
+        <div>
+            <div>{h < 10 ? '0' + h : h}:{min < 10 ? '0' + min : min}:{s < 10 ? '0' + s : s}</div>
+            <button
+                className="buttonForTimer"
+                onClick={onBtnPauseClick}>
+                {isPaused ? 'Pause' : 'Start'}
+            </button>
+        </div>
+    );
+
+
+}
+
+function TimerControle() {
+    const [sec, setSec] = useState(0);
+    const [min, setMin] = useState(0);
+    const [hours, setHours] = useState(0);
+
+    return (
+        <div>
+            <input
+                name="hours"
+                type="number"
+                placeholder="Часы"
+                onChange={(e) => setHours(+e.target.value)}
+            />
+            <input
+                name="minutes"
+                type="number"
+                placeholder="Минуты"
+                onChange={(e) => setMin(+e.target.value)}
+            />
+            <input
+                name="sec"
+                type="number"
+                placeholder="Секунды"
+                onChange={(e) => setSec(+e.target.value)}
+            />
+            <Timer sec={hours * 3600 + min * 60 + sec} />
+        </div>
+    );
+}
+
+export default TimerControle;

+ 11 - 0
React HW/HW/src/components/TimerParent.jsx

@@ -0,0 +1,11 @@
+import Timer from "./Timer"
+
+const TimerParent = () => {
+    return(
+        <div>
+            <Timer sec={60}/>
+        </div>
+    )
+}
+
+export default TimerParent;

+ 13 - 0
React HW/HW/src/index.css

@@ -0,0 +1,13 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}

+ 17 - 0
React HW/HW/src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();

File diff suppressed because it is too large
+ 1 - 0
React HW/HW/src/logo.svg


+ 13 - 0
React HW/HW/src/reportWebVitals.js

@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;

+ 5 - 0
React HW/HW/src/setupTests.js

@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';

+ 23 - 0
React HW/at a lecture/.gitignore

@@ -0,0 +1,23 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*

+ 70 - 0
React HW/at a lecture/README.md

@@ -0,0 +1,70 @@
+# Getting Started with Create React App
+
+This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
+
+## Available Scripts
+
+In the project directory, you can run:
+
+### `npm start`
+
+Runs the app in the development mode.\
+Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
+
+The page will reload when you make changes.\
+You may also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.\
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
+
+### `npm run build`
+
+Builds the app for production to the `build` folder.\
+It correctly bundles React in production mode and optimizes the build for the best performance.
+
+The build is minified and the filenames include the hashes.\
+Your app is ready to be deployed!
+
+See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can't go back!**
+
+If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
+
+Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
+
+You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
+
+## Learn More
+
+You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
+
+To learn React, check out the [React documentation](https://reactjs.org/).
+
+### Code Splitting
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
+
+### Analyzing the Bundle Size
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
+
+### Making a Progressive Web App
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
+
+### Advanced Configuration
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
+
+### Deployment
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
+
+### `npm run build` fails to minify
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

File diff suppressed because it is too large
+ 28836 - 0
React HW/at a lecture/package-lock.json


+ 41 - 0
React HW/at a lecture/package.json

@@ -0,0 +1,41 @@
+{
+  "name": "my-app",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.16.5",
+    "@testing-library/react": "^13.3.0",
+    "@testing-library/user-event": "^13.5.0",
+    "react": "^18.2.0",
+    "react-dom": "^18.2.0",
+    "react-redux": "^8.0.2",
+    "react-scripts": "5.0.1",
+    "redux": "^4.2.0",
+    "redux-thunk": "^2.4.1",
+    "web-vitals": "^2.1.4"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": [
+      "react-app",
+      "react-app/jest"
+    ]
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  }
+}

BIN
React HW/at a lecture/public/favicon.ico


+ 43 - 0
React HW/at a lecture/public/index.html

@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="theme-color" content="#000000" />
+    <meta
+      name="description"
+      content="Web site created using create-react-app"
+    />
+    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+    <!--
+      manifest.json provides metadata used when your web app is installed on a
+      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
+    -->
+    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+    <!--
+      Notice the use of %PUBLIC_URL% in the tags above.
+      It will be replaced with the URL of the `public` folder during the build.
+      Only files inside the `public` folder can be referenced from the HTML.
+
+      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+      work correctly both with client-side routing and a non-root public URL.
+      Learn how to configure a non-root public URL by running `npm run build`.
+    -->
+    <title>React App</title>
+  </head>
+  <body>
+    <noscript>You need to enable JavaScript to run this app.</noscript>
+    <div id="root"></div>
+    <!--
+      This HTML file is a template.
+      If you open it directly in the browser, you will see an empty page.
+
+      You can add webfonts, meta tags, or analytics to this file.
+      The build step will place the bundled scripts into the <body> tag.
+
+      To begin the development, run `npm start` or `yarn start`.
+      To create a production bundle, use `npm run build` or `yarn build`.
+    -->
+  </body>
+</html>

BIN
React HW/at a lecture/public/logo192.png


BIN
React HW/at a lecture/public/logo512.png


+ 25 - 0
React HW/at a lecture/public/manifest.json

@@ -0,0 +1,25 @@
+{
+  "short_name": "React App",
+  "name": "Create React App Sample",
+  "icons": [
+    {
+      "src": "favicon.ico",
+      "sizes": "64x64 32x32 24x24 16x16",
+      "type": "image/x-icon"
+    },
+    {
+      "src": "logo192.png",
+      "type": "image/png",
+      "sizes": "192x192"
+    },
+    {
+      "src": "logo512.png",
+      "type": "image/png",
+      "sizes": "512x512"
+    }
+  ],
+  "start_url": ".",
+  "display": "standalone",
+  "theme_color": "#000000",
+  "background_color": "#ffffff"
+}

+ 3 - 0
React HW/at a lecture/public/robots.txt

@@ -0,0 +1,3 @@
+# https://www.robotstxt.org/robotstxt.html
+User-agent: *
+Disallow:

+ 89 - 0
React HW/at a lecture/src/App.css

@@ -0,0 +1,89 @@
+.App {
+  display: flex;
+  flex-wrap: wrap;
+  max-width: 1250px;
+  margin: 0 auto;
+}
+
+.formBlock {
+    max-width: 2000px;
+    padding: 20px;
+    display: flex;
+    align-items: center;
+    flex-direction: column;
+    padding: 40px;
+}
+
+#aside,
+.cardBlock {
+  padding: 40px;
+}
+
+input {
+    width: 300px;
+    margin-bottom: 20px;
+    border-radius: 15px;
+    padding: 15px;
+    background-color: orange;
+    color: black;
+}
+
+button  {
+    width: 150px;
+    border-radius: 15px;
+    padding: 15px;
+    color: black;
+    cursor: pointer;
+}
+
+
+
+h2 {
+  color: orange;
+}
+
+.card h3,
+.card h4 {
+  color: olivedrab;
+}
+
+.Spoiler  {
+  text-align: center;
+}
+
+
+.Spoiler {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.Spoiler {
+  color: #61dafb;
+}
+
+
+.error{
+    background-color: red;
+}
+
+input{
+  outline: none;
+}
+
+.PasswordConfirmWrapper{
+  display: flex;
+  flex-direction: column;
+  width: 25%;
+}
+
+
+
+input{
+  outline: none;
+}

+ 613 - 0
React HW/at a lecture/src/App.js

@@ -0,0 +1,613 @@
+import logo from "./logo.svg";
+import React, { useState } from "react";
+import "./App.css";
+
+import thunk from "redux-thunk";
+import { createStore, combineReducers, applyMiddleware } from "redux";
+import { Provider, connect } from "react-redux";
+
+const store = createStore(
+    combineReducers({
+        auth: authReducer,
+        promise: promiseReducer,
+        cart: localStoreReducer(cartReducer, "cart"),
+    }),
+    applyMiddleware(thunk)
+);
+
+function jwtDecode(token) {
+    try {
+        return JSON.parse(atob(token.split(".")[1]));
+    } catch (e) {}
+}
+
+const getGQL = (url) => (query, variables) =>
+    fetch(url, {
+        method: "POST",
+        headers: {
+            "Content-Type": "application/json",
+            // 'Accept' : 'application/json',
+            ...(localStorage.authToken
+                ? { Authorization: "Bearer " + localStorage.authToken }
+                : {}),
+        },
+        body: JSON.stringify({ query, variables }),
+    })
+        .then((res) => res.json())
+        .then((data) => {
+            if (data.data) {
+                return Object.values(data.data)[0];
+            } else throw new Error(JSON.stringify(data.errors));
+        });
+
+const backendURL = "http://shop-roles.node.ed.asmer.org.ua";
+const gql = getGQL(backendURL + "/graphql");
+
+function authReducer(state, { type, token }) {
+    if (state === undefined) {
+        if (localStorage.authToken) {
+            type = "AUTH_LOGIN";
+            token = localStorage.authToken;
+        }
+    }
+    if (type === "AUTH_LOGIN") {
+        let payload = jwtDecode(token);
+        if (payload) {
+            localStorage.authToken = token;
+            return { token, payload };
+        }
+    }
+    if (type === "AUTH_LOGOUT") {
+        localStorage.removeItem("authToken");
+        return {};
+    }
+    return state || {};
+}
+
+const actionAuthLogin = (token) => ({ type: "AUTH_LOGIN", token });
+
+const actionAuthLogout = () => (dispatch) => {
+    dispatch({ type: "AUTH_LOGOUT" });
+    localStorage.removeItem("authToken");
+};
+
+function promiseReducer(state = {}, { type, name, status, payload, error }) {
+    if (type === "PROMISE") {
+        return {
+            ...state,
+            [name]: { status, payload, error },
+        };
+    }
+    return state;
+}
+
+const actionPending = (name) => ({
+    type: "PROMISE",
+    status: "PENDING",
+    name,
+});
+const actionFulfilled = (name, payload) => ({
+    type: "PROMISE",
+    status: "FULFILLED",
+    name,
+    payload,
+});
+const actionRejected = (name, error) => ({
+    type: "PROMISE",
+    status: "REJECTED",
+    name,
+    error,
+});
+
+const actionPromise = (name, promise) => async (dispatch) => {
+    try {
+        dispatch(actionPending(name));
+        let payload = await promise;
+        dispatch(actionFulfilled(name, payload));
+        return payload;
+    } catch (e) {
+        dispatch(actionRejected(name, e));
+    }
+};
+
+function cartReducer(state = {}, { type, count = 1, good }) {
+    if (type === "CART_ADD") {
+        return {
+            ...state,
+            [good._id]: { count: count + (state[good._id]?.count || 0), good },
+        };
+    }
+
+    if (type === "CART_DELETE") {
+        if (state[good._id].count > 1) {
+            return {
+                ...state,
+                [good._id]: {
+                    count: -count + (state[good._id]?.count || 0),
+                    good,
+                },
+            };
+        }
+
+        if (state[good._id].count === 1) {
+            let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
+            //delete newState[good._id]
+            return newState;
+        }
+    }
+
+    if (type === "CART_CLEAR") {
+        return {};
+    }
+    if (type === "CART_REMOVE") {
+        // let newState = {...state}
+        let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
+        //delete newState[good._id]
+        return newState;
+    }
+
+    return state;
+}
+
+const actionCartAdd = (good, count = 1) => ({ type: "CART_ADD", good, count });
+const actionCartDelete = (good) => ({ type: "CART_DELETE", good });
+const actionCartClear = () => ({ type: "CART_CLEAR" });
+const actionCartRemove = (good) => ({ type: "CART_REMOVE", good });
+
+function localStoreReducer(reducer, localStorageKey) {
+    function localStoredReducer(state, action) {
+        // Если state === undefined, то достать старый state из local storage
+        if (state === undefined) {
+            try {
+                return JSON.parse(localStorage[localStorageKey]);
+            } catch (e) {}
+        }
+        const newState = reducer(state, action);
+        // Сохранить newState в local storage
+        localStorage[localStorageKey] = JSON.stringify(newState);
+        return newState;
+    }
+    return localStoredReducer;
+}
+
+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 subCategories {
+    name _id
+}
+goods {
+    _id name price images {
+        url
+    }
+}
+}
+}`,
+            { q: JSON.stringify([{ _id }]) }
+        )
+    );
+
+const actionLogin = (login, password) =>
+    actionPromise(
+        "actionLogin",
+        gql(
+            `query log($login:String, $password:String){
+                                  login(login:$login, password:$password)
+                                }`,
+            { login, password }
+        )
+    );
+
+const actionGoodById = (_id) =>
+    actionPromise(
+        "GoodFineOne",
+        gql(
+            `query goodByid($goodId: String) {
+        GoodFindOne(query: $goodId) {
+            _id
+          name
+          price
+          description
+          images {
+            url
+          }
+        }
+      }`,
+            { goodId: JSON.stringify([{ _id }]) }
+        )
+    );
+
+store.dispatch(actionRootCats());
+store.dispatch(actionCatById("6262ca7dbf8b206433f5b3d1"));
+
+const actionFullLogin = (log, pass) => async (dispatch) => {
+    let token = await dispatch(
+        actionPromise(
+            "login",
+            gql(
+                `query login($login: String, $password: String) {
+            login(login: $login, password: $password)
+            }`,
+                { login: log, password: pass }
+            )
+        )
+    );
+    if (token) {
+        dispatch(actionAuthLogin(token));
+    }
+};
+
+const actionFullRegister = (login, password) => async (dispatch) => {
+    let user = await dispatch(
+        actionPromise(
+            "register",
+            gql(
+                `mutation register($login: String, $password: String) {
+                UserUpsert(user: {login: $login, password: $password}) {
+                   _id
+                   login
+                 }
+               }`,
+                { login: login, password: password }
+            )
+        )
+    );
+    if (user) {
+        dispatch(actionFullLogin(login, password));
+    }
+};
+
+const actionOrder = () => async (dispatch, getState) => {
+    let { cart } = getState();
+    const orderGoods = Object.entries(cart).map(([_id, { count }]) => ({
+        good: { _id },
+        count,
+    }));
+
+    let result = await dispatch(
+        actionPromise(
+            "order",
+            gql(
+                `
+                    mutation newOrder($order:OrderInput){
+                    OrderUpsert(order:$order)
+                        { _id total 	}
+                    }
+            `,
+                { order: { orderGoods } }
+            )
+        )
+    );
+    if (result?._id) {
+        dispatch(actionCartClear());
+        document.location.hash = "#/cart/";
+        alert("Purchase completed");
+    }
+};
+
+const orderHistory = () =>
+    actionPromise(
+        "history",
+        gql(` query OrderFind{
+        OrderFind(query:"[{}]"){
+            _id total createdAt orderGoods{
+                count good{
+                    _id name price images{
+                        url
+                    }
+                }
+                owner{
+                    _id login 
+                }
+            }
+        }
+    }
+    `)
+    );
+
+const LoginForm = ({ onLogin }) => {
+    const [login, setLogin] = useState("");
+    const [password, setPassword] = useState("");
+
+    const checkDisable = () => {
+        return !(login !== "" && password.match(/\w{8,30}$/));
+    };
+
+    const Authorization = () => {
+        onLogin(login, password);
+    };
+
+    return (
+        <div className="formBlock">
+            <p>Enter login:</p>
+
+            <input
+                type="text"
+                value={login}
+                onChange={(e) => setLogin(e.target.value)}
+            />
+            <p>Enter password:</p>
+            <input
+                type="password"
+                value={password}
+                onChange={(e) => setPassword(e.target.value)}
+            />
+            <button disabled={checkDisable()} onClick={Authorization}>
+                Log In
+            </button>
+        </div>
+    );
+};
+
+if (localStorage.authToken) {
+    store.dispatch(actionAuthLogin(localStorage.authToken));
+}
+
+store.subscribe(() => console.log(store.getState()));
+
+const cat = [
+    {
+        _id: "62d57ab8b74e1f5f2ec1a148",
+        name: "Motorola Razr 5G 8/256GB Graphite",
+        price: 3500,
+    },
+    {
+        _id: "62d57c4db74e1f5f2ec1a14a",
+        name: "Смартфон Google Pixel 6 Pro 12/128GB Stormy Black",
+        price: 2800,
+    },
+    {
+        _id: "62d58318b74e1f5f2ec1a14e",
+        name: "Microsoft Surface Duo 2 8GB/256GB",
+        price: 4500,
+    },
+    {
+        _id: "62d5869bb74e1f5f2ec1a150",
+        name: "Смартфон Poco F3 6/128GB EU Arctic White",
+        price: 1800,
+    },
+    {
+        _id: "62d58810b74e1f5f2ec1a152",
+        name: "Мобильный телефон Xiaomi Redmi Note 9 4G (Redmi 9t EU)",
+        price: 800,
+    },
+    {
+        _id: "62d5a7deb74e1f5f2ec1a154",
+        name: "LG V50 black REF",
+        price: 900,
+    },
+];
+
+const rootCats = [
+    {
+        name: "test3",
+    },
+    {
+        name: "Tools",
+    },
+    {
+        name: "Tomatoes",
+    },
+    {
+        name: "123",
+    },
+    {
+        name: "iPhone",
+    },
+    {
+        name: "Samsung",
+    },
+    {
+        name: "Smartphone",
+    },
+    {
+        name: "Large home appliances",
+    },
+    {
+        name: "Garden",
+    },
+    {
+        name: "Children's products",
+    },
+    {
+        name: " Hobbies and sports",
+    },
+    {
+        name: "Sale",
+    },
+];
+
+const CategoryMenu = ({rootCats = []}) => {
+    return (
+        <>
+            <aside id="aside">
+                <ul>
+                    {rootCats.map((cat) => (
+                        <CategoryMenuItem name={cat.name} />
+                    ))}
+                </ul>
+            </aside>
+        </>
+    );
+};
+
+const CCategoryMenu = connect((state) => ({rootCats: state.promise?.rootCats.payload}))(CategoryMenu)
+
+const CategoryMenuItem = ({ name }) => {
+    return (
+        <>
+            <h2>{name}</h2>
+        </>
+    );
+};
+
+const Category = ({cat = []}) => {
+    return (
+        <div className="cardBlock">
+            {cat.map((item) => (
+                <GoodCard name={item.name} price={item.price} />
+            ))}
+        </div>
+    );
+};
+
+const CCategory = connect((state) => ({cat: state.promise?.catById.payload?.goods}))(Category)
+
+const GoodCard = ({ name, price }) => {
+    return (
+        <div className="card">
+            <h3>{name}</h3>
+            <h4>{price}</h4>
+        </div>
+    );
+};
+
+const CLoginForm = connect(null, { onLogin: actionFullLogin })(LoginForm);
+
+const Spoiler = ({header = '+', open, children}) => {
+    const [isOpen, setIsOpen] = useState(open);
+
+    return (
+        <div>
+            <div onClick={() => {
+                setIsOpen(!isOpen);
+            }}>
+                <span>{header}</span>
+                {isOpen && (
+                    <div>
+                        {children}
+                    </div>
+                )}
+            </div>
+        </div>
+    );
+};
+
+const SpoilerParent = () => {
+
+    return (
+        <div>
+            <Spoiler header={<h1>Заголовок</h1>} open>
+                Контент 1
+                <p>
+                лорем ипсум траливали и тп.лорем ипсум траливали и тп.лорем ипсум траливали и тп.лорем ипсум траливали и тп.лорем ипсум траливали и тп.
+                </p>
+            </Spoiler>
+
+            <Spoiler>
+                <h2>Контент 2</h2>
+                <p>
+                лорем ипсум траливали и тп.лорем ипсум траливали и тп.лорем ипсум траливали и тп.лорем ипсум траливали и тп.лорем ипсум траливали и тп.
+                </p>
+            </Spoiler>
+        </div>
+    );
+};
+
+class RangeInput extends React.Component {
+    constructor(props) {
+        super(props);
+        this.state = {
+            value: '',
+        };
+    }
+
+    inputChange = (e) => {
+        this.setState({value: e.target.value});
+    };
+
+    render() {
+        const {min, max} = this.props;
+        const hasError = this.state.value.length > max || this.state.value.length < min;
+        return (
+            <div>
+                <input onChange={this.inputChange} className={hasError ? 'error' : ''}/>
+            </div>
+        );
+    }
+}
+
+const RangeInputParent = () => {
+    return(
+        <RangeInput min={2} max={10} />
+    )
+ }
+
+ class PasswordConfirm extends React.Component {
+    constructor(props) {
+        super(props);
+        this.state = {
+            password: '',
+            passwordConfirm: '',
+        };
+    }
+
+    inputChange = (e) => {
+        this.setState({[e.target.name]: e.target.value})
+    };
+
+    render() {
+        const {min} = this.props;
+        const arePasswordsEqual = this.state.password === this.state.passwordConfirm;
+        const hasErrorPsw = this.state.password.length < min || !arePasswordsEqual;
+        const hasErrorPswConfirm = this.state.passwordConfirm.length < min || !arePasswordsEqual;
+
+        return (
+            <div className="PasswordConfirmWrapper">
+                <input placeholder={'password'}
+                       name={'password'}
+                       type={'password'}
+                       className={hasErrorPsw ? 'error' : ''}
+                       onChange={this.inputChange}
+                />
+                <input placeholder={'confirm password'}
+                       name={'passwordConfirm'}
+                       type={'password'}
+                       className={hasErrorPswConfirm ? 'error' : ''}
+                       onChange={this.inputChange}/>
+            </div>
+        );
+    }
+}
+
+class PasswordConfirmParent extends React.Component{
+    render() {
+        return(
+            <div>
+                <PasswordConfirm min={2} />
+            </div>
+        )
+    }
+}
+
+function App() {
+    return (
+        <Provider store={store}>
+            <div className="App">
+                <SpoilerParent></SpoilerParent>
+                <RangeInputParent></RangeInputParent>
+                <PasswordConfirmParent></PasswordConfirmParent>
+                <CLoginForm />
+                <CCategoryMenu />
+                <CCategory />
+            </div>
+        </Provider>
+    );
+}
+export default App;

+ 8 - 0
React HW/at a lecture/src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

+ 13 - 0
React HW/at a lecture/src/index.css

@@ -0,0 +1,13 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}

+ 17 - 0
React HW/at a lecture/src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();

File diff suppressed because it is too large
+ 1 - 0
React HW/at a lecture/src/logo.svg


+ 13 - 0
React HW/at a lecture/src/reportWebVitals.js

@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;

+ 5 - 0
React HW/at a lecture/src/setupTests.js

@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';

+ 0 - 0
React HW/Сайт A-Level React/.DS_Store


Some files were not shown because too many files changed in this diff