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

[1주차] 최지원 미션 제출합니다. #3

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
2174809
feat: 기본 UI 구현
jiwonnchoi Sep 5, 2024
3556734
feat: 입력창 토글 기능 구현
jiwonnchoi Sep 6, 2024
1434121
feat: 할 일 추가 함수 구현
jiwonnchoi Sep 6, 2024
8ec025d
feat: 토글, 삭제 함수 구현
jiwonnchoi Sep 6, 2024
e3313a3
feat: 날짜 및 현재시각 표기
jiwonnchoi Sep 6, 2024
a254567
feat: 로컬스토리지 데이터 처리 구현
jiwonnchoi Sep 6, 2024
3152ab0
feat: 반응형 구현
jiwonnchoi Sep 6, 2024
4de67aa
style: 클래스명 수정 및 rem 단위 변환
jiwonnchoi Sep 6, 2024
8f7e29b
feat: 공통 기능 함수화
jiwonnchoi Sep 6, 2024
c08b6fa
feat: 전체, 완료된 항목 개수 표기 추가
jiwonnchoi Sep 6, 2024
86260ea
feat: 입력창 애니메이션 추가
jiwonnchoi Sep 6, 2024
3d0989b
fix: 스타일 수정 및 주석 추가
jiwonnchoi Sep 7, 2024
ca4e76e
chore: 버셀 배포
jiwonnchoi Sep 7, 2024
3d044fe
refactor: 아이콘 png에서 svg로 변경
jiwonnchoi Sep 10, 2024
28d46e6
refactor: 현재시각 1초지연 방지
jiwonnchoi Sep 10, 2024
970222b
refactor: did 네이밍 done으로 변경
jiwonnchoi Sep 10, 2024
cd12e36
refactor: addTodoItem의 input값 캐싱
jiwonnchoi Sep 10, 2024
780ce6d
refactor: deleteItem 중복호출 수정
jiwonnchoi Sep 11, 2024
a8f23ca
refactor: 전역 스타일 추가
jiwonnchoi Sep 11, 2024
eb9f93e
refactor: toggleForm 로직 분리 및 불리언 추가
jiwonnchoi Sep 11, 2024
9ef7e0e
refactor: 버튼생성 이벤트를 상위에 위임하도록 수정
jiwonnchoi Sep 11, 2024
f6d8336
fix: 배열 각 항목에 고유id 추가
jiwonnchoi Sep 11, 2024
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
3 changes: 3 additions & 0 deletions images/delete_btn.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions images/empty_checkbox.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions images/full_checkbox.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
44 changes: 42 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,52 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vanilla Todo</title>
<title>TodoList</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
/>
<link rel="stylesheet" href="style.css" />
<link rel="icon" href="images/full_checkbox.svg" />
</head>

<body>
<div class="container"></div>
<div class="container">
<header>
<h1 class="today"></h1>
</header>
<nav class="box-style">
<span class="ment-style">당신의 할 일을 작성해보세요 ✏️</span>
<hr />
<button class="show-input ment-style">입력창 불러오기</button>
</nav>
<main class="box-style">
<section class="todo">
<div class="todo-top">
<h2 class="ment-style">What I have to do</h2>
<form class="input-box box-style" style="display: none">
<input class="input" />
<button class="bold-style">작성하기</button>
</form>
</div>
<ul class="todoList"></ul>
</section>
<section class="done">
<h2 class="ment-style">What I did</h2>
<ul class="doneList"></ul>
</section>
</main>
<footer>
Copy link
Collaborator

Choose a reason for hiding this comment

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

footer main 등등 시맨틱 태그들을 적절히 잘 활용해주셨네요!! 문서의 구조를 보다 더 명확하게 파악할 수 있는 것 같습니다 ㅎㅎ

<span>
<span class="today">Total: </span>
<span class="count bold-style"></span>
</span>
<span>
<span class="today">Accomplishment: </span>
<span class="accomplishment bold-style"></span>
</span>
</footer>
</div>
</body>
<script src="script.js"></script>
</html>
225 changes: 224 additions & 1 deletion script.js
Original file line number Diff line number Diff line change
@@ -1 +1,224 @@
//😍CEOS 20기 프론트엔드 파이팅😍
/* 날짜 및 현재 시각 */
const updateTime = () => {
const today = document.querySelector(".today");
const now = new Date();

const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
};

