-
Notifications
You must be signed in to change notification settings - Fork 65
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 만들기 #20
Open
BongjoonKim
wants to merge
2
commits into
hanghae-plus:main
Choose a base branch
from
BongjoonKim:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,39 @@ | ||
/** @jsx createVNode */ | ||
import { createVNode } from "../../lib"; | ||
import { globalStore } from "../../stores/index.js"; | ||
|
||
function createContent(event) { | ||
event.preventDefault(); | ||
const formData = new FormData(event.target); | ||
console.log("formData", formData.get("content")); | ||
const data = {}; | ||
|
||
data.id = globalStore.getState().posts.length + 1; | ||
data.author = globalStore.getState().currentUser.username; | ||
data.time = Date.now(); | ||
data.content = formData.get("content"); | ||
data.likeUsers = []; | ||
globalStore.setState({ posts: [...globalStore.getState().posts, data] }); | ||
} | ||
|
||
export const PostForm = () => { | ||
return ( | ||
<div className="mb-4 bg-white rounded-lg shadow p-4"> | ||
<textarea | ||
id="post-content" | ||
placeholder="무슨 생각을 하고 계신가요?" | ||
className="w-full p-2 border rounded" | ||
/> | ||
<button | ||
id="post-submit" | ||
className="mt-2 bg-blue-600 text-white px-4 py-2 rounded" | ||
> | ||
게시 | ||
</button> | ||
<form id={"content-form"} onSubmit={createContent}> | ||
<textarea | ||
id="post-content" | ||
placeholder="무슨 생각을 하고 계신가요?" | ||
className="w-full p-2 border rounded" | ||
name="content" | ||
/> | ||
<button | ||
id="post-submit" | ||
className="mt-2 bg-blue-600 text-white px-4 py-2 rounded" | ||
type={"submit"} | ||
> | ||
게시 | ||
</button> | ||
</form> | ||
</div> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,47 @@ | ||
import { addEvent } from "./eventManager"; | ||
|
||
export function createElement(vNode) {} | ||
export function createElement(vNode) { | ||
if (vNode === undefined || vNode === null || typeof vNode === "boolean") { | ||
return document.createTextNode(""); | ||
} else if (typeof vNode === "number" || typeof vNode === "string") { | ||
return document.createTextNode(vNode.toString()); | ||
} else if (Array.isArray(vNode)) { | ||
const parentComponent = document.createDocumentFragment(); | ||
vNode.forEach((vN) => parentComponent.appendChild(createElement(vN))); | ||
return parentComponent; | ||
} | ||
|
||
function updateAttributes($el, props) {} | ||
/* vNode를 컴포넌트로 바꾸는 과정입니다 */ | ||
// 일반 Object 형태의 컴포넌트인 경우 | ||
// console.log("vNode", vNode); | ||
// vNode.type에 맞게 해당 타입으로 컴포넌트 하나 생성 | ||
const component = document.createElement(vNode.type); | ||
|
||
// vNode에 있는 props로 component | ||
updateAttributes(component, vNode.props); | ||
// component의 자식들을 creatElement재귀를 돌려서 appendChild시키기 | ||
vNode.children.forEach((child) => { | ||
component.appendChild(createElement(child)); | ||
}); | ||
// 최종 컴포넌트 리턴 | ||
return component; | ||
} | ||
/* create할 떄 attribute값을 업데이트 해주는 함수 */ | ||
function updateAttributes($el, props) { | ||
// props 값이 존재해야만 할 수 있음 | ||
if (props) { | ||
Object.entries(props).forEach(([key, value]) => { | ||
// 이벤트 함수인 경우 | ||
if (key.startsWith("on") && typeof value === "function") { | ||
const eventType = key.toLowerCase().slice(2); // on 글자 제외 | ||
addEvent($el, eventType, value); // 이벤트를 등록하기. 등록하고자 하는 컴포넌트, 이벤트 타입, 이벤트시 실행될 함수 | ||
} else if (key === "className") { | ||
// 스타일 적용하기 | ||
$el.setAttribute("class", value); | ||
} else { | ||
// 나머지 id 값 등 | ||
$el.setAttribute(key, value); | ||
} | ||
}); | ||
} | ||
Comment on lines
+31
to
+46
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 결국 props값이 있을때만 updateAttribute가 실행되어야 하는 상황 같습니다. early return 해주는건 어떨까요?! if(!props) return;
Object.entries(props).forEach(([key, value]) => {
// 이벤트 함수인 경우
if (key.startsWith("on") && typeof value === "function") {
const eventType = key.toLowerCase().slice(2); // on 글자 제외
addEvent($el, eventType, value); // 이벤트를 등록하기. 등록하고자 하는 컴포넌트, 이벤트 타입, 이벤트시 실행될 함수
} else if (key === "className") {
// 스타일 적용하기
$el.setAttribute("class", value);
} else {
// 나머지 id 값 등
$el.setAttribute(key, value);
}
}); 이번주 과제도 고생많으셨습니다 :) |
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,11 @@ | ||
// | ||
export const createObserver = () => { | ||
const listeners = new Set(); | ||
|
||
const subscribe = (fn) => listeners.add(fn); | ||
const notify = () => listeners.forEach((listener) => listener()); | ||
const notify = () => { | ||
listeners.forEach((listener) => listener()); | ||
}; | ||
|
||
return { subscribe, notify }; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,14 @@ | ||
export function createVNode(type, props, ...children) { | ||
return {}; | ||
// depth 없이 펼치기 | ||
const flattenChildren = (children) => { | ||
return children.flat(Infinity).filter((child) => { | ||
return child || child === 0 || child === ""; | ||
}); | ||
}; | ||
|
||
return { | ||
type: type, | ||
props: props, | ||
children: flattenChildren(children), | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,73 @@ | ||
export function setupEventListeners(root) {} | ||
// 사용 중인 이벤트를 담을 객체 | ||
// 이벤트 저장소 | ||
const eventMap = new Map(); | ||
// {element : {eventType : handler}} 형식으로 저장 | ||
let rootElement = null; | ||
|
||
export function addEvent(element, eventType, handler) {} | ||
export function addEvent(element, eventType, handler) { | ||
if (!eventMap.has(element)) { | ||
eventMap.set(element, new Map()); | ||
} | ||
eventMap.get(element).set(eventType, handler); | ||
} | ||
|
||
export function removeEvent(element, eventType, handler) {} | ||
export function setupEventListeners(root) { | ||
// 기존 리스너 제거 | ||
if (rootElement) { | ||
const handlers = rootElement._eventHandlers || new Map(); | ||
for (const [type, handler] of handlers) { | ||
rootElement.removeEventListener(type, handler); | ||
} | ||
} | ||
|
||
rootElement = root; | ||
rootElement._eventHandlers = new Map(); | ||
|
||
for (const eventData of eventMap) { | ||
const eventTypeMap = eventData[1]; | ||
for (const eventTypeData of eventTypeMap) { | ||
const eventType = eventTypeData[0]; | ||
if (!rootElement._eventHandlers.has(eventType)) { | ||
const eventHandler = (event) => handleEvent(event); | ||
rootElement._eventHandlers.set(eventType, eventHandler); | ||
rootElement.addEventListener(eventType, eventHandler); | ||
} | ||
} | ||
} | ||
} | ||
|
||
export function handleEvent(event) { | ||
let target = event.target; | ||
const eventType = event.type; | ||
|
||
while (target && target !== rootElement) { | ||
if (eventMap.has(target)) { | ||
const handler = eventMap.get(target).get(eventType); | ||
if (handler) { | ||
// console.log("여기 에러나나", handler, event) | ||
handler?.(event); | ||
} | ||
} | ||
target = target.parentElement; | ||
} | ||
} | ||
|
||
export function removeEvent(element, eventType) { | ||
if (!eventMap.has(element)) return; | ||
|
||
const elementEvents = eventMap.get(element); | ||
elementEvents.delete(eventType); | ||
|
||
if (elementEvents.size === 0) { | ||
eventMap.delete(element); | ||
} | ||
|
||
// 해당 이벤트 타입에 대한 리스너가 더 이상 필요없는 경우 | ||
if (![...eventMap.values()].some((map) => map.has(eventType))) { | ||
const handler = rootElement._eventHandlers?.get(eventType); | ||
if (handler) { | ||
rootElement.removeEventListener(eventType, handler, true); | ||
rootElement._eventHandlers.delete(eventType); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,28 @@ | ||
export function normalizeVNode(vNode) { | ||
return vNode; | ||
// 값이 없는 경우는 빈 스트링으로 | ||
if (vNode === null || vNode === undefined || typeof vNode === "boolean") { | ||
return ""; | ||
} | ||
|
||
// 스프링이거나 숫자인 경우는 string으로 | ||
if (typeof vNode === "string" || typeof vNode === "number") { | ||
return vNode.toString(); | ||
} | ||
|
||
// 함수형으로 들어온다면. HomePage.jsx 같은 값은 함수이다. 함수인 경우는 type에 함수가 있음 | ||
// 함수를 실행하는데, 내부 값에는 props와 children을 전달한다. | ||
if (typeof vNode.type === "function") { | ||
// console.log("함수로 들어온다는게 뭐야?", vNode) | ||
return normalizeVNode( | ||
vNode.type({ ...vNode.props, children: vNode.children }), | ||
); | ||
} | ||
|
||
// 일반 Object 타입인 경우 | ||
return { | ||
...vNode, | ||
children: vNode.children | ||
?.map((child) => normalizeVNode(child)) | ||
.filter(Boolean), | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이 부분은 구조 분해 할당으로 getState()의 중복 호출을 줄이고 가독성도 좋게 할 수 있을 듯합니다!
과제 하시느라 고생 많으셨습니다 :D