-
Notifications
You must be signed in to change notification settings - Fork 2
[REFACTORING] Simplify useMediaQeury code #3
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
Open
nnnnnoel
wants to merge
4
commits into
connect-dot:develop
Choose a base branch
from
nnnnnoel:patch-1
base: develop
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
4 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 hidden or 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,122 +1,122 @@ | ||
| import React, { useEffect, useMemo, useState, useCallback, useRef } from "react"; | ||
| import React, { useEffect, useMemo, useState, useCallback, useRef } from 'react'; | ||
|
|
||
| interface IResponsibleHookConfig { | ||
| [type: string]: string; | ||
| [type: string]: string; | ||
| } | ||
|
|
||
| type Order = 'ASC' | 'DESC'; | ||
|
|
||
| function checkBrowser() { | ||
| if (typeof window !== undefined) { | ||
| return true; | ||
| } | ||
| return false; | ||
| return typeof window !== undefined; | ||
| } | ||
|
|
||
| function checkPC() { | ||
| const PC_OS = "win16|win32|win64|mac|macintel"; | ||
| if (navigator.platform && PC_OS.indexOf(navigator.platform.toLowerCase()) >= 0) { | ||
| return true; | ||
| } else { | ||
| return false; | ||
| } | ||
| const PC_OS = 'win16|win32|win64|mac|macintel'; | ||
| return !!(navigator.platform && PC_OS.indexOf(navigator.platform.toLowerCase()) >= 0); | ||
| } | ||
|
|
||
| function checkConfig(config: any) { | ||
| if (!config) { | ||
| throw new Error("Need to config"); | ||
| function checkConfig(config: IResponsibleHookConfig) { | ||
| if (!config) { | ||
| throw new Error('Need to config'); | ||
| } | ||
| } | ||
|
|
||
| function sortConfigWithSize(config: IResponsibleHookConfig, order: Order = 'ASC') { | ||
| const configEntries = Object.entries(config); | ||
| configEntries.sort((before, after) => { | ||
| const beforeSize = Number(before[1].replace('px', '')); | ||
| const afterSize = Number(after[1].replace('px', '')); | ||
| if (!beforeSize || !afterSize || Number.isNaN(beforeSize) || Number.isNaN(afterSize)) { | ||
| throw new Error('You need to use px in size'); | ||
| } | ||
| if (order === 'ASC') return beforeSize - afterSize; | ||
| return afterSize - beforeSize; | ||
| }); | ||
|
|
||
| return Object.fromEntries(configEntries); | ||
|
Member
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. 🏷 |
||
| } | ||
|
|
||
| function sortConfigWithSize(config: IResponsibleHookConfig, order: "ASC" | "DESC" = "ASC") { | ||
| const sortedConfig = {}; | ||
| const configEntries = Object.entries(config); | ||
| const sortedConfigEntries = configEntries.sort((before, after) => { | ||
| const beforeSize = Number(before[1].replace("px", "")); | ||
| const afterSize = Number(after[1].replace("px", "")); | ||
| if (!before || !afterSize) { | ||
| throw new Error("You need to use px in size"); | ||
| export const useMediaQuery = ( | ||
| config: IResponsibleHookConfig = {}, | ||
| initial: string | ||
| ): [string, any?] => { | ||
| try { | ||
| if (!checkBrowser()) { | ||
| throw new Error('It is not broswer environment, you need to use this in browser environment'); | ||
| } | ||
| const [mediaType, setMediaType] = useState<string>(''); | ||
| const latestType = useRef<string>(''); | ||
|
|
||
| const sortedConfig = useMemo(() => sortConfigWithSize(config, 'DESC'), [config]); | ||
| const configKeys = useMemo(() => Object.keys(sortedConfig), [sortedConfig]); | ||
|
|
||
| const eventHandlerGenerator = useCallback( | ||
| (type: string) => (event: MediaQueryListEvent) => { | ||
| if (event.matches) { | ||
| setMediaType(prev => { | ||
| latestType.current = prev; | ||
| return type; | ||
| }); | ||
| } else { | ||
| const index = configKeys.findIndex(value => value === type); | ||
| if (index - 1 >= 0) { | ||
| setMediaType(configKeys[index - 1]); | ||
| } else { | ||
| setMediaType(initial); | ||
| } | ||
| } | ||
| return order === "ASC" ? beforeSize - afterSize : afterSize - beforeSize; | ||
| }); | ||
| sortedConfigEntries.forEach(item => { | ||
| Object.assign(sortedConfig, { [item[0]]: item[1] }); | ||
| }); | ||
| return sortedConfig; | ||
| } | ||
| }, | ||
| [initial, configKeys] | ||
| ); | ||
|
|
||
| const mediaQuerys = useMemo( | ||
| () => | ||
| configKeys.map(key => { | ||
| const mediaQuery = window.matchMedia(`screen and (max-width: ${config[key]})`); | ||
| return { mediaQuery, eventHandler: eventHandlerGenerator(key), type: key }; | ||
| }), | ||
| [configKeys] | ||
| ); | ||
|
|
||
| export const useMediaQuery = (config: IResponsibleHookConfig, initial: string): [string, any?] => { | ||
| try { | ||
| if (!checkBrowser()) { | ||
| throw new Error("It is not broswer environment, you need to use this in browser environment"); | ||
| useEffect(() => { | ||
| const shouldInitial = !mediaQuerys.reverse().some(item => { | ||
| const { mediaQuery, type } = item; | ||
| if (mediaQuery.matches) { | ||
| setMediaType(type); | ||
| latestType.current = type; | ||
| return true; | ||
| } | ||
| const [mediaType, setMediaType] = useState<string>(""); | ||
| const latestType = useRef<string>(""); | ||
|
|
||
| checkConfig(config); | ||
|
|
||
| const sortedConfig = useMemo(() => sortConfigWithSize(config, "DESC"), [config]); | ||
| const configKeys = useMemo(() => Object.keys(sortedConfig), [sortedConfig]); | ||
|
|
||
| const eventHandlerGenerator = useCallback( | ||
| (type: string) => (event: MediaQueryListEvent) => { | ||
| if (event.matches) { | ||
| setMediaType(prev => { | ||
| latestType.current = prev; | ||
| return type; | ||
| }); | ||
| } else { | ||
| const index = configKeys.findIndex(value => value === type); | ||
| if (index && index - 1 >= 0) { | ||
| setMediaType(configKeys[index - 1]); | ||
| } else { | ||
| setMediaType(initial); | ||
| } | ||
| } | ||
| }, | ||
| [initial, configKeys] | ||
| ); | ||
|
|
||
| const mediaQuerys = useMemo( | ||
| () => | ||
| configKeys.map(key => { | ||
| const mediaQuery = window.matchMedia(`screen and (max-width: ${config[key]})`); | ||
| return { mediaQuery, eventHandler: eventHandlerGenerator(key), type: key }; | ||
| }), | ||
| [configKeys] | ||
| ); | ||
|
|
||
| useEffect(() => { | ||
| const shouldInitial = !mediaQuerys.reverse().some(item => { | ||
| const { mediaQuery, type } = item; | ||
| if (mediaQuery.matches) { | ||
| setMediaType(type); | ||
| latestType.current = type; | ||
| return true; | ||
| } | ||
| return false; | ||
| }); | ||
| if (shouldInitial) { | ||
| setMediaType(initial); | ||
| } | ||
| }, [mediaQuerys, initial]); | ||
|
|
||
| useEffect(() => { | ||
| if (checkPC()) { | ||
| mediaQuerys.forEach(item => { | ||
| const { mediaQuery, eventHandler } = item; | ||
| mediaQuery.addEventListener("change", eventHandler); | ||
| }); | ||
|
|
||
| return () => { | ||
| mediaQuerys.forEach(item => { | ||
| const { mediaQuery, eventHandler } = item; | ||
| mediaQuery.removeEventListener("change", eventHandler); | ||
| }); | ||
| }; | ||
| } | ||
| }, [mediaQuerys]); | ||
| return [mediaType]; | ||
| } catch (error) { | ||
| return ["Error", error]; | ||
| } | ||
| return false; | ||
| }); | ||
| if (shouldInitial) { | ||
| setMediaType(initial); | ||
| } | ||
| }, [mediaQuerys, initial]); | ||
|
|
||
| useEffect(() => { | ||
| if (checkPC()) { | ||
| mediaQuerys.forEach(item => { | ||
| const { mediaQuery, eventHandler } = item; | ||
| mediaQuery.addEventListener('change', eventHandler); | ||
| }); | ||
|
|
||
| return () => { | ||
| mediaQuerys.forEach(item => { | ||
| const { mediaQuery, eventHandler } = item; | ||
| mediaQuery.removeEventListener('change', eventHandler); | ||
| }); | ||
| }; | ||
| } | ||
| }, [mediaQuerys]); | ||
|
|
||
| useEffect(() => { | ||
| checkConfig(config); | ||
| }, [config]); | ||
|
|
||
| return [mediaType]; | ||
| } catch (error) { | ||
| return ['Error', error]; | ||
| } | ||
| }; | ||
|
|
||
| export default useMediaQuery; | ||
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.
🏷Tip
array.sort()를 실행하면 내부적으로 정렬된 값이 array에 반영되어 따로 할당할 필요가 없다.
이 부분 새롭게 알아갑니다. 감사합니다.