// 요일, 날짜 및 시각 포맷 적용
today.innerHTML = now.toLocaleString("ko-KR", options);
};

updateTime();
setInterval(updateTime, 1000); // 1초마다 호출
Copy link
Member

Choose a reason for hiding this comment

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

호출 시 즉시 실행시키면 첫 1초를 기다리지 않아서 이런식으로 구성해도 좋을 것 같습니다.

Suggested change
setInterval(updateTime, 1000); // 1초마다 호출
updateTime();
setInterval(updateTime, 1000);

Copy link
Author

Choose a reason for hiding this comment

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

단순 로딩 문제라 생각했는데 앞으로는 쓰려는 함수의 작동을 정확히 이해하고 써야할 것 같습니다😂 감사합니다!


/* localStorage 데이터 처리 */
// localStorage에 항목 저장하기 함수
const saveToLocalStorage = (key, data) => {
localStorage.setItem(key, JSON.stringify(data));
};

// localStorage의 항목 불러오기 함수
const loadFromLocalStorage = (key) => {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : [];
};

let todos = loadFromLocalStorage("todos"); // 할 일 배열
let dones = loadFromLocalStorage("dones"); // 한 일 배열
Comment on lines +36 to +37
Copy link
Member

Choose a reason for hiding this comment

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

todos와 dones는 배열을 변경할 필요가 없으므로, const를 사용해도 좋을 것같습니다! let은 값이 재할당되거나 변동될 가능성이 있는 경우에만 사용하는 것이 좋다고 합니다. :)

Copy link
Author

Choose a reason for hiding this comment

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

항목을 삭제하거나 옮기는 deleteTodoItem, todoToDid 등의 함수에서 값을 재할당하는 부분이 있어서 let을 사용하였습니다!

사실 코드 쓸 때는 배열이 계속해서 변동된다는 생각에 곧바로 let을 사용하고선 넘어갔는데, 주신 리뷰보고서 한 번 더 디버깅 해보면서 정확히 어디까진 동작하고 어느 지점부터 재할당으로 인해 반영이 안되는지 파악해볼 수 있었습니다.
또 push()도 배열을 바꾼다고 생각하여 let을 써야겠다는 생각에 한 몫하였는데, 다시 찾아보니 배열을 선언한 것은 포인터이므로 pop(), push()를 통한 접근은 객체가 저장된 공간이 아닌 그 안의 내용이기 때문에 const로 선언해도 무관하다는 내용을 정확히 정리하고 넘어갈 수 있었습니다.

Comment on lines +36 to +37
Copy link

Choose a reason for hiding this comment

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

로컬스토리지에 key값을 두 개로 분리하여 저장하는 방법을 배워갑니다! 호기심에 다른 방법은 없을까 찾아보다
let tasks = loadFromLocalStorage("tasks") || { todos: [], dones: [] }; // 초기화
로 하나의 키값에 배열만 따로 두어 관리하는 방법도 있음을 알게 되었습니다. 한번 참고해보셔도 좋을 것 같습니다


// localStorage의 항목으로 초기화하기 함수
const initTodoList = () => {
todos.forEach((todo) => printItem(todo.text, "todo", todo.id));
dones.forEach((done) => printItem(done.text, "done", done.id));
};

// 할 일과 한 일 개수 및 성취도 업데이트 함수
const updateCounts = () => {
const totalCount = todos.length + dones.length;
const doneCount = dones.length;
const countElement = document.querySelector(".count");
const accomplishmentElement = document.querySelector(".accomplishment");

countElement.innerText = totalCount;
accomplishmentElement.innerText =
totalCount > 0 ? `${doneCount}/${totalCount}` : "0/0";
Comment on lines +51 to +54
Copy link

Choose a reason for hiding this comment

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

삼항조건문으로 count 처리를 하는 게 인상깊습니다! 저도 최근에 알게 된 사실인데 innerText와 textContent로 text를 넣는 차이가 있다는 것을 알았습니다.
innerText -> display에 띄워진 요소만 레이아웃 계산 후 렌더링해서 가져옴(display:none 되어있는 텍스트는 가져오지 않음)
textContent -> 모든 텍스트를 전부 가져옴
그렇기에 특별한 css가 적용되지 않았을 때 textContent가 더 빠를 수 있다고 합니다! 한번 참고해보셔도 좋을 것 같습니다.

Copy link
Author

Choose a reason for hiding this comment

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

innerHTML과 innerText만 알고 있었는데 말씀해주신 각 개념과 차이점까지 분명하게 정리하고 넘어갑니다👍 감사합니다!

};

