jy-headless 0.3.6 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +62 -0
  2. package/dist/Autocomplete/Autocomplete.d.ts +8 -0
  3. package/dist/Autocomplete/Autocomplete.js +309 -0
  4. package/dist/Autocomplete/Autocomplete.type.d.ts +36 -0
  5. package/dist/Autocomplete/index.d.ts +1 -0
  6. package/{cjs → dist}/Input/TextInput.type.d.ts +2 -2
  7. package/dist/Input/index.d.ts +2 -0
  8. package/dist/Select/Select.js +176 -0
  9. package/dist/Select/index.d.ts +1 -0
  10. package/dist/cjs/Autocomplete/Autocomplete.d.ts +8 -0
  11. package/dist/cjs/Autocomplete/Autocomplete.js +311 -0
  12. package/dist/cjs/Autocomplete/Autocomplete.type.d.ts +36 -0
  13. package/dist/cjs/Autocomplete/index.d.ts +1 -0
  14. package/{Input → dist/cjs/Input}/TextInput.type.d.ts +2 -2
  15. package/dist/cjs/Input/index.d.ts +2 -0
  16. package/dist/cjs/Select/Select.js +178 -0
  17. package/dist/cjs/Select/index.d.ts +1 -0
  18. package/dist/cjs/index.d.ts +5 -0
  19. package/{cjs → dist/cjs}/index.js +3 -0
  20. package/dist/index.d.ts +5 -0
  21. package/{index.js → dist/index.js} +2 -0
  22. package/package.json +66 -45
  23. package/Popover/Popover.d.ts +0 -2
  24. package/Popover/Popover.js +0 -75
  25. package/Popover/Popover.type.d.ts +0 -9
  26. package/Popover/index.d.ts +0 -2
  27. package/cjs/Popover/Popover.d.ts +0 -2
  28. package/cjs/Popover/Popover.js +0 -77
  29. package/cjs/Popover/Popover.type.d.ts +0 -9
  30. package/cjs/Popover/index.d.ts +0 -2
  31. package/cjs/index.d.ts +0 -4
  32. package/index.d.ts +0 -4
  33. package/version.txt +0 -1
  34. /package/{Input → dist/Input}/NumberInput.d.ts +0 -0
  35. /package/{Input → dist/Input}/NumberInput.type.d.ts +0 -0
  36. /package/{Input → dist/Input}/TextInput.d.ts +0 -0
  37. /package/{Select → dist/Select}/Select.d.ts +0 -0
  38. /package/{Select → dist/Select}/Select.type.d.ts +0 -0
  39. /package/{Tooltip → dist/Tooltip}/Tooltip.d.ts +0 -0
  40. /package/{Tooltip → dist/Tooltip}/Tooltip.js +0 -0
  41. /package/{Tooltip → dist/Tooltip}/Tooltip.type.d.ts +0 -0
  42. /package/{Tooltip → dist/Tooltip}/index.d.ts +0 -0
  43. /package/{cjs → dist/cjs}/Input/NumberInput.d.ts +0 -0
  44. /package/{cjs → dist/cjs}/Input/NumberInput.type.d.ts +0 -0
  45. /package/{cjs → dist/cjs}/Input/TextInput.d.ts +0 -0
  46. /package/{cjs → dist/cjs}/Select/Select.d.ts +0 -0
  47. /package/{cjs → dist/cjs}/Select/Select.type.d.ts +0 -0
  48. /package/{cjs → dist/cjs}/Tooltip/Tooltip.d.ts +0 -0
  49. /package/{cjs → dist/cjs}/Tooltip/Tooltip.js +0 -0
  50. /package/{cjs → dist/cjs}/Tooltip/Tooltip.type.d.ts +0 -0
  51. /package/{cjs → dist/cjs}/Tooltip/index.d.ts +0 -0
  52. /package/{cjs → dist/cjs}/hooks/index.d.ts +0 -0
  53. /package/{cjs → dist/cjs}/hooks/useDebounce.d.ts +0 -0
  54. /package/{cjs → dist/cjs}/hooks/useDebounce.js +0 -0
  55. /package/{cjs → dist/cjs}/hooks/usePortal.d.ts +0 -0
  56. /package/{cjs → dist/cjs}/hooks/usePortal.js +0 -0
  57. /package/{cjs → dist/cjs}/hooks/useThrottle.d.ts +0 -0
  58. /package/{cjs → dist/cjs}/hooks/useThrottle.js +0 -0
  59. /package/{hooks → dist/hooks}/index.d.ts +0 -0
  60. /package/{hooks → dist/hooks}/useDebounce.d.ts +0 -0
  61. /package/{hooks → dist/hooks}/useDebounce.js +0 -0
  62. /package/{hooks → dist/hooks}/usePortal.d.ts +0 -0
  63. /package/{hooks → dist/hooks}/usePortal.js +0 -0
  64. /package/{hooks → dist/hooks}/useThrottle.d.ts +0 -0
  65. /package/{hooks → dist/hooks}/useThrottle.js +0 -0
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # jy-headless
2
+
3
+ React용 Headless UI 라이브러리
4
+
5
+ ---
6
+
7
+ ## 특징
8
+
9
+ * React 기반 Headless UI
10
+ * 스타일 비강제 (디자인 시스템 자유 적용)
11
+ * Portal 기반 레이어 UI 지원
12
+ * 고급 입력 처리 지원
13
+ * debounce / throttle
14
+ * validate / format / parse
15
+ * IME 대응
16
+ * 접근성 고려한 인터랙션 로직
17
+ * 재사용 가능한 훅 제공
18
+
19
+ ---
20
+
21
+ ## 제공 요소
22
+
23
+ ### Components
24
+
25
+ * Select (Compound Component, Portal 기반)
26
+ * Autocomplete (Compound Component, Portal 기반)
27
+ * TextInput
28
+ * NumberInput
29
+ * Tooltip (Portal 기반)
30
+
31
+ ---
32
+
33
+ ### Hooks
34
+
35
+ * usePortal
36
+ * useDebounce
37
+ * useThrottle
38
+ * (추가 예정) useOutsideClick 등
39
+
40
+ ---
41
+
42
+ ## 사용 목적
43
+
44
+ * 디자인 시스템 구축
45
+ * 커스텀 UI 라이브러리 제작
46
+ * 접근성 + 인터랙션 로직 재사용
47
+ * 입력 처리 로직 표준화
48
+
49
+ ---
50
+
51
+ ## 스타일링
52
+
53
+ * Tailwind
54
+ * CSS-in-JS
55
+ * CSS Modules
56
+ * 어떤 방식이든 자유
57
+
58
+ ---
59
+
60
+ ## 라이선스
61
+
62
+ MIT
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+ import type { AutocompleteInputProps, AutocompleteOptionProps, AutocompleteOptionsProps, AutocompleteProps } from './Autocomplete.type';
3
+ declare const Autocomplete: (({ value, onChange, inputValue, onInputChange, disabled, filterFn, children, }: AutocompleteProps) => import("react/jsx-runtime").JSX.Element) & {
4
+ Input: ({ onKeyDown, onFocus, onChange, ...props }: AutocompleteInputProps) => import("react/jsx-runtime").JSX.Element;
5
+ Options: ({ items, renderItem, itemHeight, maxVisibleItems, overscan, children, ...props }: AutocompleteOptionsProps) => React.ReactPortal | null;
6
+ Option: ({ value, label, disabled, children, ...props }: AutocompleteOptionProps) => import("react/jsx-runtime").JSX.Element | null;
7
+ };
8
+ export default Autocomplete;
@@ -0,0 +1,309 @@
1
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
2
+ import { createContext, useState, useRef, useId, useMemo, useEffect, useContext } from 'react';
3
+ import usePortal from '../hooks/usePortal.js';
4
+
5
+ const AutocompleteContext = createContext(null);
6
+ const useAutocomplete = () => {
7
+ const ctx = useContext(AutocompleteContext);
8
+ if (!ctx)
9
+ throw new Error('Autocomplete components must be used within <Autocomplete>');
10
+ return ctx;
11
+ };
12
+ const defaultFilter = (item, query) => item.label.toLowerCase().includes(query.trim().toLowerCase());
13
+ /**
14
+ * Root
15
+ */
16
+ const AutocompleteContainer = ({ value, onChange, inputValue, onInputChange, disabled, filterFn = defaultFilter, children, }) => {
17
+ const [open, setOpen] = useState(false);
18
+ const [activeIndex, setActiveIndex] = useState(-1);
19
+ const inputRef = useRef(null);
20
+ // controlled/uncontrolled query
21
+ const [internalQuery, setInternalQuery] = useState('');
22
+ const query = inputValue ?? internalQuery;
23
+ const setQuery = (v) => {
24
+ onInputChange?.(v);
25
+ if (inputValue === undefined)
26
+ setInternalQuery(v);
27
+ };
28
+ const listboxId = useId();
29
+ // NOTE:
30
+ // - virtualization을 제대로 하려면 options data(items)가 Root에 필요하지만,
31
+ // compound API 유지를 위해 Options에서 items를 주입받아 Root에서 filtered를 만들기 어렵다.
32
+ // 그래서 Root에서는 "filtered"를 Options에서 제공할 수 있게 설계하면 복잡해짐.
33
+ // ✅ 해결: Options에 items를 주면 Root가 접근할 수 있도록 "itemsRef"를 둔다.
34
+ const itemsRef = useRef([]);
35
+ const setItems = (items) => {
36
+ itemsRef.current = items;
37
+ };
38
+ const filtered = useMemo(() => {
39
+ const src = itemsRef.current ?? [];
40
+ if (!query.trim())
41
+ return src;
42
+ return src.filter((it) => filterFn(it, query));
43
+ }, [query, filterFn]);
44
+ const close = () => {
45
+ setOpen(false);
46
+ setActiveIndex(-1);
47
+ };
48
+ const commitByIndex = (index) => {
49
+ const item = filtered[index];
50
+ if (!item || item.disabled)
51
+ return;
52
+ onChange(item.value);
53
+ setQuery(item.label);
54
+ close();
55
+ };
56
+ // 외부 value 변경 시 input label 동기화
57
+ useEffect(() => {
58
+ if (!value)
59
+ return;
60
+ const found = itemsRef.current.find((i) => i.value === value);
61
+ if (found)
62
+ setQuery(found.label);
63
+ // eslint-disable-next-line react-hooks/exhaustive-deps
64
+ }, [value]);
65
+ const statusText = useMemo(() => {
66
+ if (!open)
67
+ return '';
68
+ const n = filtered.length;
69
+ if (n === 0)
70
+ return 'No results.';
71
+ if (n === 1)
72
+ return '1 result available.';
73
+ return `${n} results available.`;
74
+ }, [open, filtered.length]);
75
+ return (jsxs(AutocompleteContext.Provider, { value: {
76
+ open,
77
+ setOpen,
78
+ selectedValue: value,
79
+ setSelectedValue: onChange,
80
+ query,
81
+ setQuery,
82
+ disabled,
83
+ inputRef,
84
+ listboxId,
85
+ activeIndex,
86
+ setActiveIndex,
87
+ filtered,
88
+ statusText,
89
+ commitByIndex,
90
+ close,
91
+ }, children: [jsx(ItemsBridge, { onItems: setItems }), children] }));
92
+ };
93
+ /**
94
+ * Options에서 items를 주입해주기 위한 브릿지(보이지 않는 컴포넌트)
95
+ * - Options가 items prop을 받으면, 내부에서 window.__ 같은 걸 쓰지 않고 Root ref에 주입
96
+ */
97
+ const ItemsBridgeContext = createContext(null);
98
+ const ItemsBridge = ({ onItems }) => {
99
+ return jsx(ItemsBridgeContext.Provider, { value: onItems });
100
+ };
101
+ const useItemsBridge = () => useContext(ItemsBridgeContext);
102
+ /**
103
+ * Input (Combobox Trigger)
104
+ * - 포커스는 input 유지
105
+ * - aria-activedescendant로 active option을 알려줌
106
+ */
107
+ const Input = ({ onKeyDown, onFocus, onChange, ...props }) => {
108
+ const { open, setOpen, query, setQuery, disabled, listboxId, activeIndex, setActiveIndex, filtered, commitByIndex, close, inputRef, } = useAutocomplete();
109
+ const activeId = activeIndex >= 0 ? `${listboxId}-opt-${activeIndex}` : undefined;
110
+ const move = (delta) => {
111
+ if (!filtered.length)
112
+ return;
113
+ setOpen(true);
114
+ setActiveIndex(activeIndex < 0 ? 0 : (activeIndex + delta + filtered.length) % filtered.length);
115
+ };
116
+ const pageMove = (deltaPages) => {
117
+ if (!filtered.length)
118
+ return;
119
+ setOpen(true);
120
+ // 10개 단위 이동(관례). 필요하면 props로 빼도 됨
121
+ const jump = 10 * deltaPages;
122
+ setActiveIndex(Math.max(0, Math.min(filtered.length - 1, (activeIndex < 0 ? 0 : activeIndex) + jump)));
123
+ };
124
+ return (jsxs(Fragment, { children: [jsx("input", { ref: inputRef, role: 'combobox', "aria-autocomplete": 'list', "aria-expanded": open, "aria-controls": listboxId, "aria-activedescendant": activeId, disabled: disabled, value: query, onFocus: (e) => {
125
+ if (!disabled) {
126
+ setOpen(true);
127
+ setActiveIndex(filtered.length ? 0 : -1);
128
+ }
129
+ onFocus?.(e);
130
+ }, onChange: (e) => {
131
+ if (disabled)
132
+ return;
133
+ setQuery(e.target.value);
134
+ setOpen(true);
135
+ setActiveIndex(0);
136
+ onChange?.(e);
137
+ }, onKeyDown: (e) => {
138
+ if (disabled)
139
+ return;
140
+ switch (e.key) {
141
+ case 'ArrowDown':
142
+ e.preventDefault();
143
+ move(1);
144
+ break;
145
+ case 'ArrowUp':
146
+ e.preventDefault();
147
+ move(-1);
148
+ break;
149
+ case 'Home':
150
+ e.preventDefault();
151
+ setOpen(true);
152
+ setActiveIndex(filtered.length ? 0 : -1);
153
+ break;
154
+ case 'End':
155
+ e.preventDefault();
156
+ setOpen(true);
157
+ setActiveIndex(filtered.length ? filtered.length - 1 : -1);
158
+ break;
159
+ case 'PageDown':
160
+ e.preventDefault();
161
+ pageMove(1);
162
+ break;
163
+ case 'PageUp':
164
+ e.preventDefault();
165
+ pageMove(-1);
166
+ break;
167
+ case 'Enter':
168
+ if (open && activeIndex >= 0) {
169
+ e.preventDefault();
170
+ commitByIndex(activeIndex);
171
+ }
172
+ break;
173
+ case 'Escape':
174
+ e.preventDefault();
175
+ close();
176
+ break;
177
+ case 'Tab':
178
+ // 관례: 탭 이동 시 팝오버 닫기
179
+ close();
180
+ break;
181
+ }
182
+ onKeyDown?.(e);
183
+ }, ...props }), jsx("span", { "aria-live": 'polite', style: {
184
+ position: 'absolute',
185
+ width: 1,
186
+ height: 1,
187
+ overflow: 'hidden',
188
+ clip: 'rect(0 0 0 0)',
189
+ whiteSpace: 'nowrap',
190
+ }, children: open ? `${filtered.length} results.` : '' })] }));
191
+ };
192
+ /**
193
+ * Options
194
+ * - portal
195
+ * - outside click close
196
+ * - virtualization (items + renderItem provided)
197
+ */
198
+ const Options = ({ items, renderItem, itemHeight = 36, maxVisibleItems = 8, overscan = 3, children, ...props }) => {
199
+ const bridge = useItemsBridge();
200
+ const { open, setOpen, close, inputRef, listboxId, filtered, activeIndex, setActiveIndex, commitByIndex, } = useAutocomplete();
201
+ // items 주입(가상화 모드)
202
+ useEffect(() => {
203
+ if (items && bridge)
204
+ bridge(items);
205
+ }, [items, bridge]);
206
+ const popoverRef = useRef(null);
207
+ const triggerWidth = inputRef.current?.getBoundingClientRect().width;
208
+ // outside click
209
+ useEffect(() => {
210
+ if (!open)
211
+ return;
212
+ const onDown = (e) => {
213
+ const t = e.target;
214
+ if (inputRef.current?.contains(t) || popoverRef.current?.contains(t))
215
+ return;
216
+ close();
217
+ };
218
+ document.addEventListener('mousedown', onDown);
219
+ return () => document.removeEventListener('mousedown', onDown);
220
+ }, [open, close, inputRef]);
221
+ // scroll container ref for virtualization
222
+ const scrollRef = useRef(null);
223
+ // active option이 항상 보이게 스크롤 보정
224
+ useEffect(() => {
225
+ if (!open)
226
+ return;
227
+ if (!scrollRef.current)
228
+ return;
229
+ if (activeIndex < 0)
230
+ return;
231
+ const top = activeIndex * itemHeight;
232
+ const bottom = top + itemHeight;
233
+ const viewTop = scrollRef.current.scrollTop;
234
+ const viewBottom = viewTop + scrollRef.current.clientHeight;
235
+ if (top < viewTop)
236
+ scrollRef.current.scrollTop = top;
237
+ else if (bottom > viewBottom)
238
+ scrollRef.current.scrollTop = bottom - scrollRef.current.clientHeight;
239
+ }, [open, activeIndex, itemHeight]);
240
+ // virtualization range
241
+ const total = filtered.length;
242
+ const viewportCount = Math.min(maxVisibleItems, Math.max(1, total));
243
+ const viewportHeight = viewportCount * itemHeight;
244
+ const [scrollTop, setScrollTop] = useState(0);
245
+ const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan);
246
+ const endIndex = Math.min(total, Math.ceil((scrollTop + viewportHeight) / itemHeight) + overscan);
247
+ const visible = filtered.slice(startIndex, endIndex);
248
+ const { portal } = usePortal({
249
+ visible: open,
250
+ targetRef: inputRef,
251
+ popoverRef,
252
+ direction: 'bottom',
253
+ gap: 4,
254
+ content: (jsx("div", { ref: popoverRef, style: { width: triggerWidth }, ...props, children: items && renderItem ? (jsx("div", { id: listboxId, role: 'listbox', ref: scrollRef, style: { maxHeight: viewportHeight, overflow: 'auto', position: 'relative' }, onScroll: (e) => setScrollTop(e.target.scrollTop), children: jsx("div", { style: { height: total * itemHeight, position: 'relative' }, children: visible.map((item, i) => {
255
+ const index = startIndex + i; // filtered index
256
+ const isActive = index === activeIndex;
257
+ const isSelected = item.value === undefined; // selection 표시를 더 강하게 원하면 ctx.selectedValue 비교해서 쓰면 됨
258
+ return (jsx("div", { id: `${listboxId}-opt-${index}`, role: 'option', "aria-selected": isSelected, "aria-disabled": item.disabled, "data-active": isActive, tabIndex: -1, onMouseEnter: () => setActiveIndex(index), onMouseDown: (e) => {
259
+ // 클릭 시 input blur 방지(중요)
260
+ e.preventDefault();
261
+ }, onClick: () => commitByIndex(index), style: {
262
+ position: 'absolute',
263
+ top: index * itemHeight,
264
+ left: 0,
265
+ right: 0,
266
+ height: itemHeight,
267
+ display: 'flex',
268
+ alignItems: 'center',
269
+ }, children: renderItem(item) }, item.value));
270
+ }) }) })) : (
271
+ /* ✅ children 모드(비가상화) */
272
+ jsx("div", { id: listboxId, role: 'listbox', children: children })) })),
273
+ });
274
+ return open ? portal : null;
275
+ };
276
+ /**
277
+ * Option (children 모드 전용 / small list)
278
+ * - a11y option role/ids만 최소 보장
279
+ * - 가상화는 여기엔 적용하지 않음
280
+ */
281
+ const Option = ({ value, label, disabled, children, ...props }) => {
282
+ const { listboxId, filtered, query, open, setOpen, setQuery, setSelectedValue, activeIndex, setActiveIndex, } = useAutocomplete();
283
+ // children 모드에서 필터링은 “간단 버전”
284
+ const visible = useMemo(() => {
285
+ if (!query.trim())
286
+ return true;
287
+ return label.toLowerCase().includes(query.trim().toLowerCase());
288
+ }, [label, query]);
289
+ useMemo(() => {
290
+ // filtered는 items 모드에서만 의미있음.
291
+ // children 모드는 간단히 -1 처리(aria-activedescendant는 items 모드가 권장)
292
+ return -1;
293
+ }, []);
294
+ if (!visible)
295
+ return null;
296
+ return (jsx("div", { role: "option", "aria-disabled": disabled, "aria-selected": false, tabIndex: -1, onMouseDown: (e) => e.preventDefault(), onClick: () => {
297
+ if (disabled)
298
+ return;
299
+ setSelectedValue(value);
300
+ setQuery(label);
301
+ setOpen(false);
302
+ setActiveIndex(-1);
303
+ }, ...props, children: children ?? label }));
304
+ };
305
+ Object.assign(AutocompleteContainer, {
306
+ Input,
307
+ Options,
308
+ Option,
309
+ });
@@ -0,0 +1,36 @@
1
+ import { HTMLAttributes, InputHTMLAttributes, ReactNode } from 'react';
2
+ export type AutocompleteItem = {
3
+ value: string;
4
+ label: string;
5
+ disabled?: boolean;
6
+ };
7
+ export interface AutocompleteProps {
8
+ value: string | null;
9
+ onChange: (v: string | null) => void;
10
+ inputValue?: string;
11
+ onInputChange?: (v: string) => void;
12
+ disabled?: boolean;
13
+ /** 옵션 필터 커스터마이즈 */
14
+ filterFn?: (item: AutocompleteItem, query: string) => boolean;
15
+ children: ReactNode;
16
+ }
17
+ export interface AutocompleteInputProps extends InputHTMLAttributes<HTMLInputElement> {
18
+ /** label 연결용 (없으면 aria-label 필수) */
19
+ 'aria-label'?: string;
20
+ }
21
+ export interface AutocompleteOptionsProps extends HTMLAttributes<HTMLDivElement> {
22
+ /** ✅ 가상화 모드: 데이터 기반 */
23
+ items?: AutocompleteItem[];
24
+ /** 가상화 모드에서 항목 렌더 */
25
+ renderItem?: (item: AutocompleteItem) => ReactNode;
26
+ /** virtualization 옵션 */
27
+ itemHeight?: number;
28
+ maxVisibleItems?: number;
29
+ overscan?: number;
30
+ }
31
+ export interface AutocompleteOptionProps extends HTMLAttributes<HTMLDivElement> {
32
+ /** children 모드(비가상화) */
33
+ value: string;
34
+ label: string;
35
+ disabled?: boolean;
36
+ }
@@ -0,0 +1 @@
1
+ export * from './Autocomplete';
@@ -1,4 +1,4 @@
1
- import { ChangeEvent, CompositionEvent, HTMLProps } from 'react';
1
+ import { ChangeEvent, CompositionEvent, InputHTMLAttributes } from 'react';
2
2
  /**
3
3
  * 고급 기능을 제공하는 TextInput 컴포넌트 props
4
4
  *
@@ -9,7 +9,7 @@ import { ChangeEvent, CompositionEvent, HTMLProps } from 'react';
9
9
  * - IME(한글 입력) 대응
10
10
  * - 공백 제어
11
11
  */
