-
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
[7팀 김원표] [Chapter 1-2] 프레임워크 없이 SPA 만들기 #33
Open
pitangland
wants to merge
20
commits into
hanghae-plus:main
Choose a base branch
from
pitangland: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 18 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
6c8462c
chore: npm i
pitangland 660d2b6
feat: 여러 자식 처리 및 자식 배열 평탄화
pitangland 4e935ee
feat: normallizeVNode 함수 작성
pitangland 7d3dd6c
[WIP]: createElement 작성중..
pitangland f06124d
feat: createElement 함수 작성
pitangland e9279dd
comment: 주석 추가
pitangland 0aef381
feat: eventManager 작성
pitangland 4d8dc1e
feat: renderElement 작성
pitangland 8e25a8d
[WIP] fix: 함수형 컴포넌트 처리 고민중..
pitangland 9338d96
fix: 자식 노드 재귀적으로 정규화
pitangland d01fad8
refactor: 불필요한 조건문 제거
pitangland a63a221
fix: while->if로 변경
pitangland 31c0c29
comment: 함수 설명 추가
pitangland 09d86cd
comment: 주석 설명 추가
pitangland 58172c7
feat: updateElement 작성
pitangland 4a16cbb
fix: 심화 과제에 맞춰 renderElement 수정
pitangland 07795b4
feat: 포스트 추가 기능 구현
pitangland 6de90ad
feat: 포스트 좋아요 기능 구현
pitangland 23f460a
docs: README.md
pitangland 3ff86ab
docs: README.md
pitangland 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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,70 @@ | ||
import { addEvent } from "./eventManager"; | ||
|
||
export function createElement(vNode) {} | ||
export function createElement(vNode) { | ||
//1. falsy값 처리 | ||
if (vNode === undefined || vNode === null || typeof vNode === "boolean") { | ||
return document.createTextNode(""); | ||
} | ||
|
||
function updateAttributes($el, props) {} | ||
// 2. 텍스트 노드 처리 | ||
if (typeof vNode === "string" || typeof vNode === "number") { | ||
return document.createTextNode(String(vNode)); | ||
} | ||
|
||
// 3. 배열이면 DocumentFragment로 생성하고 재귀 호출하여 추가 | ||
if (Array.isArray(vNode)) { | ||
const fragment = document.createDocumentFragment(); | ||
vNode.forEach((child) => { | ||
const childNode = createElement(child); // 재귀적으로 처리 | ||
fragment.appendChild(childNode); // 유효한 노드만 추가 | ||
}); | ||
return fragment; | ||
} | ||
|
||
// 4. 함수형 컴포넌트 처리 | ||
if (typeof vNode.type === "function") { | ||
throw new Error("Unsupported component type"); | ||
} | ||
|
||
// 5. DOM 요소 처리 | ||
const { type, props = {}, children = [] } = vNode; | ||
const $el = document.createElement(type); | ||
|
||
// 5.1 속성 노드 처리 | ||
updateAttributes($el, props); | ||
|
||
// 5.2 자식 노드 처리 | ||
const childNodes = Array.isArray(children) ? children : [children]; | ||
childNodes.forEach((child) => { | ||
const childNode = createElement(child); | ||
if (childNode) $el.appendChild(childNode); | ||
}); | ||
|
||
return $el; | ||
} | ||
|
||
// 5-1. 속성 노드 처리 함수 | ||
function updateAttributes($el, props) { | ||
// props가 없으면 아무것도 없다는 것을 고려하지 않아서 계속 오류가 났었음... | ||
if (!props) return $el; | ||
|
||
Object.entries(props).forEach(([key, value]) => { | ||
// 이벤트 | ||
if (key.startsWith("on") && typeof value === "function") { | ||
const eventType = key.slice(2).toLowerCase(); // "onClick" -> "click" | ||
addEvent($el, eventType, value); | ||
} else if (key === "className") { | ||
$el.className = value; // className -> class | ||
} else if (key.startsWith("data-")) { | ||
$el.setAttribute(key, value); // data-* 속성 처리 | ||
} else if (typeof value === "boolean") { | ||
// 불리언 속성 처리 | ||
$el[key] = value; // DOM 속성으로 반영 | ||
} else if (value === null || value === undefined) { | ||
// null 또는 undefined 속성은 제거 | ||
$el.removeAttribute(key); | ||
} else { | ||
$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,3 +1,17 @@ | ||
export function createVNode(type, props, ...children) { | ||
return {}; | ||
return { | ||
type, // 노드의 타입 | ||
props, // 해당 노드의 적용할 속성 | ||
children: children // 이 노드의 자식 요소들 | ||
.flat(Infinity) // 모든 중첩 배열을 평탄화함. | ||
.filter( | ||
// 자식 요소에서 0을 제외한 falsy값을 제거 | ||
(child) => | ||
child !== false && | ||
child !== null && | ||
child !== undefined && | ||
child !== "" && | ||
!Number.isNaN(child), | ||
), | ||
}; | ||
} |
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,68 @@ | ||
export function setupEventListeners(root) {} | ||
// 요소와 이벤트 타입을 기반으로 저장 DOM 요소가 삭제되면 해당 키와 값이 자동으로 제거되므로 메모리 누수 방지 | ||
// 특정 요소(key, element)에 대해 여러 핸들러(뭘 할건지)를 관리하기 위해 | ||
const eventHandlers = new Map(); | ||
// 이벤트 타입(key, eventType)별로 루트 요소에 리스너 등록, 발생한 이벤트 해당 핸들러로 전달 | ||
const rootEvent = new Map(); | ||
|
||
export function addEvent(element, eventType, handler) {} | ||
// 루트에서 이벤트를 위임 처리 | ||
function handleEvent(event, root) { | ||
let target = event.target; | ||
|
||
export function removeEvent(element, eventType, handler) {} | ||
// 이벤트 전파를 따라가며 핸들러 호출 | ||
while (target && target !== root) { | ||
const handlersMap = eventHandlers.get(target); | ||
|
||
if (handlersMap && handlersMap.has(event.type)) { | ||
handlersMap.get(event.type).forEach((handler) => handler(event)); // 핸들러 호출 | ||
} | ||
|
||
target = target.parentNode; // 부모로 이동 | ||
} | ||
} | ||
|
||
export function setupEventListeners(root) { | ||
//이벤트 함수를 가져와서 한 번에 root에 이벤트를 등록한다. | ||
// rootEvent의 각 이벤트 타입에 대해 리스너를 등록 | ||
rootEvent.forEach((listener, eventType) => { | ||
if (listener) return; // 이미 등록된 경우 무시 | ||
|
||
const rootListener = (event) => handleEvent(event, root); // 위임된 이벤트 처리 | ||
rootEvent.set(eventType, rootListener); // 리스너 저장 | ||
root.addEventListener(eventType, rootListener); // 리스너 등록 | ||
}); | ||
} | ||
|
||
export function addEvent(element, eventType, handler) { | ||
if (eventHandlers.has(element)) return; | ||
|
||
eventHandlers.set(element, new Map()); | ||
|
||
const handlersMap = eventHandlers.get(element); | ||
if (!handlersMap.has(eventType)) { | ||
handlersMap.set(eventType, new Set()); | ||
} | ||
handlersMap.get(eventType).add(handler); | ||
|
||
//초기화 => 이거 해주니까 통과.. | ||
//이벤트 타입이 rootEvent에 등록되지 않은 경우 rootEvent에 등록 | ||
if (!rootEvent.has(eventType)) { | ||
rootEvent.set(eventType, null); // 이벤트 전파를 위임할 리스트 | ||
setupEventListeners(document.body); // rootElement에 이벤트를 등록 | ||
} | ||
} | ||
|
||
export function removeEvent(element, eventType, handler) { | ||
const handlersMap = eventHandlers.get(element); | ||
if (!handlersMap) return; | ||
|
||
const handlers = handlersMap.get(eventType); | ||
if (!handlers) return; | ||
|
||
handlers.delete(handler); | ||
if (handlers.size === 0) { | ||
handlersMap.delete(eventType); | ||
if (handlersMap.size === 0) { | ||
eventHandlers.delete(element); | ||
} | ||
} | ||
} |
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,42 @@ | ||
export function normalizeVNode(vNode) { | ||
// 1. null, undefined, boolean 값은 빈 문자열로 변환 | ||
if ( | ||
vNode === null || | ||
vNode === undefined || | ||
vNode === true || | ||
vNode === false | ||
) { | ||
return ""; | ||
} | ||
|
||
// 2. 문자열과 숫자는 문자열로 변환 | ||
if (typeof vNode === "string" || typeof vNode === "number") { | ||
return String(vNode); | ||
} | ||
|
||
// 3. 컴포넌트를 정규화 | ||
// 배열처리 중첩 배열을 평탄화하고, 모든 요소를 재귀적으로 정규화 | ||
if (Array.isArray(vNode)) { | ||
return vNode.flat(Infinity).map(normalizeVNode); | ||
} | ||
|
||
// 사용자 정의 컴포넌트 처리 (컴포넌트 정규화) | ||
if (typeof vNode.type === "function") { | ||
const componentVNode = vNode.type({ | ||
...(vNode.props || {}), | ||
children: vNode.children, | ||
}); | ||
return normalizeVNode(componentVNode); // 반환된 VNode를 재귀적으로 처리 | ||
} | ||
|
||
// 4. 기본 노드 처리 | ||
if (typeof vNode.type === "string") { | ||
return { | ||
type: vNode.type, | ||
props: vNode.props, | ||
children: vNode.children.map(normalizeVNode).filter(normalizeVNode), | ||
}; | ||
} | ||
|
||
return vNode; | ||
} |
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.
이렇게 각 DOM 요소별, 루트 요소에 이벤트 타입별로 나눠서 관리하니 더 명확한거 같아요!! 생각 못한 부분인데 코드 잘 보고 갑니다!