Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[14기 팝콘] Step2 상태 관리로 메뉴 관리하기 #284

Open
wants to merge 10 commits into
base: yeomgahui
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@

<br/>

# 카라멜 팝콘
## 팝콘, 신다혜, 킹지,안수경, 민오, 선리


## 🔥 Projects!

<p align="middle">
Expand Down
6 changes: 3 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ <h1 class="text-center font-bold">🌝 문벅스 메뉴 관리</h1>
<main class="mt-10 d-flex justify-center">
<div class="wrapper bg-white p-10">
<div class="heading d-flex justify-between">
<h2 class="mt-1">☕ 에스프레소 메뉴 관리</h2>
<h2 class="mt-1 heading-title">☕ 에스프레소 메뉴 관리</h2>
<span class="mr-2 mt-4 menu-count">총 0개</span>
</div>
<form id="espresso-menu-form">
Expand All @@ -65,11 +65,11 @@ <h2 class="mt-1">☕ 에스프레소 메뉴 관리</h2>
id="espresso-menu-name"
name="espressoMenuName"
class="input-field"
placeholder="에스프레소 메뉴 이름"
placeholder="메뉴 이름"
autocomplete="off"
/>
<button
type="button"
type="submit"
name="submit"
id="espresso-menu-submit-button"
class="input-submit bg-green-600 ml-2"
Expand Down
143 changes: 143 additions & 0 deletions src/js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { fetchMenu, storeMenu, removeStoreMenu, updateStoreMenu } from './store/index.js';

const $ = (selector) => document.querySelector(selector);

function App() {
let currentCategory;

const submitMenu = (event) => {
event.preventDefault();
const keyword = $('#espresso-menu-name').value.trim();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$('#espresso-menu-name') 선언이 중복되고 있는데 윗부분에 한번만 선언해도 되지 않을까요~? 😀

if(keyword.length === 0) return;
addMenu({name : keyword});
storeMenu(keyword, currentCategory);

updateTotalCount();
$('#espresso-menu-name').value = '';
}

const addMenu = (menu) => {
$('#espresso-menu-list').insertAdjacentHTML('beforeend', menuTemplate(menu));
}

const menuTemplate = (item) => {
return `<li class="menu-list-item d-flex items-center py-2">
<span class="w-100 pl-2 menu-name ${item.soldOut ? 'sold-out' : ''}">${item.name}</span>
<button
type="button"
class="bg-gray-50 text-gray-500 text-sm mr-1 menu-sold-out-button"
>
품절
</button>
<button
type="button"
class="bg-gray-50 text-gray-500 text-sm mr-1 menu-edit-button"
>
수정
</button>
<button
type="button"
class="bg-gray-50 text-gray-500 text-sm menu-remove-button"
>
삭제
</button>
</li>`;
}
const updateTotalCount = () => {
const menuCount = $('#espresso-menu-list').childElementCount;
$('.menu-count').innerText = `총 ${menuCount}개`
}
const updateMenu = (e) => {
const $targetList = e.target.closest('li');

const $menuName = $targetList.querySelector(".menu-name");
let updatedMenu = prompt('메뉴명을 수정하세요.', $menuName.innerText) ?? '';
updatedMenu = updatedMenu.trim().length > 0 ? updatedMenu : $menuName.innerText;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
updatedMenu = updatedMenu.trim().length > 0 ? updatedMenu : $menuName.innerText;
if(updatedMenu.trim().length === 0){
return;
}

이렇게 변경해도 같은 동작을 하지 않을까요~? 지금은 변경되지 않아도 아래 로직이 동작하면서 안해도 되는 처리까지 진행되고 있는 것 같아용!😮

$menuName.innerText = updatedMenu;

//localStorage변경
updateStoreMenu(getTargetIndex($targetList),{name : updatedMenu}, currentCategory);

}
const removeMenu = (e) => {
const wantDelete = confirm('정말 삭제하시겠습니까?');
if(wantDelete){
const $targetList = e.target.closest('li');

removeStoreMenu(getTargetIndex($targetList), currentCategory);

$targetList.remove();
updateTotalCount();
}
}
const soldOutMenu = (e) => {
const $targetList = e.target.closest('li');
const index = getTargetIndex($targetList);
const menu = fetchMenu();
const targetItem = menu[currentCategory][index];

let soldOut = !targetItem.hasOwnProperty('soldOut') ? true : targetItem.soldOut ? false : true;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

개인적으로 3항연산자를 2중으로 쓰게 되면 코드 읽기가 어려워지는 것 같아요 ㅠ


soldOut ? $targetList.children[0].classList.add('sold-out') : $targetList.children[0].classList.remove('sold-out');

const storeTemplate = {...targetItem, soldOut};
updateStoreMenu(index, storeTemplate, currentCategory);

}
const getTargetIndex = (selectedItem) => {
const $menuItems = Array.from(selectedItem.closest('ul').children);
return $menuItems.indexOf(selectedItem);
}
const setSavedMenu = (category) => {
currentCategory = category;
const menu = fetchMenu();
menu[currentCategory].forEach(menu => {
addMenu(menu);
});
updateTotalCount();
}
const handleCategory = (e) => {
clearListMenu();
setSavedMenu(e.target.dataset.categoryName)
const categoryName = e.target.innerText;
const $headingChild = $('.heading').children;

for(let index = 0; index < $headingChild.length; index++ ){
if($headingChild[index].classList.contains('heading-title')){
$headingChild[index].innerText = `${categoryName} 메뉴 관리`;
$('.input-label').innerText = `${categoryName.substring(2)} 메뉴 이름`;
}
}
};
const clearListMenu = () => {
while($('#espresso-menu-list').hasChildNodes()){
$('#espresso-menu-list').removeChild($('#espresso-menu-list').firstChild);
}
}

const setCategoryEvent = () => {
const $categorys = document.querySelectorAll('.cafe-category-name');
$categorys.forEach(category => {
category.addEventListener('click', handleCategory);
});
}

setSavedMenu('espresso');
setCategoryEvent();

$('#espresso-menu-form').addEventListener('submit', submitMenu);
$('#espresso-menu-list').addEventListener('click', (e)=> {
if(e.target.classList.contains('menu-edit-button')){
updateMenu(e);
}
if(e.target.classList.contains('menu-remove-button')){
removeMenu(e);
}
if(e.target.classList.contains('menu-sold-out-button')){
soldOutMenu(e);
}
});

}

