@fibery/react 1.0.0

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.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @fibery/react
2
+
3
+ This package contains all React-related utilities that may be consumed by other packages
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@fibery/react",
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "license": "UNLICENSED",
6
+ "files": ["src"],
7
+ "scripts": {
8
+ "lint": "eslint .",
9
+ "test": "jest",
10
+ "test:ci": "yarn test --coverage --reporters=default --reporters=jest-junit"
11
+ },
12
+ "peerDependencies": {
13
+ "react": "^16.14"
14
+ },
15
+ "dependencies": {
16
+ "@fibery/helpers": "1.0.0"
17
+ },
18
+ "devDependencies": {
19
+ "@testing-library/react": "12.1.3",
20
+ "@testing-library/react-hooks": "7.0.2",
21
+ "@fibery/babel-preset": "7.2.0",
22
+ "@fibery/eslint-config": "7.1.0",
23
+ "jest": "27.5.1",
24
+ "jest-junit": "13.0.0",
25
+ "react": "16.14",
26
+ "react-test-renderer": "16.4.0"
27
+ },
28
+ "jest": {
29
+ "coveragePathIgnorePatterns": [
30
+ "/node_modules/"
31
+ ],
32
+ "collectCoverageFrom": [
33
+ "src/**/*.{js,jsx,ts,tsx}",
34
+ "!src/**/*.d.ts"
35
+ ],
36
+ "coverageReporters": [
37
+ "text",
38
+ "cobertura"
39
+ ]
40
+ }
41
+ }
@@ -0,0 +1,19 @@
1
+ import * as React from "react";
2
+
3
+ export const createContext = <CtxType>(
4
+ displayName: string,
5
+ defaultCtx?: CtxType
6
+ ): [React.Provider<CtxType>, () => CtxType] => {
7
+ const Context = React.createContext(defaultCtx as CtxType);
8
+
9
+ Context.displayName = displayName;
10
+
11
+ function useContext() {
12
+ const ctx = React.useContext(Context);
13
+ if (ctx === undefined) {
14
+ throw new Error(`${displayName} consumer must be used within ${displayName}.Provider`);
15
+ }
16
+ return ctx;
17
+ }
18
+ return [Context.Provider, useContext];
19
+ };
@@ -0,0 +1,5 @@
1
+ import {RefObject} from "react";
2
+
3
+ /** Returns current value if refOrValue is RefObject otherwise returns itself */
4
+ export const getRefValue = <Value>(refOrValue: RefObject<Value> | Value | null): Value | null =>
5
+ refOrValue && "current" in refOrValue ? refOrValue.current : refOrValue;
@@ -0,0 +1,5 @@
1
+ import {Children} from "react";
2
+
3
+ /** React helper which checks whether children has at least one truthy child */
4
+ export const hasNonEmptyChild = (children: React.ReactNode): boolean =>
5
+ Children.toArray(children).some((value) => Boolean(value));
@@ -0,0 +1,3 @@
1
+ export const stopPropagation = (e: React.SyntheticEvent): void => {
2
+ e.stopPropagation();
3
+ };
@@ -0,0 +1,19 @@
1
+ import {useCallback, useLayoutEffect, useRef} from "react";
2
+
3
+ /**
4
+ * Hook to wrap callback in ref
5
+ * so it doesn't trigger re-renders and remains up-to-date
6
+ *
7
+ * Could be replaced with https://github.com/reactjs/rfcs/pull/220 in future
8
+ */
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ export const useCallbackRef = <T extends (...args: any[]) => any>(callback?: T): T => {
11
+ const callbackRef = useRef(callback);
12
+
13
+ useLayoutEffect(() => {
14
+ callbackRef.current = callback;
15
+ });
16
+
17
+ // eslint-disable-next-line react-hooks/exhaustive-deps
18
+ return useCallback(((...args) => callbackRef.current?.(...args)) as T, []);
19
+ };
@@ -0,0 +1,26 @@
1
+ import React, {useCallback} from "react";
2
+
3
+ const composeRefs = <T>(...refs: React.Ref<T>[]) => {
4
+ return function setRefs(node: T) {
5
+ refs.forEach((ref) => {
6
+ if (!ref) {
7
+ return;
8
+ }
9
+
10
+ if (typeof ref === "function") {
11
+ ref(node);
12
+ } else {
13
+ (ref as React.MutableRefObject<T>).current = node;
14
+ }
15
+ });
16
+ };
17
+ };
18
+
19
+ /**
20
+ * Hook to compose multiple refs
21
+ * Accepts callback refs and RefObject(s)
22
+ */
23
+ export const useComposedRefs = <T>(...refs: React.Ref<T>[]) => {
24
+ // eslint-disable-next-line react-hooks/exhaustive-deps
25
+ return useCallback(composeRefs(...refs), refs);
26
+ };
@@ -0,0 +1 @@
1
+ export * from "./use-controllable-state";
@@ -0,0 +1,45 @@
1
+ import {act, renderHook} from "@testing-library/react-hooks";
2
+ import {useControllableState} from "./use-controllable-state";
3
+
4
+ describe("useControllableState", () => {
5
+ describe("uncontrolled", () => {
6
+ it("should work for uncontrolled", () => {
7
+ const onChange = jest.fn();
8
+ const {result} = renderHook(() => useControllableState({onChange}));
9
+ expect(result.current[0]).toBe(undefined);
10
+
11
+ act(() => {
12
+ result.current[1](true);
13
+ });
14
+
15
+ expect(result.current[0]).toBe(true);
16
+ expect(onChange).toHaveBeenCalledWith(true);
17
+ });
18
+ it("should work for uncontrolled with default value", () => {
19
+ const onChange = jest.fn();
20
+ const {result} = renderHook(() => useControllableState({defaultValue: true, onChange}));
21
+ expect(result.current[0]).toBe(true);
22
+
23
+ act(() => {
24
+ result.current[1](false);
25
+ });
26
+
27
+ expect(result.current[0]).toBe(false);
28
+ expect(onChange).toHaveBeenCalledWith(false);
29
+ });
30
+ });
31
+ describe("controlled", () => {
32
+ it("should not change internal state. It's controlled by 'value'", () => {
33
+ const onChange = jest.fn();
34
+ const {result} = renderHook(() => useControllableState({value: true, onChange}));
35
+ expect(result.current[0]).toEqual(true);
36
+
37
+ act(() => {
38
+ result.current[1](false);
39
+ });
40
+
41
+ expect(result.current[0]).toEqual(true);
42
+ expect(onChange).toHaveBeenCalledWith(false);
43
+ });
44
+ });
45
+ });
@@ -0,0 +1,46 @@
1
+ import {Dispatch, SetStateAction, useCallback, useState} from "react";
2
+ import {useCallbackRef} from "../use-callback-ref";
3
+
4
+ type UseControllableStateProps<TState> = {
5
+ /** value to be used in controlled mode */
6
+ value?: TState;
7
+ /** initial value to be used in uncontrolled mode */
8
+ defaultValue?: TState;
9
+ /** callback for value changes */
10
+ onChange?: (state: TState) => unknown;
11
+ };
12
+
13
+ /**
14
+ * React hook to support both controlled/uncontrolled modes
15
+ * @see https://reactjs.org/docs/uncontrolled-components.html
16
+ */
17
+ export const useControllableState = <TState>({
18
+ value,
19
+ defaultValue,
20
+ onChange,
21
+ }: UseControllableStateProps<TState>): [TState, Dispatch<SetStateAction<TState>>] => {
22
+ const [uncontrolledState, setUncontrolledState] = useState(defaultValue as TState);
23
+ const onChangeState = useCallbackRef(onChange);
24
+
25
+ const isControlled = value !== undefined;
26
+ const state = isControlled ? value : uncontrolledState;
27
+
28
+ const setState = useCallback<Dispatch<SetStateAction<TState>>>(
29
+ (nextValue) => {
30
+ const nextState = nextValue instanceof Function ? nextValue(state) : nextValue;
31
+
32
+ if (state === nextState) {
33
+ return;
34
+ }
35
+
36
+ if (!isControlled) {
37
+ setUncontrolledState(nextState);
38
+ }
39
+
40
+ onChangeState(nextState as TState);
41
+ },
42
+ [isControlled, onChangeState, state]
43
+ );
44
+
45
+ return [state, setState];
46
+ };
@@ -0,0 +1,33 @@
1
+ import {useLayoutEffect, useRef} from "react";
2
+ import {useCallbackRef} from "./use-callback-ref";
3
+
4
+ type OnFocusOutside = (event: FocusEvent) => void;
5
+
6
+ /**
7
+ * Hook to react on focus moving outside of react tree including portals
8
+ *
9
+ * https://github.com/facebook/react/issues/19637#issuecomment-850412650
10
+ */
11
+ export const useFocusOutside = (onFocusOutside?: OnFocusOutside) => {
12
+ const handleFocusOutside = useCallbackRef(onFocusOutside);
13
+ const isFocusInsideReactTreeRef = useRef(false);
14
+
15
+ useLayoutEffect(() => {
16
+ const handleFocus = (event: FocusEvent) => {
17
+ if (!isFocusInsideReactTreeRef.current) {
18
+ handleFocusOutside(event);
19
+ }
20
+ };
21
+ document.addEventListener("focusin", handleFocus);
22
+ return () => document.removeEventListener("focusin", handleFocus);
23
+ }, [handleFocusOutside]);
24
+
25
+ return {
26
+ onFocusCapture: () => {
27
+ isFocusInsideReactTreeRef.current = true;
28
+ },
29
+ onBlurCapture: () => {
30
+ isFocusInsideReactTreeRef.current = false;
31
+ },
32
+ };
33
+ };
@@ -0,0 +1,42 @@
1
+ import {RefObject, useLayoutEffect} from "react";
2
+ import {getRefValue} from "./get-ref-value";
3
+ import {useCallbackRef} from "./use-callback-ref";
4
+ import {getResizeListener, ResizeListenerCallback} from "@fibery/helpers/utils/resize-listener";
5
+
6
+ /**
7
+ * React hook to observe provided element with ResizeObserver
8
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
9
+ */
10
+ export const useResizeObserver = <TargetElement extends HTMLElement>(
11
+ /** React ref created by `useRef()` or an HTML element */
12
+ target: RefObject<TargetElement> | TargetElement | null,
13
+ /**Invoked with a single `ResizeObserverEntry` any time the `target` resizes */
14
+ callback: ResizeListenerCallback
15
+ ): ResizeObserver => {
16
+ const resizeListener = getResizeListener();
17
+ const onResize = useCallbackRef(callback);
18
+
19
+ useLayoutEffect(() => {
20
+ let active = true;
21
+ const element = getRefValue(target);
22
+ if (!element) {
23
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
24
+ return () => {};
25
+ }
26
+
27
+ const observerCallback: ResizeListenerCallback = (entry, observer) => {
28
+ if (active) {
29
+ onResize(entry, observer);
30
+ }
31
+ };
32
+
33
+ resizeListener.subscribe(element, observerCallback);
34
+
35
+ return () => {
36
+ active = false;
37
+ resizeListener.unsubscribe(element, observerCallback);
38
+ };
39
+ }, [onResize, resizeListener, target]);
40
+
41
+ return resizeListener.observer;
42
+ };
@@ -0,0 +1,43 @@
1
+ import {RefObject, useLayoutEffect, useState} from "react";
2
+ import {getRefValue} from "./get-ref-value";
3
+ import {useResizeObserver} from "./use-resize-observer";
4
+
5
+ type Size = {
6
+ width: number;
7
+ height: number;
8
+ };
9
+
10
+ const calculateSize = <TargetElement extends HTMLElement>(element: TargetElement | null) => {
11
+ return {
12
+ width: element?.offsetWidth || 0,
13
+ height: element?.offsetHeight || 0,
14
+ };
15
+ };
16
+
17
+ /**
18
+ * React hook for watching size changes of HTML elements
19
+ */
20
+ export const useSize = <TargetElement extends HTMLElement>(
21
+ /** React ref created by `useRef()` or an HTML element */
22
+ target: RefObject<TargetElement> | TargetElement | null
23
+ ): Size => {
24
+ const [size, setSize] = useState<Size>(() => {
25
+ const element = getRefValue(target);
26
+ return calculateSize(element);
27
+ });
28
+
29
+ useLayoutEffect(() => {
30
+ const element = getRefValue(target);
31
+ if (!element) {
32
+ return;
33
+ }
34
+ setSize(calculateSize(element));
35
+ }, [target]);
36
+
37
+ useResizeObserver(target, (entry) => {
38
+ const element = entry.target as HTMLElement;
39
+ setSize(calculateSize(element));
40
+ });
41
+
42
+ return size;
43
+ };
package/src/wrap.tsx ADDED
@@ -0,0 +1,33 @@
1
+ type OwnProps<Wrapper extends React.ElementType> = {
2
+ if: boolean;
3
+ with: Wrapper;
4
+ children: React.ReactNode;
5
+ };
6
+
7
+ type Props<Wrapper extends React.ElementType> = OwnProps<Wrapper> &
8
+ Omit<React.ComponentProps<Wrapper>, keyof OwnProps<Wrapper>>;
9
+ /**
10
+ * React component to conditionally wrap children
11
+ * @example
12
+ * pass react Element
13
+ * ```
14
+ * <Wrap if={clickable} with={AwesomeButton}>
15
+ * Hello
16
+ * </Wrap>
17
+ * ```
18
+ * or use html tag names
19
+ * ```
20
+ * <Wrap if={clickable} with="button">
21
+ * Hello
22
+ * </Wrap>
23
+ * ```
24
+ */
25
+ export const Wrap = <T extends React.ElementType>({
26
+ if: condition,
27
+ with: With,
28
+ children,
29
+ ...rest
30
+ }: Props<T>): JSX.Element => {
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
+ return condition ? <With {...(rest as any)}>{children}</With> : <>{children}</>;
33
+ };