@ilokesto/utilinent 0.0.14 → 0.0.16

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.
@@ -1,2 +1,9 @@
1
+ import { ComponentPropsWithRef } from "react";
1
2
  import type { ForProps } from "../types";
2
- export declare function For<T extends Array<unknown>>({ each, children, fallback, }: ForProps<T>): string | number | boolean | import("react").ReactElement<any, string | import("react").JSXElementConstructor<any>> | Iterable<import("react").ReactNode> | null;
3
+ type ForType = {
4
+ <T extends Array<unknown>>(props: ForProps<T>): React.ReactNode;
5
+ } & {
6
+ [K in keyof JSX.IntrinsicElements]: <T extends Array<unknown>>(props: ForProps<T> & ComponentPropsWithRef<K>) => React.ReactNode;
7
+ };
8
+ export declare const For: ForType;
9
+ export {};
@@ -0,0 +1,12 @@
1
+ import { createElement } from "react";
2
+ import { htmlTags } from "../constants/htmlTags";
3
+ function BaseFor({ each, children, fallback = null, }) {
4
+ return each && each.length > 0 ? each.map(children) : fallback;
5
+ }
6
+ const renderForTag = (tag) => ({ each, children, fallback = null, ...props }) => {
7
+ if (!each || each.length === 0)
8
+ return fallback;
9
+ const content = each.map(children);
10
+ return createElement(tag, props, content);
11
+ };
12
+ export const For = Object.assign(BaseFor, Object.fromEntries(htmlTags.map(tag => [tag, renderForTag(tag)])));
@@ -0,0 +1,21 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useIntersectionObserver } from "../hooks/useIntersectionObserver";
3
+ import { Show } from "./Show";
4
+ export function Observer({ children, fallback = null, threshold = 0, rootMargin = "0px", triggerOnce: freezeOnceVisible = false, onIntersect: onChange, }) {
5
+ const { ref, isIntersecting } = useIntersectionObserver({
6
+ threshold,
7
+ rootMargin,
8
+ freezeOnceVisible,
9
+ onChange,
10
+ });
11
+ return (_jsx(Show.div, { ref: ref, style:
12
+ // fallback이 없고 isIntersecting이 false인 경우
13
+ !fallback && !isIntersecting
14
+ ? {
15
+ minHeight: "1px",
16
+ minWidth: "1px",
17
+ flexShrink: 0, // flex 컨테이너에서 축소되지 않도록
18
+ display: "block", // inline 요소가 되지 않도록
19
+ }
20
+ : undefined, when: isIntersecting, fallback: fallback, children: typeof children === "function" ? children(isIntersecting) : children }));
21
+ }
@@ -0,0 +1,5 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Show } from "./Show";
3
+ export function OptionalWrapper({ when, children, wrapper, fallback }) {
4
+ return _jsx(Show, { when: when, fallback: fallback ? fallback(children) : children, children: wrapper(children) });
5
+ }
@@ -1,2 +1,9 @@
1
- import type { RepeatProps } from "../types";
2
- export declare function Repeat({ times, children, fallback }: RepeatProps): string | number | true | Iterable<import("react").ReactNode> | import("react/jsx-runtime").JSX.Element | null;
1
+ import { ComponentPropsWithRef } from "react";
2
+ import { RepeatProps } from "../types";
3
+ type RepeatType = {
4
+ (props: RepeatProps): React.ReactNode;
5
+ } & {
6
+ [K in keyof JSX.IntrinsicElements]: (props: RepeatProps & ComponentPropsWithRef<K>) => React.ReactNode;
7
+ };
8
+ export declare const Repeat: RepeatType;
9
+ export {};
@@ -0,0 +1,17 @@
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
+ import { createElement } from "react";
3
+ import { htmlTags } from "../constants/htmlTags";
4
+ function BaseRepeat({ times, children, fallback = null }) {
5
+ if (!times || times <= 0 || !Number.isInteger(times)) {
6
+ return fallback ?? null;
7
+ }
8
+ return _jsx(_Fragment, { children: Array.from({ length: times }, (_, i) => children(i)) });
9
+ }
10
+ const renderForTag = (tag) => ({ times, children, fallback = null, ...props }) => {
11
+ if (!times || times <= 0 || !Number.isInteger(times)) {
12
+ return fallback ?? null;
13
+ }
14
+ const content = Array.from({ length: times }, (_, i) => children(i));
15
+ return createElement(tag, props, content);
16
+ };
17
+ export const Repeat = Object.assign(BaseRepeat, Object.fromEntries(htmlTags.map(tag => [tag, renderForTag(tag)])));
@@ -1,3 +1,13 @@
1
- import type { ShowProps, ShowPropsArray } from "../types";
2
- export declare function Show<T extends unknown[]>({ when, children, fallback }: ShowPropsArray<T>): React.ReactNode;
3
- export declare function Show<T extends unknown>({ when, children, fallback }: ShowProps<T>): React.ReactNode;
1
+ import { ComponentPropsWithRef } from "react";
2
+ import { ShowProps, ShowPropsArray } from "../types";
3
+ type ShowType = {
4
+ <T extends unknown[]>(props: ShowPropsArray<T>): React.ReactNode;
5
+ <T extends unknown>(props: ShowProps<T>): React.ReactNode;
6
+ } & {
7
+ [K in keyof JSX.IntrinsicElements]: {
8
+ <T extends unknown[]>(props: ShowPropsArray<T> & ComponentPropsWithRef<K>): React.ReactNode;
9
+ <T extends unknown>(props: ShowProps<T> & ComponentPropsWithRef<K>): React.ReactNode;
10
+ };
11
+ };
12
+ export declare const Show: ShowType;
13
+ export {};
@@ -0,0 +1,18 @@
1
+ import { createElement } from "react";
2
+ import { htmlTags } from "../constants/htmlTags";
3
+ const BaseShow = ({ when, children, fallback = null }) => {
4
+ const shouldRender = Array.isArray(when) ? when.every(Boolean) : !!when;
5
+ return shouldRender
6
+ ? typeof children === "function"
7
+ ? children(when)
8
+ : children
9
+ : fallback;
10
+ };
11
+ const renderForTag = (tag) => ({ when, children, fallback = null, ...props }) => {
12
+ const shouldRender = Array.isArray(when) ? when.every(Boolean) : !!when;
13
+ if (!shouldRender)
14
+ return fallback;
15
+ const content = typeof children === "function" ? children(when) : children;
16
+ return createElement(tag, props, content);
17
+ };
18
+ export const Show = Object.assign(BaseShow, Object.fromEntries(htmlTags.map(tag => [tag, renderForTag(tag)])));
@@ -0,0 +1 @@
1
+ export declare const htmlTags: string[];
@@ -0,0 +1,3 @@
1
+ export const htmlTags = [
2
+ "a", "abbr", "address", "article", "aside", "b", "bdi", "bdo", "blockquote", "button", "canvas", "cite", "code", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "div", "dl", "dt", "em", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "menu", "meter", "nav", "ol", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "small", "span", "strong", "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "tr", "u", "ul", "var", "video"
3
+ ];
@@ -0,0 +1,8 @@
1
+ import { useEffect, useState } from "react";
2
+ export function Mount({ children, fallback = null }) {
3
+ const [resolvedChildren, setResolvedChildren] = useState(fallback);
4
+ useEffect(() => {
5
+ (async () => setResolvedChildren(typeof children === "function" ? await children() : children))();
6
+ }, [children]);
7
+ return resolvedChildren;
8
+ }
@@ -0,0 +1,96 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useState } from "react";
3
+ import { Observer } from "../components/Observer";
4
+ /**
5
+ * Slacker 컴포넌트 - Lazy Loading 전용
6
+ *
7
+ * 뷰포트에 보이지 않을 때는 fallback을 표시하고,
8
+ * 뷰포트에 들어오면 loader를 실행하여 데이터를 로드한 후
9
+ * children 함수에 로드된 데이터를 전달하여 렌더링합니다.
10
+ * 한 번 로드되면 다시 되돌리지 않습니다 (triggerOnce=true).
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * // 컴포넌트 lazy loading
15
+ * <Slacker
16
+ * fallback={<ChartSkeleton />}
17
+ * loader={async () => {
18
+ * const { HeavyChart } = await import('./HeavyChart');
19
+ * return HeavyChart;
20
+ * }}
21
+ * >
22
+ * {(Component) => <Component data={data} />}
23
+ * </Slacker>
24
+ *
25
+ * // 데이터 lazy loading
26
+ * <Slacker
27
+ * fallback={<div>Loading data...</div>}
28
+ * loader={async () => {
29
+ * const response = await fetch('/api/data');
30
+ * return response.json();
31
+ * }}
32
+ * >
33
+ * {(data) => (
34
+ * <div>
35
+ * <h2>{data.title}</h2>
36
+ * <p>{data.description}</p>
37
+ * </div>
38
+ * )}
39
+ * </Slacker>
40
+ *
41
+ * // 라이브러리와 데이터 함께 로딩
42
+ * <Slacker
43
+ * fallback={<div>Loading chart library...</div>}
44
+ * loader={async () => {
45
+ * const [{ Chart }, chartData] = await Promise.all([
46
+ * import('chart.js'),
47
+ * fetch('/api/chart-data').then(r => r.json())
48
+ * ]);
49
+ * return { Chart, data: chartData };
50
+ * }}
51
+ * >
52
+ * {({ Chart, data }) => <Chart data={data} />}
53
+ * </Slacker>
54
+ *
55
+ * // 이미지와 메타데이터 함께 로딩
56
+ * <Slacker
57
+ * fallback={<ImageSkeleton />}
58
+ * loader={async () => {
59
+ * const [imageUrl, metadata] = await Promise.all([
60
+ * loadHighResImage(id),
61
+ * fetch(`/api/images/${id}/metadata`).then(r => r.json())
62
+ * ]);
63
+ * return { imageUrl, metadata };
64
+ * }}
65
+ * >
66
+ * {({ imageUrl, metadata }) => (
67
+ * <div>
68
+ * <img src={imageUrl} alt={metadata.title} />
69
+ * <p>{metadata.description}</p>
70
+ * </div>
71
+ * )}
72
+ * </Slacker>
73
+ * ```
74
+ */
75
+ export function Slacker({ children, fallback, loader, threshold = 0.1, rootMargin = "50px", }) {
76
+ const [loadedData, setLoadedData] = useState(null);
77
+ const [isLoading, setIsLoading] = useState(false);
78
+ const [hasLoaded, setHasLoaded] = useState(false);
79
+ const handleIntersect = async (isIntersecting) => {
80
+ if (isIntersecting && !hasLoaded) {
81
+ setIsLoading(true);
82
+ try {
83
+ const data = await loader();
84
+ setLoadedData(data);
85
+ setHasLoaded(true);
86
+ }
87
+ catch (error) {
88
+ console.error('Slacker loader failed:', error);
89
+ }
90
+ finally {
91
+ setIsLoading(false);
92
+ }
93
+ }
94
+ };
95
+ return (_jsx(Observer, { threshold: threshold, rootMargin: rootMargin, fallback: fallback, triggerOnce: true, onIntersect: handleIntersect, children: hasLoaded ? children(loadedData) : null }));
96
+ }
@@ -0,0 +1,4 @@
1
+ export declare const Slot: import("react").ForwardRefExoticComponent<import("react").HTMLAttributes<HTMLElement> & import("react").RefAttributes<HTMLElement>>;
2
+ export declare const Slottable: ({ children }: {
3
+ children: React.ReactNode;
4
+ }) => import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,69 @@
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
+ import { Children, cloneElement, forwardRef, isValidElement } from 'react';
3
+ function mergeProps(slotProps, childProps) {
4
+ const merged = { ...childProps };
5
+ for (const propName in slotProps) {
6
+ const slotProp = slotProps[propName];
7
+ const childProp = merged[propName];
8
+ if (/^on[A-Z]/.test(propName) && typeof slotProp === 'function' && typeof childProp === 'function') {
9
+ merged[propName] = (...args) => {
10
+ childProp(...args);
11
+ slotProp(...args);
12
+ };
13
+ }
14
+ else if (propName === 'style' && typeof slotProp === 'object' && typeof childProp === 'object') {
15
+ merged[propName] = { ...childProp, ...slotProp };
16
+ }
17
+ else if (propName === 'className' && typeof slotProp === 'string' && typeof childProp === 'string') {
18
+ merged[propName] = [childProp, slotProp].filter(Boolean).join(' ');
19
+ }
20
+ else {
21
+ merged[propName] = slotProp;
22
+ }
23
+ }
24
+ return merged;
25
+ }
26
+ function composeRefs(...refs) {
27
+ return (node) => {
28
+ for (const ref of refs) {
29
+ if (typeof ref === 'function') {
30
+ ref(node);
31
+ }
32
+ else if (ref != null) {
33
+ ref.current = node;
34
+ }
35
+ }
36
+ };
37
+ }
38
+ export const Slot = forwardRef((props, ref) => {
39
+ const { children, ...slotProps } = props;
40
+ const childrenArray = Children.toArray(children);
41
+ const slottable = childrenArray.find(isSlottable);
42
+ if (slottable) {
43
+ const newElement = cloneElement(slottable, {
44
+ ...mergeProps(slotProps, slottable.props),
45
+ ref: composeRefs(ref, slottable.ref)
46
+ });
47
+ const newChildren = childrenArray.map((child) => {
48
+ if (child === slottable) {
49
+ return newElement;
50
+ }
51
+ return child;
52
+ });
53
+ return _jsx(_Fragment, { children: newChildren });
54
+ }
55
+ const [child] = childrenArray;
56
+ if (!isValidElement(child)) {
57
+ return null;
58
+ }
59
+ return cloneElement(child, {
60
+ ...mergeProps(slotProps, child.props),
61
+ ref: composeRefs(ref, child.ref)
62
+ });
63
+ });
64
+ function isSlottable(child) {
65
+ return isValidElement(child) && child.type === Slottable;
66
+ }
67
+ export const Slottable = ({ children }) => {
68
+ return _jsx(_Fragment, { children: children });
69
+ };
@@ -0,0 +1,21 @@
1
+ export function createSwitcher(data) {
2
+ function Switch({ children, when, fallback = null }) {
3
+ children.reduce((acc, { type, props }) => {
4
+ if (type !== Match)
5
+ throw new Error("Match 컴포넌트만 사용할 수 있습니다.");
6
+ if (props.case) {
7
+ if (acc.includes(props.case))
8
+ throw new Error(`Duplicate Match key: ${props.case}`);
9
+ else
10
+ acc.push(props.case);
11
+ }
12
+ return acc;
13
+ }, []);
14
+ return children.find(({ props }) => props.case === data[when]) ?? fallback;
15
+ }
16
+ function Match({ children }) {
17
+ return children(data);
18
+ }
19
+ ;
20
+ return { Switch, Match };
21
+ }
@@ -0,0 +1,5 @@
1
+ export * from './experimental/Mount';
2
+ export * from './experimental/Slacker';
3
+ export * from './experimental/Switch';
4
+ export * from './experimental/Slot';
5
+ export * from './hooks/useIntersectionObserver';
@@ -0,0 +1,5 @@
1
+ export * from './experimental/Mount';
2
+ export * from './experimental/Slacker';
3
+ export * from './experimental/Switch';
4
+ export * from './experimental/Slot';
5
+ export * from './hooks/useIntersectionObserver';
@@ -0,0 +1,61 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ export function useIntersectionObserver({ threshold = 0, root = null, rootMargin = "0%", freezeOnceVisible = false, initialIsIntersecting = false, onChange, } = {}) {
3
+ const [element, setElement] = useState(null);
4
+ const [isIntersecting, setIsIntersecting] = useState(initialIsIntersecting);
5
+ const [entry, setEntry] = useState();
6
+ const observerRef = useRef(null);
7
+ const changeCallbackRef = useRef(onChange);
8
+ // Memoize options to prevent unnecessary observer recreation
9
+ const observerOptions = useMemo(() => ({
10
+ threshold,
11
+ root,
12
+ rootMargin,
13
+ }), [threshold, root, rootMargin]);
14
+ const isFrozen = freezeOnceVisible && isIntersecting;
15
+ // Keep callback ref updated
16
+ useEffect(() => {
17
+ changeCallbackRef.current = onChange;
18
+ }, [onChange]);
19
+ // Ref callback to set the element
20
+ const ref = useCallback((node) => {
21
+ setElement(node);
22
+ }, []);
23
+ // Main intersection observer effect
24
+ useEffect(() => {
25
+ if (!element || !("IntersectionObserver" in window) || isFrozen) {
26
+ return;
27
+ }
28
+ const observer = new IntersectionObserver((entries) => {
29
+ const [intersectionEntry] = entries;
30
+ if (!intersectionEntry)
31
+ return;
32
+ const thresholds = Array.isArray(observer.thresholds)
33
+ ? observer.thresholds
34
+ : [observer.thresholds];
35
+ const isCurrentlyIntersecting = intersectionEntry.isIntersecting &&
36
+ thresholds.some((t) => intersectionEntry.intersectionRatio >= t);
37
+ setIsIntersecting(isCurrentlyIntersecting);
38
+ setEntry(intersectionEntry);
39
+ // Call onChange callback if provided
40
+ changeCallbackRef.current?.(isCurrentlyIntersecting, intersectionEntry);
41
+ }, observerOptions);
42
+ observer.observe(element);
43
+ observerRef.current = observer;
44
+ return () => {
45
+ observer.disconnect();
46
+ observerRef.current = null;
47
+ };
48
+ }, [element, observerOptions, isFrozen]);
49
+ // Reset state when element is removed and not frozen
50
+ useEffect(() => {
51
+ if (!element && !freezeOnceVisible && !isFrozen) {
52
+ setIsIntersecting(initialIsIntersecting);
53
+ setEntry(undefined);
54
+ }
55
+ }, [element, freezeOnceVisible, isFrozen, initialIsIntersecting]);
56
+ return useMemo(() => ({
57
+ ref,
58
+ isIntersecting,
59
+ entry,
60
+ }), [ref, isIntersecting, entry]);
61
+ }
package/dist/index.d.ts CHANGED
@@ -3,7 +3,3 @@ export * from './components/Observer';
3
3
  export * from './components/OptionalWrapper';