App();
40 changes: 40 additions & 0 deletions src/js/store/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const defaultMenuCategory = {
espresso : [],
frappuccino: [],
blended: [],
teavana: [],
desert: []
}

export function fetchMenu() {
let menuItem = JSON.parse(localStorage.getItem("menu"));
if(!menuItem) {
menuItem = defaultMenuCategory
localStorage.menu = JSON.stringify(menuItem);
};
Comment on lines +10 to +14

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let menuItem = JSON.parse(localStorage.getItem("menu"));
if(!menuItem) {
menuItem = defaultMenuCategory
localStorage.menu = JSON.stringify(menuItem);
};
let menuItem = JSON.parse(localStorage.getItem("menu")) || defaultMenuCategory;
localStorage.menu = JSON.stringify(menuItem);

이렇게 변경해도 같은 동작을 할 것 같아요!


return menuItem;
}

export function storeMenu(menu, category) {
let savedMenus = JSON.parse(localStorage.getItem('menu'));
savedMenus[category].push({name : menu});
localStorage.menu = JSON.stringify(savedMenus);
Comment on lines +20 to +22

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JSON.parse(localStorage.getItem('menu')JSON.stringify 가 중복해서 여러번 호출되고 있는데 함수화 하면 어떨까요~? 😀

}

export function removeStoreMenu(index, category){
const savedMenus = JSON.parse(localStorage.getItem('menu'));
savedMenus[category].splice(index,1);
localStorage.menu = JSON.stringify(savedMenus);
}

export function updateStoreMenu(index,item, category){
const savedMenus = JSON.parse(localStorage.getItem('menu'));
savedMenus[category][index] = item;
localStorage.menu = JSON.stringify(savedMenus);
}

export function updateSoldOutInfoMenu(index, category){
const savedMenus = JSON.parse(localStorage.getItem('menu'));

}