// 이벤트 위임으로 버튼 클릭 처리를 위한 리스너 추가
document.querySelector(".todoList").addEventListener("click", (e) => {
if (e.target.closest(".todo-check")) {
completeTodo(e);
} else if (e.target.closest(".todo-del")) {
deleteTodoItem(e);
}
});

document.querySelector(".doneList").addEventListener("click", (e) => {
if (e.target.closest(".todo-check")) {
restoreTodo(e);
} else if (e.target.closest(".todo-del")) {
deleteDoneItem(e);
}
});

// 버튼 생성하기 함수
const createBtn = (src, className) => {
const btn = document.createElement("button");
const img = document.createElement("img");
img.setAttribute("src", src);
btn.appendChild(img);
btn.setAttribute("class", className);

return btn;
};

// 항목 출력하기 함수
const printItem = (text, type, id) => {
const list = document.querySelector(`.${type}List`);
const item = document.createElement("li");
const itemContent = document.createElement("div");
const itemText = document.createElement("span");
itemText.innerText = text;
itemText.className = `${type}-text`;
item.setAttribute("data-id", id);

// 체크 버튼 생성하기
const checkBtn = createBtn(
type === "todo" ? "images/empty_checkbox.svg" : "images/full_checkbox.svg",
"todo-check"
);

// 삭제 버튼 생성하기
const deleteBtn = createBtn("images/delete_btn.svg", "todo-del");

// 항목 구성하기
itemContent.className = "todo-item";
itemContent.appendChild(checkBtn);
itemContent.appendChild(itemText);
itemContent.appendChild(deleteBtn);

item.appendChild(itemContent);
list.appendChild(item);
};

// 할 일 추가하기 함수
const addTodoItem = (event) => {
Copy link
Member

Choose a reason for hiding this comment

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

image

항목의 내용이 동일한 경우 하나만 삭제해도 그 동일 항목은 모두 삭제되는 버그가 있어요! 필터링 기준이 텍스트로만 의존되어서 같은 텍스트를 가진 모든 항목이 배열에서 제거되는 것 같아요.

이러한 리스트나 배열 부분을 추가하거나 삭제할 경우 항목을 구분할 수 있는 고유한 식별자(예: id 또는 timestamp)를 추가하여 각 항목을 고유하게 식별하는 것을 추천드려요!

Suggested change
const addTodoItem = (event) => {
// 할 일 추가하기 함수 (고유 id 추가)
const addTodoItem = (event) => {
event.preventDefault();
const todoInput = document.querySelector(".input").value.trim(); // 입력값 공백 확인
if (todoInput) {
const todoItem = { id: Date.now(), text: todoInput }; // 고유 id 추가
todos.push(todoItem);
saveToLocalStorage("todos", todos); // 업데이트된 todos 배열을 localStorage에 저장
printItem(todoItem, "todo"); // 객체 전체 전달
document.querySelector(".input").value = ""; // 입력창 초기화
updateCounts();
}
};

Copy link
Author

Choose a reason for hiding this comment

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

미처 확인해보지 못한 케이스인데, id로 배열의 요소를 관리하는 것은 어떻게 보면 기본이었다는 생각이 들어 반성합니다ㅜ.ㅜ (pr에도 쓴 아쉬운 점의 현상이 아무래도 동일 항목을 입력했을 때였을 거라고 예상됩니다.) 알려주신 부분 반영해보겠습니다! 감사합니다.

event.preventDefault();
const inputElement = document.querySelector(".input");
const todoInput = inputElement.value.trim(); // 입력값 공백 확인

if (todoInput) {
const todoItem = { id: Date.now().toString(), text: todoInput };

todos.push(todoItem);
saveToLocalStorage("todos", todos); // 업데이트된 todos 배열을 localStorage에 저장
printItem(todoInput, "todo", todoItem.id);
document.querySelector(".input").value = ""; // 입력창 초기화
updateCounts();
}
};

// 항목 삭제하기 함수
const deleteItem = (e, array, key, listSelector) => {
const target = e.target.closest("li");
const itemId = target.getAttribute("data-id");

array = array.filter((item) => item.id !== itemId);
saveToLocalStorage(key, array);

document.querySelector(listSelector).removeChild(target);
return array;
};

const deleteTodoItem = (e) => {
todos = deleteItem(e, todos, "todos", ".todoList");
updateCounts();
Copy link
Member

Choose a reason for hiding this comment

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

updateCounts가 deleteItem 함수 내부에서 이미 호출되고 있으므로, todoToDid 및 didToTodo 함수에서 중복 호출되는 것 같아요. 이러한 중복 호출은 제거해도 괜찮을 것 같습니다 :)

};

