From e8310ae78b2cfd33265a41af21668e7deb66a3ed Mon Sep 17 00:00:00 2001 From: Chuzhikov Danil Date: Thu, 11 Mar 2021 19:44:58 +0300 Subject: [PATCH 1/5] hw2 --- index.html | 16 ++++++++++++ script.js | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 index.html create mode 100644 script.js diff --git a/index.html b/index.html new file mode 100644 index 0000000..dd40b1b --- /dev/null +++ b/index.html @@ -0,0 +1,16 @@ + + + + eShop + + +
+ +
+
+
+
+ + + + \ No newline at end of file diff --git a/script.js b/script.js new file mode 100644 index 0000000..678fa9c --- /dev/null +++ b/script.js @@ -0,0 +1,75 @@ +class ApiMock { + constructor() { + + } + + fetch() { + return [{ + title: 'Shirt', + price: 150 + }, + { + title: 'Socks', + price: 50 + }, + { + title: 'Jacket', + price: 350 + }, + { + title: 'Shoes', + price: 250 + }, + ]; + } +} + +class GoodsItem { + constructor(title, price) { + this.title = title; + this.price = price; + } + + getHtml() { + return `

${this.title}

${this.price}

`; + } +} + +class GoodsList { + constructor() { + this.api = new ApiMock(); + this.$goodsList = document.querySelector('.goods-list'); + this.goods = []; + } + + fetchGoods() { + this.goods = this.api.fetch().map(({ + title, + price + }) => new GoodsItem(title, price)); + } + + render() { + this.$goodsList.textContent = ''; + this.goods.forEach((good) => { + this.$goodsList.insertAdjacentHTML('beforeend', good.getHtml()); + }) + } + + goodsPrice() { + return this.goods.reduce((sum, { + price + }) => sum + price, 0); + } + +} + +class Basket {} + +class ProductsInBasket {} + +const goodsList = new GoodsList(); + +goodsList.fetchGoods(); +goodsList.render(); +goodsList.goodsPrice(); \ No newline at end of file From 84933910d9dc357452e12093e0d095bb2439bd6d Mon Sep 17 00:00:00 2001 From: Chuzhikov Danil Date: Mon, 15 Mar 2021 19:30:16 +0300 Subject: [PATCH 2/5] hw3 --- css/normalize.css | 349 ++++++++++++++++++++++++++++++++++++++++++++++ css/style.css | 171 +++++++++++++++++++++++ index.html | 30 +++- js/script.js | 218 +++++++++++++++++++++++++++++ script.js | 75 ---------- 5 files changed, 762 insertions(+), 81 deletions(-) create mode 100644 css/normalize.css create mode 100644 css/style.css create mode 100644 js/script.js delete mode 100644 script.js diff --git a/css/normalize.css b/css/normalize.css new file mode 100644 index 0000000..192eb9c --- /dev/null +++ b/css/normalize.css @@ -0,0 +1,349 @@ +/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ + +/* Document + ========================================================================== */ + +/** + * 1. Correct the line height in all browsers. + * 2. Prevent adjustments of font size after orientation changes in iOS. + */ + +html { + line-height: 1.15; /* 1 */ + -webkit-text-size-adjust: 100%; /* 2 */ +} + +/* Sections + ========================================================================== */ + +/** + * Remove the margin in all browsers. + */ + +body { + margin: 0; +} + +/** + * Render the `main` element consistently in IE. + */ + +main { + display: block; +} + +/** + * Correct the font size and margin on `h1` elements within `section` and + * `article` contexts in Chrome, Firefox, and Safari. + */ + +h1 { + font-size: 2em; + margin: 0.67em 0; +} + +/* Grouping content + ========================================================================== */ + +/** + * 1. Add the correct box sizing in Firefox. + * 2. Show the overflow in Edge and IE. + */ + +hr { + box-sizing: content-box; /* 1 */ + height: 0; /* 1 */ + overflow: visible; /* 2 */ +} + +/** + * 1. Correct the inheritance and scaling of font size in all browsers. + * 2. Correct the odd `em` font sizing in all browsers. + */ + +pre { + font-family: monospace, monospace; /* 1 */ + font-size: 1em; /* 2 */ +} + +/* Text-level semantics + ========================================================================== */ + +/** + * Remove the gray background on active links in IE 10. + */ + +a { + background-color: transparent; +} + +/** + * 1. Remove the bottom border in Chrome 57- + * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari. + */ + +abbr[title] { + border-bottom: none; /* 1 */ + text-decoration: underline; /* 2 */ + text-decoration: underline dotted; /* 2 */ +} + +/** + * Add the correct font weight in Chrome, Edge, and Safari. + */ + +b, +strong { + font-weight: bolder; +} + +/** + * 1. Correct the inheritance and scaling of font size in all browsers. + * 2. Correct the odd `em` font sizing in all browsers. + */ + +code, +kbd, +samp { + font-family: monospace, monospace; /* 1 */ + font-size: 1em; /* 2 */ +} + +/** + * Add the correct font size in all browsers. + */ + +small { + font-size: 80%; +} + +/** + * Prevent `sub` and `sup` elements from affecting the line height in + * all browsers. + */ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +/* Embedded content + ========================================================================== */ + +/** + * Remove the border on images inside links in IE 10. + */ + +img { + border-style: none; +} + +/* Forms + ========================================================================== */ + +/** + * 1. Change the font styles in all browsers. + * 2. Remove the margin in Firefox and Safari. + */ + +button, +input, +optgroup, +select, +textarea { + font-family: inherit; /* 1 */ + font-size: 100%; /* 1 */ + line-height: 1.15; /* 1 */ + margin: 0; /* 2 */ +} + +/** + * Show the overflow in IE. + * 1. Show the overflow in Edge. + */ + +button, +input { /* 1 */ + overflow: visible; +} + +/** + * Remove the inheritance of text transform in Edge, Firefox, and IE. + * 1. Remove the inheritance of text transform in Firefox. + */ + +button, +select { /* 1 */ + text-transform: none; +} + +/** + * Correct the inability to style clickable types in iOS and Safari. + */ + +button, +[type="button"], +[type="reset"], +[type="submit"] { + -webkit-appearance: button; +} + +/** + * Remove the inner border and padding in Firefox. + */ + +button::-moz-focus-inner, +[type="button"]::-moz-focus-inner, +[type="reset"]::-moz-focus-inner, +[type="submit"]::-moz-focus-inner { + border-style: none; + padding: 0; +} + +/** + * Restore the focus styles unset by the previous rule. + */ + +button:-moz-focusring, +[type="button"]:-moz-focusring, +[type="reset"]:-moz-focusring, +[type="submit"]:-moz-focusring { + outline: 1px dotted ButtonText; +} + +/** + * Correct the padding in Firefox. + */ + +fieldset { + padding: 0.35em 0.75em 0.625em; +} + +/** + * 1. Correct the text wrapping in Edge and IE. + * 2. Correct the color inheritance from `fieldset` elements in IE. + * 3. Remove the padding so developers are not caught out when they zero out + * `fieldset` elements in all browsers. + */ + +legend { + box-sizing: border-box; /* 1 */ + color: inherit; /* 2 */ + display: table; /* 1 */ + max-width: 100%; /* 1 */ + padding: 0; /* 3 */ + white-space: normal; /* 1 */ +} + +/** + * Add the correct vertical alignment in Chrome, Firefox, and Opera. + */ + +progress { + vertical-align: baseline; +} + +/** + * Remove the default vertical scrollbar in IE 10+. + */ + +textarea { + overflow: auto; +} + +/** + * 1. Add the correct box sizing in IE 10. + * 2. Remove the padding in IE 10. + */ + +[type="checkbox"], +[type="radio"] { + box-sizing: border-box; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Correct the cursor style of increment and decrement buttons in Chrome. + */ + +[type="number"]::-webkit-inner-spin-button, +[type="number"]::-webkit-outer-spin-button { + height: auto; +} + +/** + * 1. Correct the odd appearance in Chrome and Safari. + * 2. Correct the outline style in Safari. + */ + +[type="search"] { + -webkit-appearance: textfield; /* 1 */ + outline-offset: -2px; /* 2 */ +} + +/** + * Remove the inner padding in Chrome and Safari on macOS. + */ + +[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} + +/** + * 1. Correct the inability to style clickable types in iOS and Safari. + * 2. Change font properties to `inherit` in Safari. + */ + +::-webkit-file-upload-button { + -webkit-appearance: button; /* 1 */ + font: inherit; /* 2 */ +} + +/* Interactive + ========================================================================== */ + +/* + * Add the correct display in Edge, IE 10+, and Firefox. + */ + +details { + display: block; +} + +/* + * Add the correct display in all browsers. + */ + +summary { + display: list-item; +} + +/* Misc + ========================================================================== */ + +/** + * Add the correct display in IE 10+. + */ + +template { + display: none; +} + +/** + * Add the correct display in IE 10. + */ + +[hidden] { + display: none; +} diff --git a/css/style.css b/css/style.css new file mode 100644 index 0000000..801db80 --- /dev/null +++ b/css/style.css @@ -0,0 +1,171 @@ +body{ + font-family: 'SF Pro Display', sans-serif; +} +header{ + display: flex; + background-color: #2f2a2d; + justify-content: space-between; + color: #fafafa; + padding: 30px 80px; +} +button:focus{ + outline: none; +} +.logo{ + + text-transform: uppercase; + font-weight: bold; +} +.btn-cart{ + background-color: #fafafa; + padding: 10px 20px; + border: 1px solid transparent; + color: #2f2a2d; + border-radius: 5px; + transition: all ease-in-out .4s; + cursor: pointer; +} +.btn-cart:hover{ + background-color: transparent; + border-color: #fafafa; + color: #fafafa; +} +.btn-cart, .logo{ + align-self: center; +} +/*.products {*/ +/*display: flex;*/ +/*justify-content: space-between;*/ +/*flex-wrap: wrap;*/ +/*padding: 40px 80px;*/ +/*}*/ +.products{ + column-gap: 30px; + display: grid; + grid-template-columns: repeat(auto-fit, 200px); + grid-template-rows: 1fr; + padding: 40px 80px; + justify-content: space-between; +} +p { + margin: 0 0 5px 0; +} +.product-item{ + display: flex; + flex-direction: column; + width: 200px; + border-radius: 5px; + overflow: hidden; + margin: 20px 0; +} +img { + max-width: 100%; + height: auto +} +.desc { + border: 1px solid #c0c0c040; + padding: 15px +} +.cart{ + position: relative; +} +.cart-block{ + box-shadow: 0 0 5px rgba(0, 0, 0, 0.62); + border-radius: 5px; + box-sizing: border-box; + right: 0; + top: 130%; + position: absolute; + background-color: white; + padding: 20px; + color: black; + width: 300px; +} + +.invisible{ + display: none; +} +.cart-block:before{ + content: ''; + width: 0; + height: 0; + position: absolute; + top: -10px; + right: 35px; + border-left: 10px solid transparent; + border-right: 10px solid transparent; + border-bottom: 10px solid white; +} + +.buy-btn, .del-btn{ + margin-top: 5px; + background-color: #2f2a2d; + padding: 5px 15px; + border: 1px solid transparent; + color: #fafafa; + border-radius: 5px; + transition: all ease-in-out .4s; + cursor: pointer; +} +.buy-btn:hover, .del-btn:hover{ + background-color: #fafafa; + color: #2f2a2d; + border: 1px solid #2f2a2d; +} +.cart-item { + display: flex; + justify-content: space-between; +} +.cart-item:not(:last-child){ + margin-bottom: 20px; +} +.product-bio{ + display: flex; +} +.cart-item img{ + align-self: flex-start; + margin-right: 15px; +} +.product-single-price{ + color: #474747; + font-size: 0.5em; +} +.product-price{ + margin-left: 30px; +} +.product-desc{ + max-width: 150px; +} +.product-quantity { + margin-top: 15px; + font-size: 0.75em; +} +.right-block{ + text-align: right; +} +.btn-search { + background-color: transparent; + border: none; + color: #fafafa; + font-size: 1.2em; + position: absolute; + bottom: 5px; + right: 0; +} +.search-form{ + position: relative; + margin-right: 50px; + display: inline-block; +} +.search-field:focus{ + outline: none; +} +.search-field { + box-sizing: border-box; + width: 200px; + color: #fafafa; + padding: 10px; + background-color: transparent; + border: none; + border-bottom: 2px solid #fafafa; +} diff --git a/index.html b/index.html index dd40b1b..6623e74 100644 --- a/index.html +++ b/index.html @@ -1,16 +1,34 @@ - + + - eShop + + Интернет-магазин + + +
- + +
+
+ + +
+ + +
-
+
- - + + + \ No newline at end of file diff --git a/js/script.js b/js/script.js new file mode 100644 index 0000000..34762fe --- /dev/null +++ b/js/script.js @@ -0,0 +1,218 @@ +const API = + "https://raw.githubusercontent.com/GeekBrainsTutorial/online-store-api/master/responses"; + +class List { + constructor(url, container, list = listContext) { + this.container = container; + this.list = list; + this.url = url; + this.goods = []; + this.allProducts = []; + this.filtered = []; + this._init(); + } + + getJson(url) { + return fetch(url ? url : `${API + this.url}`) + .then((result) => result.json()) + .catch((error) => { + console.log(error); + }); + } + + handleData(data) { + this.goods = [...data]; + this.render(); + } + + calcSum() { + return this.allProducts.reduce((accum, item) => (accum += item.price), 0); + } + render() { + const block = document.querySelector(this.container); + for (let product of this.goods) { + console.log(this.constructor.name); + const productObj = new this.list[this.constructor.name](product); + console.log(productObj); + this.allProducts.push(productObj); + block.insertAdjacentHTML("beforeend", productObj.render()); + } + } + + filter(value) { + const regexp = new RegExp(value, "i"); + this.filtered = this.allProducts.filter((product) => + regexp.test(product.product_name) + ); + this.allProducts.forEach((el) => { + const block = document.querySelector( + `.product-item[data-id="${el.id_product}"]` + ); + if (!this.filtered.includes(el)) { + block.classList.add("invisible"); + } else { + block.classList.remove("invisible"); + } + }); + } + _init() { + return false; + } +} + +class Item { + constructor(el, img = "https://placehold.it/200x150") { + this.product_name = el.product_name; + this.price = el.price; + this.id_product = el.id_product; + this.img = img; + } + render() { + return ``; + } +} + +class ProductsList extends List { + constructor(cart, container = ".products", url = "/catalogData.json") { + super(url, container); + this.cart = cart; + this.getJson().then((data) => this.handleData(data)); + } + + _init() { + document.querySelector(this.container).addEventListener("click", (e) => { + if (e.target.classList.contains("buy-btn")) { + this.cart.addProduct(e.target); + } + }); + document.querySelector(".search-form").addEventListener("submit", (e) => { + e.preventDefault(); + this.filter(document.querySelector(".search-field").value); + }); + } +} + +class ProductItem extends Item { + render() { + return `
+ Some img +
+

${this.product_name}

+

${this.price} ₽

+ +
+
`; + } +} + +class Cart extends List { + constructor(container = ".cart-block", url = "/getBasket.json") { + super(url, container); + this.getJson().then((data) => { + this.handleData(data.contents); + }); + } + + addProduct(element) { + this.getJson(`${API}/addToBasket.json`).then((data) => { + if (data.result === 1) { + let productId = +element.dataset["id"]; + let find = this.allProducts.find( + (product) => product.id_product === productId + ); + if (find) { + find.quantity++; + this._updateCart(find); + } else { + let product = { + id_product: productId, + price: +element.dataset["price"], + product_name: element.dataset["name"], + quantity: 1, + }; + + this.goods = [product]; + this.render(); + } + } else { + alert("Error"); + } + }); + } + + removeProduct(element) { + this.getJson(`${API}/deleteFromBasket.json`).then((data) => { + if (data.result === 1) { + let productId = +element.dataset["id"]; + let find = this.allProducts.find( + (product) => product.id_product === productId + ); + if (find.quantity > 1) { + find.quantity--; + this._updateCart(find); + } else { + this.allProducts.splice(this.allProducts.indexOf(find), 1); + document.querySelector(`.cart-item[data-id="${productId}"]`).remove(); + } + } else { + alert("Error"); + } + }); + } + + _updateCart(product) { + let block = document.querySelector( + `.cart-item[data-id="${product.id_product}"]` + ); + block.querySelector( + ".product-quantity" + ).textContent = `Количество: ${product.quantity}`; + block.querySelector(".product-price").textContent = `${product.quantity * product.price + } ₽`; + } + _init() { + document.querySelector(".btn-cart").addEventListener("click", () => { + document.querySelector(this.container).classList.toggle("invisible"); + }); + document.querySelector(this.container).addEventListener("click", (e) => { + if (e.target.classList.contains("del-btn")) { + this.removeProduct(e.target); + } + }); + } +} + +class CartItem extends Item { + constructor(el, img = "https://placehold.it/50x100") { + super(el, img); + this.quantity = el.quantity; + } + render() { + return `
+
+ Some image +
+

${this.product_name}

+

Количество: ${this.quantity}

+

${this.price} за ед.

+
+
+
+

${this.quantity * this.price} ₽

+ +
+
`; + } +} + +const listContext = { + ProductsList: ProductItem, + Cart: CartItem, +}; + +let cart = new Cart(); +let products = new ProductsList(cart); \ No newline at end of file diff --git a/script.js b/script.js deleted file mode 100644 index 678fa9c..0000000 --- a/script.js +++ /dev/null @@ -1,75 +0,0 @@ -class ApiMock { - constructor() { - - } - - fetch() { - return [{ - title: 'Shirt', - price: 150 - }, - { - title: 'Socks', - price: 50 - }, - { - title: 'Jacket', - price: 350 - }, - { - title: 'Shoes', - price: 250 - }, - ]; - } -} - -class GoodsItem { - constructor(title, price) { - this.title = title; - this.price = price; - } - - getHtml() { - return `

${this.title}

${this.price}

`; - } -} - -class GoodsList { - constructor() { - this.api = new ApiMock(); - this.$goodsList = document.querySelector('.goods-list'); - this.goods = []; - } - - fetchGoods() { - this.goods = this.api.fetch().map(({ - title, - price - }) => new GoodsItem(title, price)); - } - - render() { - this.$goodsList.textContent = ''; - this.goods.forEach((good) => { - this.$goodsList.insertAdjacentHTML('beforeend', good.getHtml()); - }) - } - - goodsPrice() { - return this.goods.reduce((sum, { - price - }) => sum + price, 0); - } - -} - -class Basket {} - -class ProductsInBasket {} - -const goodsList = new GoodsList(); - -goodsList.fetchGoods(); -goodsList.render(); -goodsList.goodsPrice(); \ No newline at end of file From cb48d32767bc05be1c619817489b11a0bb7ba358 Mon Sep 17 00:00:00 2001 From: Chuzhikov Danil Date: Thu, 18 Mar 2021 18:25:22 +0300 Subject: [PATCH 3/5] homework_4 without * --- regex_replace/replace.js | 4 ++++ regex_replace/replace_quotes.html | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 regex_replace/replace.js create mode 100644 regex_replace/replace_quotes.html diff --git a/regex_replace/replace.js b/regex_replace/replace.js new file mode 100644 index 0000000..1ef53f8 --- /dev/null +++ b/regex_replace/replace.js @@ -0,0 +1,4 @@ +let text = document.getElementById('text'); +document.getElementById('replace').addEventListener('click', ()=>{ + text.textContent = text.textContent.replace(/\B'|'\B/g, '"'); +}); \ No newline at end of file diff --git a/regex_replace/replace_quotes.html b/regex_replace/replace_quotes.html new file mode 100644 index 0000000..119da32 --- /dev/null +++ b/regex_replace/replace_quotes.html @@ -0,0 +1,31 @@ + + + + + + + + Document + + + +

Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto 'possimus suscipit delectus illo' cupiditate. + Iste inventore at culpa nulla! Praesentium veritatis molestiae neque possimus modi iusto dolorum soluta + reprehenderit excepturi deserunt, blanditiis, quidem omnis. Ipsam eligendi, vitae expedita laborum, unde tenetur + sed ullam, dolore nihil illo blanditiis ad consectetur provident beatae eius quod deserunt. Id quae, mollitia + illo repellat deleniti officiis inventore numquam beatae ab 'debitis', recusandae, ut voluptas optio adipisci + accusantium. Ducimus, officiis provident, ratione saepe suscipit velit illo soluta aspernatur aliquam atque eos + nisi iure dolorum don't dignissimos in. Accusamus nulla, atque perferendis iusto nemo numquam doloremque + error molestiae voluptatem corporis sit quisquam minus neque recusandae aliquid harum. 'Facilis fugiat eaque + perferendis quam explicabo! Harum numquam porro placeat, explicabo perspiciatis similique doloribus', saepe + facere dignissimos quia odit architecto rem, isn't aut omnis optio earum perferendis cupiditate eaque dolore + nobis. Ab pariatur quod ut perspiciatis expedita quasi. Magnam repellendus sapiente fugit officiis? Odio, in + optio eaque ipsa alias magnam et repellat molestias aren't eum amet, tempora, voluptatem itaque? Architecto, + asperiores doloremque ad culpa nobis libero! 'Ducimus error asperiores sapiente nesciunt earum non cupiditate + eveniet impedit assumenda' ratione libero aut atque odit, eaque provident tempore inventore doloremque est quos + sint?

+ + + + + \ No newline at end of file From 709202bef46f1574ff4314ab7d967eb3f9a31bd0 Mon Sep 17 00:00:00 2001 From: chuzhikov_danil Date: Thu, 25 Mar 2021 17:39:47 +0300 Subject: [PATCH 4/5] homework_5 --- README.md | 1 - index.html | 79 +++++++---- js/main.js | 73 ++++++++++ js/script.js | 218 ------------------------------ regex_replace/replace.js | 4 - regex_replace/replace_quotes.html | 31 ----- 6 files changed, 124 insertions(+), 282 deletions(-) delete mode 100644 README.md create mode 100644 js/main.js delete mode 100644 js/script.js delete mode 100644 regex_replace/replace.js delete mode 100644 regex_replace/replace_quotes.html diff --git a/README.md b/README.md deleted file mode 100644 index fc9fd69..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ -# JS_Advanced \ No newline at end of file diff --git a/index.html b/index.html index 6623e74..437bdb3 100644 --- a/index.html +++ b/index.html @@ -1,34 +1,57 @@ - - - Интернет-магазин - - + + Интернет-магазин + + - -
- -
-
- - -
- - -
-
-
-
-
- - +
+
+ +
+
+ + +
+ +
+

Корзина пуста

+
+
+ Some image +
+

{{item.product_name}}

+

Количество: {{item.quantity}}

+

{{item.price}}₽ за единицу

+
+
+
+

{{item.quantity*item.price}}₽

+ +
+
+
+
+
+
+
+
+ Some img +
+

{{product.product_name}}

+

{{product.price}}₽

+ +
+
+
+
+
+ + + - - \ No newline at end of file + diff --git a/js/main.js b/js/main.js new file mode 100644 index 0000000..4987998 --- /dev/null +++ b/js/main.js @@ -0,0 +1,73 @@ +const API = 'https://raw.githubusercontent.com/GeekBrainsTutorial/online-store-api/master/responses'; + +const app = new Vue({ + el: '#app', + data: { + userSearch: '', + showCart: false, + cartUrl: '/getBasket.json', + catalogUrl: '/catalogData.json', + products: [], + cartItems: [], + filtered: [], + imgCatalog: 'https://placehold.it/200x150', + imgCart: 'https://placehold.it/50x100', + }, + methods: { + getJson(url) { + return fetch(url) + .then(result => result.json()) + .catch(error => { + console.log(error); + }) + }, + addProduct(product) { + this.getJson(`${API}/addToBasket.json`) + .then(data => { + if (data.result === 1) { + let find = this.cartItems.find(el => el.id_product === product.id_product); + if (find) { + find.quantity++; + } else { + let prod = Object.assign({quantity: 1}, product); + this.cartItems.push(prod) + } + } else { + alert('Error'); + } + }) + }, + remove(item) { + this.getJson(`${API}/deleteFromBasket.json`) + .then(data => { + if (data.result === 1) { + if (item.quantity > 1) { + item.quantity--; + } else { + this.cartItems.splice(this.cartItems.indexOf(item), 1) + } + } + }) + }, + filter() { + let regexp = new RegExp(this.userSearch, 'i'); + this.filtered = this.products.filter(el => regexp.test(el.product_name)); + }, + }, + mounted() { + this.getJson(`${API + this.cartUrl}`) + .then(data => { + for (let el of data.contents) { + this.cartItems.push(el); + } + }); + this.getJson(`${API + this.catalogUrl}`) + .then(data => { + for (let el of data) { + this.products.push(el); + this.filtered.push(el); + } + }); + } +}); + diff --git a/js/script.js b/js/script.js deleted file mode 100644 index 34762fe..0000000 --- a/js/script.js +++ /dev/null @@ -1,218 +0,0 @@ -const API = - "https://raw.githubusercontent.com/GeekBrainsTutorial/online-store-api/master/responses"; - -class List { - constructor(url, container, list = listContext) { - this.container = container; - this.list = list; - this.url = url; - this.goods = []; - this.allProducts = []; - this.filtered = []; - this._init(); - } - - getJson(url) { - return fetch(url ? url : `${API + this.url}`) - .then((result) => result.json()) - .catch((error) => { - console.log(error); - }); - } - - handleData(data) { - this.goods = [...data]; - this.render(); - } - - calcSum() { - return this.allProducts.reduce((accum, item) => (accum += item.price), 0); - } - render() { - const block = document.querySelector(this.container); - for (let product of this.goods) { - console.log(this.constructor.name); - const productObj = new this.list[this.constructor.name](product); - console.log(productObj); - this.allProducts.push(productObj); - block.insertAdjacentHTML("beforeend", productObj.render()); - } - } - - filter(value) { - const regexp = new RegExp(value, "i"); - this.filtered = this.allProducts.filter((product) => - regexp.test(product.product_name) - ); - this.allProducts.forEach((el) => { - const block = document.querySelector( - `.product-item[data-id="${el.id_product}"]` - ); - if (!this.filtered.includes(el)) { - block.classList.add("invisible"); - } else { - block.classList.remove("invisible"); - } - }); - } - _init() { - return false; - } -} - -class Item { - constructor(el, img = "https://placehold.it/200x150") { - this.product_name = el.product_name; - this.price = el.price; - this.id_product = el.id_product; - this.img = img; - } - render() { - return ``; - } -} - -class ProductsList extends List { - constructor(cart, container = ".products", url = "/catalogData.json") { - super(url, container); - this.cart = cart; - this.getJson().then((data) => this.handleData(data)); - } - - _init() { - document.querySelector(this.container).addEventListener("click", (e) => { - if (e.target.classList.contains("buy-btn")) { - this.cart.addProduct(e.target); - } - }); - document.querySelector(".search-form").addEventListener("submit", (e) => { - e.preventDefault(); - this.filter(document.querySelector(".search-field").value); - }); - } -} - -class ProductItem extends Item { - render() { - return `
- Some img -
-

${this.product_name}

-

${this.price} ₽

- -
-
`; - } -} - -class Cart extends List { - constructor(container = ".cart-block", url = "/getBasket.json") { - super(url, container); - this.getJson().then((data) => { - this.handleData(data.contents); - }); - } - - addProduct(element) { - this.getJson(`${API}/addToBasket.json`).then((data) => { - if (data.result === 1) { - let productId = +element.dataset["id"]; - let find = this.allProducts.find( - (product) => product.id_product === productId - ); - if (find) { - find.quantity++; - this._updateCart(find); - } else { - let product = { - id_product: productId, - price: +element.dataset["price"], - product_name: element.dataset["name"], - quantity: 1, - }; - - this.goods = [product]; - this.render(); - } - } else { - alert("Error"); - } - }); - } - - removeProduct(element) { - this.getJson(`${API}/deleteFromBasket.json`).then((data) => { - if (data.result === 1) { - let productId = +element.dataset["id"]; - let find = this.allProducts.find( - (product) => product.id_product === productId - ); - if (find.quantity > 1) { - find.quantity--; - this._updateCart(find); - } else { - this.allProducts.splice(this.allProducts.indexOf(find), 1); - document.querySelector(`.cart-item[data-id="${productId}"]`).remove(); - } - } else { - alert("Error"); - } - }); - } - - _updateCart(product) { - let block = document.querySelector( - `.cart-item[data-id="${product.id_product}"]` - ); - block.querySelector( - ".product-quantity" - ).textContent = `Количество: ${product.quantity}`; - block.querySelector(".product-price").textContent = `${product.quantity * product.price - } ₽`; - } - _init() { - document.querySelector(".btn-cart").addEventListener("click", () => { - document.querySelector(this.container).classList.toggle("invisible"); - }); - document.querySelector(this.container).addEventListener("click", (e) => { - if (e.target.classList.contains("del-btn")) { - this.removeProduct(e.target); - } - }); - } -} - -class CartItem extends Item { - constructor(el, img = "https://placehold.it/50x100") { - super(el, img); - this.quantity = el.quantity; - } - render() { - return `
-
- Some image -
-

${this.product_name}

-

Количество: ${this.quantity}

-

${this.price} за ед.

-
-
-
-

${this.quantity * this.price} ₽

- -
-
`; - } -} - -const listContext = { - ProductsList: ProductItem, - Cart: CartItem, -}; - -let cart = new Cart(); -let products = new ProductsList(cart); \ No newline at end of file diff --git a/regex_replace/replace.js b/regex_replace/replace.js deleted file mode 100644 index 1ef53f8..0000000 --- a/regex_replace/replace.js +++ /dev/null @@ -1,4 +0,0 @@ -let text = document.getElementById('text'); -document.getElementById('replace').addEventListener('click', ()=>{ - text.textContent = text.textContent.replace(/\B'|'\B/g, '"'); -}); \ No newline at end of file diff --git a/regex_replace/replace_quotes.html b/regex_replace/replace_quotes.html deleted file mode 100644 index 119da32..0000000 --- a/regex_replace/replace_quotes.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - Document - - - -

Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto 'possimus suscipit delectus illo' cupiditate. - Iste inventore at culpa nulla! Praesentium veritatis molestiae neque possimus modi iusto dolorum soluta - reprehenderit excepturi deserunt, blanditiis, quidem omnis. Ipsam eligendi, vitae expedita laborum, unde tenetur - sed ullam, dolore nihil illo blanditiis ad consectetur provident beatae eius quod deserunt. Id quae, mollitia - illo repellat deleniti officiis inventore numquam beatae ab 'debitis', recusandae, ut voluptas optio adipisci - accusantium. Ducimus, officiis provident, ratione saepe suscipit velit illo soluta aspernatur aliquam atque eos - nisi iure dolorum don't dignissimos in. Accusamus nulla, atque perferendis iusto nemo numquam doloremque - error molestiae voluptatem corporis sit quisquam minus neque recusandae aliquid harum. 'Facilis fugiat eaque - perferendis quam explicabo! Harum numquam porro placeat, explicabo perspiciatis similique doloribus', saepe - facere dignissimos quia odit architecto rem, isn't aut omnis optio earum perferendis cupiditate eaque dolore - nobis. Ab pariatur quod ut perspiciatis expedita quasi. Magnam repellendus sapiente fugit officiis? Odio, in - optio eaque ipsa alias magnam et repellat molestias aren't eum amet, tempora, voluptatem itaque? Architecto, - asperiores doloremque ad culpa nobis libero! 'Ducimus error asperiores sapiente nesciunt earum non cupiditate - eveniet impedit assumenda' ratione libero aut atque odit, eaque provident tempore inventore doloremque est quos - sint?

- - - - - \ No newline at end of file From 277031f58ac6a56c8c92293bf3cb461650ded4e9 Mon Sep 17 00:00:00 2001 From: chuzhikov_danil Date: Thu, 25 Mar 2021 17:50:11 +0300 Subject: [PATCH 5/5] homework_6 --- css/style.css | 27 ++++++++++++++++ getProducts.json | 12 +++++++ index.html | 42 +++++-------------------- js/CartComp.js | 82 ++++++++++++++++++++++++++++++++++++++++++++++++ js/ErrorComp.js | 25 +++++++++++++++ js/FilterComp.js | 15 +++++++++ js/ProducComp.js | 56 +++++++++++++++++++++++++++++++++ js/main.js | 79 +++++++--------------------------------------- 8 files changed, 237 insertions(+), 101 deletions(-) create mode 100644 getProducts.json create mode 100644 js/CartComp.js create mode 100644 js/ErrorComp.js create mode 100644 js/FilterComp.js create mode 100644 js/ProducComp.js diff --git a/css/style.css b/css/style.css index 801db80..008f02f 100644 --- a/css/style.css +++ b/css/style.css @@ -67,6 +67,7 @@ img { padding: 15px } .cart{ + display: flex; position: relative; } .cart-block{ @@ -169,3 +170,29 @@ img { border: none; border-bottom: 2px solid #fafafa; } +.error-msg { + padding: 30px 20px; + background-color: red; + color: white; + position: relative; +} +.error-block { + background-color: rgba(0,0,0, .5); + justify-content: center; + display: flex; + position: absolute; + top: 0; + width: 100%; + height: 100%; + align-items: center; +} +.close-btn { + font-size: 1.5em; + top: -40px; + position: absolute; + right: 0; + background: none; + border: none; + color: white; + font-weight: bold; +} diff --git a/getProducts.json b/getProducts.json new file mode 100644 index 0000000..f541d81 --- /dev/null +++ b/getProducts.json @@ -0,0 +1,12 @@ +[ + { + "id_product": 124, + "product_name": "Keyboard", + "price": 1600 + }, + { + "id_product": 457, + "product_name": "Gamepad", + "price": 3000 + } +] \ No newline at end of file diff --git a/index.html b/index.html index 437bdb3..4286a2b 100644 --- a/index.html +++ b/index.html @@ -11,47 +11,21 @@
-
- - -
- -
-

Корзина пуста

-
-
- Some image -
-

{{item.product_name}}

-

Количество: {{item.quantity}}

-

{{item.price}}₽ за единицу

-
-
-
-

{{item.quantity*item.price}}₽

- -
-
-
+ +
-
-
- Some img -
-

{{product.product_name}}

-

{{product.price}}₽

- -
-
-
+ +
+ + + + diff --git a/js/CartComp.js b/js/CartComp.js new file mode 100644 index 0000000..03b50b4 --- /dev/null +++ b/js/CartComp.js @@ -0,0 +1,82 @@ +Vue.component('cart', { + data(){ + return { + imgCart: 'https://placehold.it/50x100', + cartUrl: '/getBasket.json', + cartItems: [], + showCart: false, + } + }, + methods: { + addProduct(product){ + this.$parent.getJson(`${API}/addToBasket.json`) + .then(data => { + if(data.result === 1){ + let find = this.cartItems.find(el => el.id_product === product.id_product); + if(find){ + find.quantity++; + } else { + let prod = Object.assign({quantity: 1}, product); + this.cartItems.push(prod) + } + } else { + alert('Error'); + } + }) + }, + remove(item) { + this.$parent.getJson(`${API}/deleteFromBasket.json`) + .then(data => { + if(data.result === 1) { + if(item.quantity>1){ + item.quantity--; + } else { + this.cartItems.splice(this.cartItems.indexOf(item), 1) + } + } + }) + }, + }, + mounted(){ + this.$parent.getJson(`${API + this.cartUrl}`) + .then(data => { + for(let el of data.contents){ + this.cartItems.push(el); + } + }); + }, + template: ` +
+ +
+

Корзина пуста

+ + +
+
` +}); + +Vue.component('cart-item', { + props: ['cartItem', 'img'], + template: ` +
+
+ Some image +
+

{{cartItem.product_name}}

+

Количество: {{cartItem.quantity}}

+

{{cartItem.price}}₽ за шт.

+
+
+
+

{{cartItem.quantity*cartItem.price}}

+ +
+
+ ` +}); diff --git a/js/ErrorComp.js b/js/ErrorComp.js new file mode 100644 index 0000000..7fef048 --- /dev/null +++ b/js/ErrorComp.js @@ -0,0 +1,25 @@ +Vue.component('error', { + data(){ + return { + text: '' + } + }, + methods: { + setError(error){ + this.text = error + } + }, + computed: { + isVisible(){ + return this.text !== '' + } + }, + template: ` +
+

+ + {{ text }} +

+
+ ` +}); diff --git a/js/FilterComp.js b/js/FilterComp.js new file mode 100644 index 0000000..c9347ff --- /dev/null +++ b/js/FilterComp.js @@ -0,0 +1,15 @@ +Vue.component('filter-el', { + data(){ + return { + userSearch: '' + } + }, + template: ` +
+ + +
+ ` +}); diff --git a/js/ProducComp.js b/js/ProducComp.js new file mode 100644 index 0000000..50c71f1 --- /dev/null +++ b/js/ProducComp.js @@ -0,0 +1,56 @@ +Vue.component('products', { + data(){ + return { + catalogUrl: '/catalogData.json', + products: [], + filtered: [], + imgCatalog: 'https://placehold.it/200x150', + } + }, + methods: { + filter(value){ + let regexp = new RegExp(value, 'i'); + this.filtered = this.products.filter(el => regexp.test(el.product_name)); + } + }, + mounted(){ + this.$parent.getJson(`${API + this.catalogUrl}`) + .then(data => { + for(let el of data){ + this.products.push(el); + this.filtered.push(el); + } + }); + }, + template: ` +
+ +
+ ` +}); +Vue.component('product', { + props: ['product', 'img'], + data() { + return { + /** + * Создали ссылку на API нашей корзины. Т.к. все компоненты у нас регистрируются в корневом экземпляре Vue, + * то мы легко можем получить доступ к ним используя свойство $root. + * $parent можно использовать для доступа к родительскому экземпляру из дочернего. + */ + cartAPI: this.$root.$refs.cart, + }; + }, + + template: ` +
+ Some img +
+

{{product.product_name}}

+

{{product.price}}₽

+ + + +
+
+ ` +}); diff --git a/js/main.js b/js/main.js index 4987998..f851830 100644 --- a/js/main.js +++ b/js/main.js @@ -1,73 +1,18 @@ const API = 'https://raw.githubusercontent.com/GeekBrainsTutorial/online-store-api/master/responses'; const app = new Vue({ - el: '#app', - data: { - userSearch: '', - showCart: false, - cartUrl: '/getBasket.json', - catalogUrl: '/catalogData.json', - products: [], - cartItems: [], - filtered: [], - imgCatalog: 'https://placehold.it/200x150', - imgCart: 'https://placehold.it/50x100', - }, - methods: { - getJson(url) { - return fetch(url) - .then(result => result.json()) - .catch(error => { - console.log(error); - }) + el: '#app', + methods: { + getJson(url){ + return fetch(url) + .then(result => result.json()) + .catch(error => { + this.$refs.error.setError(error); + }) + }, }, - addProduct(product) { - this.getJson(`${API}/addToBasket.json`) - .then(data => { - if (data.result === 1) { - let find = this.cartItems.find(el => el.id_product === product.id_product); - if (find) { - find.quantity++; - } else { - let prod = Object.assign({quantity: 1}, product); - this.cartItems.push(prod) - } - } else { - alert('Error'); - } - }) - }, - remove(item) { - this.getJson(`${API}/deleteFromBasket.json`) - .then(data => { - if (data.result === 1) { - if (item.quantity > 1) { - item.quantity--; - } else { - this.cartItems.splice(this.cartItems.indexOf(item), 1) - } - } - }) - }, - filter() { - let regexp = new RegExp(this.userSearch, 'i'); - this.filtered = this.products.filter(el => regexp.test(el.product_name)); - }, - }, - mounted() { - this.getJson(`${API + this.cartUrl}`) - .then(data => { - for (let el of data.contents) { - this.cartItems.push(el); - } - }); - this.getJson(`${API + this.catalogUrl}`) - .then(data => { - for (let el of data) { - this.products.push(el); - this.filtered.push(el); - } - }); - } + mounted() { + console.log(this); + } });