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

[6팀 소수지] [Chapter 1-2] 프레임워크 없이 SPA 만들기 #47

Open
wants to merge 5 commits into
base: main
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
33 changes: 31 additions & 2 deletions src/components/posts/Post.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,42 @@
/** @jsx createVNode */
import { createVNode } from "../../lib";
import { globalStore } from "../../stores/globalStore.js";
import { toTimeFormat } from "../../utils/index.js";

export const Post = ({
id,
author,
time,
content,
likeUsers,
activationLike = false,
// activationLike = false,
}) => {
const { getState, setState } = globalStore;
const { currentUser, loggedIn, posts } = getState();

const handleLike = () => {
if (!loggedIn) {
window.alert("로그인 후 이용해주세요");
return;
}

const targetPost = posts.find((post) => post.id === id);
const username = currentUser.username;

const updatedLikeUsers = targetPost.likeUsers.includes(username)
? targetPost.likeUsers.filter((user) => user !== username)
: [...targetPost.likeUsers, username];

const updatedPost = { ...targetPost, likeUsers: updatedLikeUsers };
const updatedPosts = posts.map((post) =>
post.id === id ? updatedPost : post,
);

setState({ posts: updatedPosts });
};

const isLiked = currentUser && likeUsers.includes(currentUser?.username);

return (
<div className="bg-white rounded-lg shadow p-4 mb-4">
<div className="flex items-center mb-2">
Expand All @@ -20,7 +48,8 @@ export const Post = ({
<p>{content}</p>
<div className="mt-2 flex justify-between text-gray-500">
<span
className={`like-button cursor-pointer${activationLike ? " text-blue-500" : ""}`}
onClick={handleLike}
className={`like-button cursor-pointer${isLiked ? " text-blue-500" : ""}`}
>
좋아요 {likeUsers.length}
</span>
Expand Down
24 changes: 24 additions & 0 deletions src/components/posts/PostForm.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
/** @jsx createVNode */
import { createVNode } from "../../lib";
import { globalStore } from "../../stores/globalStore";

export const PostForm = () => {
const { getState, setState } = globalStore;
const { currentUser, posts } = getState();

const submitPost = () => {
const contentEl = document.querySelector("#post-content");
const content = contentEl.value.trim();

if (!currentUser || !content) return;

const newPosts = [
...posts,
{
id: posts.length + 1,
author: currentUser?.username,
time: new Date().getTime(),
content,
likeUsers: [],
},
];

setState({ posts: newPosts });
};
return (
<div className="mb-4 bg-white rounded-lg shadow p-4">
<textarea
Expand All @@ -12,6 +35,7 @@ export const PostForm = () => {
<button
id="post-submit"
className="mt-2 bg-blue-600 text-white px-4 py-2 rounded"
onClick={submitPost}
>
게시
</button>
Expand Down
42 changes: 40 additions & 2 deletions src/lib/createElement.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,43 @@
import { addEvent } from "./eventManager";

export function createElement(vNode) {}
export function createElement(vNode) {
if (
typeof vNode === "undefined" ||
vNode === null ||
typeof vNode === "boolean"
) {
return document.createTextNode("");
}

function updateAttributes($el, props) {}
if (typeof vNode === "string" || typeof vNode === "number") {
return document.createTextNode(vNode);
}

if (Array.isArray(vNode)) {
const fragment = document.createDocumentFragment();
vNode.forEach((child) => fragment.appendChild(createElement(child)));

return fragment;
}

const $el = document.createElement(vNode.type);

updateAttributes($el, vNode.props ?? {});

$el.append(...vNode.children.map(createElement));

return $el;
}

function updateAttributes($el, props) {
Object.entries(props).forEach(([attr, value]) => {
if (attr.startsWith("on") && typeof value === "function") {
const eventType = attr.toLowerCase().slice(2);
addEvent($el, eventType, value);
} else if (attr === "className") {
$el.setAttribute("class", value);
} else {
Comment on lines +33 to +39

Choose a reason for hiding this comment

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

크게 중요하지는 않을 것 같지만 리뷰 남겨 봅니다...!
현재 taillwind를 사용해서 css를 다루다 보니 각 element에 className이 더 자주 사용되지 않을까 라는 생각이 듭니다!
그래서 조건문 비교를 attr === 'className'을 가장 처음에 비교하는게 더 좋지 않을까? 라는 생각을 해봤습니다 ㅎㅎ

if (attr === "className") {
      $el.setAttribute("class", value);
    } else if (attr.startsWith("on") && typeof value === "function") {
      const eventType = attr.toLowerCase().slice(2);
      addEvent($el, eventType, value);
    }

이번주 과제도 고생 많으셨습니다 :)

Choose a reason for hiding this comment

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

앗 근데 생각 해보니 의미가 없을것 같네요....ㅎㅎㅎ

$el.setAttribute(attr, value);
}
});
}
8 changes: 7 additions & 1 deletion src/lib/createVNode.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
export function createVNode(type, props, ...children) {
return {};
return {
type,
props,
children: children
.flat(Infinity)
.filter((value) => value === 0 || Boolean(value)),
};
}
60 changes: 57 additions & 3 deletions src/lib/eventManager.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,59 @@
export function setupEventListeners(root) {}
const eventListeners = new Map();
let $root = null;

export function addEvent(element, eventType, handler) {}
function handleEvent(e) {
let target = e.target;

export function removeEvent(element, eventType, handler) {}
while (target && target !== $root) {
const handlers = eventListeners.get(e.type)?.get(target);
if (handlers) {
handlers.forEach((handler) => handler(e));
}
target = target.parentElement;
}
}

export function setupEventListeners(root) {
if (!root) return;
$root = root;

Choose a reason for hiding this comment

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

오호! early return!


eventListeners.forEach((handlers, eventType) => {
$root.removeEventListener(eventType, handleEvent);
$root.addEventListener(eventType, handleEvent);
});
}

export function addEvent(element, eventType, handler) {
if (!eventListeners.has(eventType)) {
eventListeners.set(eventType, new WeakMap());
}

const handlers = eventListeners.get(eventType);
if (!handlers.has(element)) {
handlers.set(element, new Set());
}

handlers.get(element).add(handler);
}

export function removeEvent(element, eventType, handler) {
const handlersMap = eventListeners.get(eventType);
if (!handlersMap) return;

const handlers = handlersMap.get(element);
if (!handlers) return;

if (handler) {
handlers.delete(handler);

if (handlers.size === 0) {
handlersMap.delete(element);
}
} else {
handlersMap.delete(element);
}

if (handlersMap.size === 0) {
eventListeners.delete(eventType);
}
}
33 changes: 32 additions & 1 deletion src/lib/normalizeVNode.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
export function normalizeVNode(vNode) {
return vNode;
if (
typeof vNode === "undefined" ||
vNode === null ||
typeof vNode === "boolean"
) {
return "";
}

if (typeof vNode === "string" || typeof vNode === "number") {
return String(vNode);
}

if (typeof vNode.type === "function") {
return normalizeVNode(
vNode.type({ ...vNode.props, children: vNode.children }),
);
}

// if (Array.isArray(vNode)) {
// return vNode.map(normalizeVNode).join("");
// }

const children = Array.isArray(vNode.children)
? vNode.children
: vNode.children
? [vNode.children]
: [];

return {
...vNode,
children: children.map(normalizeVNode).filter(Boolean),

Choose a reason for hiding this comment

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

filter(Boolean)은 JavaScript에서 truthy한 값만 남기기 위한 필터링 방법이라고 하네요! (처음 알았어요) 깔끔한 처리인 것 같습니다.
수지님 과제 하시느라 넘 고생 많으셨어요~!

};
}
16 changes: 16 additions & 0 deletions src/lib/renderElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,24 @@ import { createElement } from "./createElement";
import { normalizeVNode } from "./normalizeVNode";
import { updateElement } from "./updateElement";

const OldNodeMap = new WeakMap();

export function renderElement(vNode, container) {
// 최초 렌더링시에는 createElement로 DOM을 생성하고
// 이후에는 updateElement로 기존 DOM을 업데이트한다.
// 렌더링이 완료되면 container에 이벤트를 등록한다.
// console.log(`renderElement ${JSON.stringify(vNode)}, ${container}`);

const oldNode = OldNodeMap.get(container);
const newNode = normalizeVNode(vNode);

if (!oldNode) {
const element = createElement(newNode);
container.appendChild(element);
} else {
updateElement(container, newNode, oldNode);
}

OldNodeMap.set(container, newNode);
setupEventListeners(container);
}
75 changes: 73 additions & 2 deletions src/lib/updateElement.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,77 @@
import { addEvent, removeEvent } from "./eventManager";
import { createElement } from "./createElement.js";

function updateAttributes(target, originNewProps, originOldProps) {}
function updateAttributes(target, originNewProps, originOldProps) {
const oldProps = originOldProps || {};
const newProps = originNewProps || {};

export function updateElement(parentElement, newNode, oldNode, index = 0) {}
Object.entries(oldProps).forEach(([attr, value]) => {
if (!newProps[attr]) {
if (attr.startsWith("on")) {
const eventType = attr.slice(2).toLowerCase();
removeEvent(target, eventType, value);
} else {
target.removeAttribute(attr);
}
}
});

Object.entries(newProps).forEach(([attr, value]) => {
if (oldProps[attr] !== value) {
if (attr.startsWith("on")) {
const eventType = attr.slice(2).toLowerCase();
if (typeof oldProps[attr] === "function") {
removeEvent(target, eventType, oldProps[attr]);
}
addEvent(target, eventType, value);
} else if (attr === "className") {
target.setAttribute("class", value);
} else {
target.setAttribute(attr, value);
}
}
});
}

export function updateElement(parentElement, newNode, oldNode, index = 0) {
const existingNode = parentElement?.childNodes[index];

// oldNode만 있는 경우: oldNode를 parentElement에서 제거한다.
if (!newNode && oldNode) {
parentElement.removeChild(existingNode);
return;
}

// newNode만 있는 경우: newNode를 parentElement에 추가한다.
if (!oldNode && newNode) {
parentElement.appendChild(createElement(newNode));
return;
}

// oldNode와 newNode 모두 string인 경우: oldNode와 newNode 내용이 다르다면, newNode 내용으로 교체한다.
if (typeof oldNode === "string" || typeof newNode === "string") {
if (newNode !== oldNode) {
parentElement.replaceChild(createElement(newNode), existingNode);
}
return;
}

// oldeNode와 newNode의 태그 이름(type)이 다를 경우: oldNode를 제거하고 해당 위치에 newNode를 추가한다.
if (oldNode.type !== newNode.type) {
parentElement.replaceChild(createElement(newNode), existingNode);
return;
}

// oldNode와 newNode의 태그 이름(type)이 같을 경우: newNode와 oldNode의 속성을 비교하여 변경된 부분만 반영한다.
updateAttributes(existingNode, newNode.props || {}, oldNode.props || {});

// oldNode와 newNode를 순회하며, 앞에 조건식을 반복한다.
const newChildren = newNode.children || [];
const oldChildren = oldNode.children || [];

const maxLength = Math.max(newChildren.length, oldChildren.length);

for (let i = 0; i < maxLength; i++) {
updateElement(existingNode, newChildren[i], oldChildren[i], i);
}
}
15 changes: 8 additions & 7 deletions src/pages/HomePage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { globalStore } from "../stores";
* - 로그인하지 않은 사용자가 게시물에 좋아요를 누를 경우, "로그인 후 이용해주세요"를 alert로 띄운다.
*/
export const HomePage = () => {
const { posts } = globalStore.getState();
const { posts, loggedIn } = globalStore.getState();

return (
<div className="bg-gray-100 min-h-screen flex justify-center">
Expand All @@ -20,13 +20,14 @@ export const HomePage = () => {
<Navigation />

<main className="p-4">
<PostForm />
{loggedIn && <PostForm />}
<div id="posts-container" className="space-y-4">
{[...posts]
.sort((a, b) => b.time - a.time)
.map((props) => {
return <Post {...props} activationLike={false} />;
})}
{posts &&
[...posts]
.sort((a, b) => b.time - a.time)
.map((props) => {
return <Post key={props.id} {...props} />;
})}
</div>
</main>

Expand Down
Loading