const deleteDoneItem = (e) => {
dones = deleteItem(e, dones, "dones", ".doneList");
updateCounts();
};

// 할 일에서 한 일로 이동 함수
const completeTodo = (e) => {
const target = e.target.closest("li");
const todoItem = {
id: target.getAttribute("data-id"),
text: target.innerText,
};
// const todoText = target.querySelector(".todo-text").innerText;
todos = deleteItem(e, todos, "todos", ".todoList");
dones.push(todoItem);
saveToLocalStorage("dones", dones); // 한 일 저장
printItem(todoItem.text, "done", todoItem.id);
updateCounts();
};

// 한 일에서 할 일로 이동 함수
const restoreTodo = (e) => {
const target = e.target.closest("li");
const doneItem = {
id: target.getAttribute("data-id"),
text: target.innerText,
};
//const doneText = target.querySelector(".done-text").innerText;
dones = deleteItem(e, dones, "dones", ".doneList");
todos.push(doneItem);
saveToLocalStorage("todos", todos); // 할 일 저장
printItem(doneItem.text, "todo", doneItem.id);
updateCounts();
};

/* todo 입력, 체크, 삭제 */
const form = document.querySelector(".input-box"); // 입력창 폼 요소
const showMessage = document.querySelector(".show-input"); // 입력창 열고 닫는 버튼 요소

// 입력창 토글 함수
let isFormOpen = false;

const toggleForm = () => {
Copy link
Member

Choose a reason for hiding this comment

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

이런식으로 스타일을 통해서 관리하는 것도 좋지만 입력창의 상태(열림/닫힘)를 명확하게 추적하기 위해 boolean 변수로 상태를 관리하여 여닫는것도 유지보수하기엔 더 편하니까 한번 사용해봐도 좋을 것 같아요 :)_

Copy link
Author

Choose a reason for hiding this comment

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

클래스명은 워낙 지정하기 나름이라 혼동할 수도 있고, html/css에서 변경될 가능성도 있어 확실히 클래스 변경에 의존하는 것보다는 말씀해주신 것이 훨씬 직관적이고 혼란을 줄일 수 있겠다는 생각이 듭니다! 좋은 의견 주셔서 감사합니다☺️

if (isFormOpen) {
form.classList.remove("show");
form.classList.add("hide");
isFormOpen = false;

showMessage.innerHTML = "입력창 불러오기";
} else {
form.style.display = "flex";
form.classList.remove("hide");
form.classList.add("show");
isFormOpen = true;

showMessage.innerHTML = "입력창 다시닫기";
}
};

// 애니메이션 종료 처리하는 이벤트리스너
const handleAnimationEnd = (e) => {
if (form.classList.contains("hide")) {
form.style.display = "none";
form.classList.remove("hide");
}
};

// 이벤트 리스너 등록 및 기존 데이터 불러오기 함수
const init = () => {
initTodoList();
updateCounts();
form.addEventListener("submit", addTodoItem);
form.addEventListener("animationend", handleAnimationEnd);
showMessage.addEventListener("click", toggleForm);
};

init();
Copy link

Choose a reason for hiding this comment

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

window.onload / document.addEventListener("DOMContentLoaded" / 이벤트 리스너 등록없이 함수 실행

이라는 렌더링 방식에 있어 각각의 사용목적과 장단점이 있음을 이번에 알게 되었습니다. 링크 한번 달겠습니다! 한번 참고하셔도 좋을 것 같습니다. (링크를 줄이는 방법을 몰라 링크가 긴 점 양해부탁드립니다..)

https://mesonia.tistory.com/entry/%ED%8E%98%EC%9D%B4%EC%A7%80-%EB%A1%9C%EB%93%9C-%ED%9B%84-%EC%8B%A4%ED%96%89%ED%95%98%EA%B8%B0-windowonload-documentready-documentready%EB%A5%BC-%EC%88%9C%EC%88%98%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EB%A1%9C-DOMContentLoaded

Loading