12
- export interface TextInputProps extends HTMLProps<HTMLInputElement> {
12
+ export interface TextInputProps extends InputHTMLAttributes<HTMLInputElement> {
13
13
  /**
14
14
  * 입력값 검증 함수
15
15
  *
@@ -0,0 +1,2 @@
1
+ export * from './NumberInput';
2
+ export * from './TextInput';
@@ -0,0 +1,176 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import { createContext, useContext, useState, useRef, useEffect, useMemo } from 'react';
3
+ import usePortal from '../hooks/usePortal.js';
4
+
5
+ const SelectContext = createContext(null);
6
+ /**
7
+ * Select Context 접근 훅
8
+ *
9
+ * @throws Select 외부에서 사용할 경우 에러
10
+ */
11
+ const useSelectContext = () => {
12
+ const ctx = useContext(SelectContext);
13
+ if (!ctx)
14
+ throw new Error('Select components must be used within <Select>');
15
+ return ctx;
16
+ };
17
+ /**
18
+ * Select 루트 컨테이너
19
+ *
20
+ * - 상태 관리 담당
21
+ * - Context Provider 역할
22
+ */
23
+ const SelectContainer = ({ value, onChange, multiple = false, children }) => {
24
+ const [open, setOpen] = useState(false);
25
+ const triggerRef = useRef(null);
26
+ const optionRefs = useRef([]);
27
+ const [focusedIndex, setFocusedIndex] = useState(-1);
28
+ const toggleValue = (v) => {
29
+ if (!multiple) {
30
+ onChange([v]);
31
+ setOpen(false);
32
+ return;
33
+ }
34
+ onChange(value.includes(v)
35
+ ? value.filter(i => i !== v)
36
+ : [...value, v]);
37
+ };
38
+ return (jsx(SelectContext.Provider, { value: {
39
+ open,
40
+ setOpen,
41
+ value,
42
+ toggleValue,
43
+ multiple,
44
+ triggerRef,
45
+ optionRefs,
46
+ focusedIndex,
47
+ setFocusedIndex,
48
+ }, children: children }));
49
+ };
50
+ /**
51
+ * Select 트리거 버튼
52
+ *
53
+ * - 클릭 시 Options 열림
54
+ * - 최초 포커스를 첫 옵션으로 이동
55
+ */
56
+ const Trigger = (props) => {
57
+ const { open, setOpen, triggerRef, setFocusedIndex } = useSelectContext();
58
+ return (jsx("div", { ref: triggerRef, role: 'button', "aria-expanded": open, onClick: (e) => {
59
+ setOpen(!open);
60
+ setFocusedIndex(0);
61
+ props.onClick?.(e);
62
+ }, ...props }));
63
+ };
64
+ /**
65
+ * Options 드롭다운 영역
66
+ *
67
+ * 기능:
68
+ * - 외부 클릭 시 닫힘
69
+ * - ESC 키 닫기
70
+ * - ↑ ↓ 키 포커스 이동
71
+ * - portal 렌더링
72
+ */
73
+ const Options = ({ children, ...props }) => {
74
+ const { open, triggerRef, setOpen, setFocusedIndex, optionRefs } = useSelectContext();
75
+ const popoverRef = useRef(null);
76
+ const triggerWidth = triggerRef.current?.getBoundingClientRect().width;
77
+ useEffect(() => {
78
+ if (!open)
79
+ return;
80
+ const handleOutsideClick = (e) => {
81
+ const target = e.target;
82
+ if (triggerRef.current?.contains(target) ||
83
+ popoverRef.current?.contains(target)) {
84
+ return;
85
+ }
86
+ setOpen(false);
87
+ };
88
+ document.addEventListener('mousedown', handleOutsideClick);
89
+ return () => {
90
+ document.removeEventListener('mousedown', handleOutsideClick);
91
+ };
92
+ }, [open, setOpen, triggerRef]);
93
+ useEffect(() => {
94
+ if (!open)
95
+ return;
96
+ const handleKeyDown = (e) => {
97
+ e.preventDefault();
98
+ if (e.key === 'Escape') {
99
+ setOpen(false);
100
+ setFocusedIndex(-1);
101
+ }
102
+ if (e.key === 'ArrowUp') {
103
+ setFocusedIndex(prev => prev - 1 < 0 ? optionRefs.current.length - 1 : prev - 1);
104
+ }
105
+ if (e.key === 'ArrowDown') {
106
+ setFocusedIndex(prev => prev + 1 >= optionRefs.current.length ? 0 : prev + 1);
107
+ }
108
+ };
109
+ document.addEventListener('keydown', handleKeyDown);
110
+ return () => {
111
+ optionRefs.current = [];
112
+ document.removeEventListener('keydown', handleKeyDown);
113
+ };
114
+ }, [open]);
115
+ const { portal } = usePortal({
116
+ visible: open,
117
+ targetRef: triggerRef,
118
+ popoverRef,
119
+ direction: 'bottom',
120
+ gap: 4,
121
+ content: (jsx("div", { ref: popoverRef, style: { width: triggerWidth }, ...props, children: children })),
122
+ });
123
+ return open ? portal : null;
124
+ };
125
+ /**
126
+ * 개별 선택 옵션
127
+ *
128
+ * 기능:
129
+ * - 선택 상태 표시
130
+ * - 포커스 관리
131
+ * - disabled 지원
132
+ */
133
+ const Option = ({ value, disabled, children, ...props }) => {
134
+ const { value: selected, toggleValue, optionRefs, focusedIndex } = useSelectContext();
135
+ const isSelected = selected.includes(value);
136
+ const [index, setIndex] = useState(null);
137
+ const isFocused = useMemo(() => focusedIndex === index, [focusedIndex, index]);
138
+ const ref = useRef(null);
139
+ useEffect(() => {
140
+ if (ref.current && index === null) {
141
+ setIndex(optionRefs.current.length);
142
+ optionRefs.current[optionRefs.current.length] = ref.current;
143
+ }
144
+ }, []);
145
+ useEffect(() => {
146
+ ref.current?.setAttribute('data-focused', String(focusedIndex === index));
147
+ if (focusedIndex === index) {
148
+ ref.current?.focus();
149
+ }
150
+ }, [focusedIndex, index]);
151
+ return (jsx("div", { ref: ref, role: 'option', "aria-selected": isSelected, "aria-disabled": disabled, "data-focused": isFocused, onClick: () => {
152
+ if (!disabled)
153
+ toggleValue(value);
154
+ }, ...props, children: children }));
155
+ };
156
+ /**
157
+ * Compound Select 컴포넌트
158
+ *
159
+ * 사용 예시:
160
+ *
161
+ * @example
162
+ * <Select value={value} onChange={setValue}>
163
+ * <Select.Trigger>열기</Select.Trigger>
164
+ * <Select.Options>
165
+ * <Select.Option value="a">A</Select.Option>
166
+ * <Select.Option value="b">B</Select.Option>
167
+ * </Select.Options>
168
+ * </Select>
169
+ */
170
+ Object.assign(SelectContainer, {
171
+ Trigger,
172
+ Options,
173
+ Option,
174
+ });
175
+
176
+ export { useSelectContext };
@@ -0,0 +1 @@
1
+ export * from './Select';
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+ import type { AutocompleteInputProps, AutocompleteOptionProps, AutocompleteOptionsProps, AutocompleteProps } from './Autocomplete.type';
3
+ declare const Autocomplete: (({ value, onChange, inputValue, onInputChange, disabled, filterFn, children, }: AutocompleteProps) => import("react/jsx-runtime").JSX.Element) & {
4
+ Input: ({ onKeyDown, onFocus, onChange, ...props }: AutocompleteInputProps) => import("react/jsx-runtime").JSX.Element;
5
+ Options: ({ items, renderItem, itemHeight, maxVisibleItems, overscan, children, ...props }: AutocompleteOptionsProps) => React.ReactPortal | null;
6
+ Option: ({ value, label, disabled, children, ...props }: AutocompleteOptionProps) => import("react/jsx-runtime").JSX.Element | null;
7
+ };
8
+ export default Autocomplete;