4
4
  export * from './components/Repeat';
5
5
  export * from './components/Show';
6
- export * from './experimental/Mount';
7
- export * from './experimental/Slacker';
8
- export * from './experimental/Switch';
9
- export * from './hooks/useIntersectionObserver';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './components/For';
2
+ export * from './components/Observer';
3
+ export * from './components/OptionalWrapper';
4
+ export * from './components/Repeat';
5
+ export * from './components/Show';
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ilokesto/utilinent",
3
- "version": "0.0.14",
3
+ "version": "0.0.16",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/ilokesto/utilinent.git"
@@ -8,6 +8,16 @@
8
8
  "sideEffects": false,
9
9
  "types": "dist/index.d.ts",
10
10
  "module": "dist/index.js",
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/index.js",
14
+ "types": "./dist/index.d.ts"
15
+ },
16
+ "./experimental": {
17
+ "import": "./dist/experimental.js",
18
+ "types": "./dist/experimental.d.ts"
19
+ }
20
+ },
11
21
  "files": [
12
22
  "dist"
13
23
  ],
@@ -37,6 +47,6 @@
37
47
  "typescript": "^5.4.5"
38
48
  },
39
49
  "scripts": {
40
- "build": "rm -rf dist && tsc --emitDeclarationOnly"
50
+ "build": "rm -rf dist && tsc"
41
51
  }
42
52
  }