diff --git a/.changeset/outside-click-ref.md b/.changeset/outside-click-ref.md new file mode 100644 index 00000000..01c24e2e --- /dev/null +++ b/.changeset/outside-click-ref.md @@ -0,0 +1,5 @@ +--- +'react-simplikit': minor +--- + +Add `useOutsideClickRef`, which returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to. One ref can be shared by a trigger and its menu, so the elements no longer need their own state. Pass `enabled: false` to stop listening, for example while the menu is closed. A pointer press that starts inside and is released outside is not treated as an outside click. diff --git a/.scripts/commands/generateSkill/template.md b/.scripts/commands/generateSkill/template.md index 1e1715d0..734e4604 100644 --- a/.scripts/commands/generateSkill/template.md +++ b/.scripts/commands/generateSkill/template.md @@ -1,6 +1,6 @@ --- name: react-simplikit -description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit. +description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useOutsideClickRef, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit. license: MIT metadata: author: toss @@ -40,6 +40,7 @@ Backticks in this table mark catalog entries only. | Effect that runs only when a condition holds | `useConditionalEffect` | | Side effect tied to a DOM ref (attach/detach) | `useRefEffect` | | Click / tap outside an element (close menu, modal) | `useOutsideClickEffect` | +| Click / tap outside a trigger and its menu sharing one ref | `useOutsideClickRef` | | Long press / double click | `useLongPress` / `useDoubleClick` | | Element enters or leaves the viewport | `useIntersectionObserver` | | How long an element stayed visible (impression tracking) | `useImpressionRef` / `ImpressionArea` | diff --git a/docs/es/use-cases.md b/docs/es/use-cases.md index 304bb57d..21b82935 100644 --- a/docs/es/use-cases.md +++ b/docs/es/use-cases.md @@ -18,6 +18,7 @@ Llama a los Hooks en el nivel superior de un componente React o de un Hook perso | Limitar la frecuencia de un callback | [useThrottledCallback](/es/hooks/useThrottledCallback) | Un callback con frecuencia limitada al intervalo configurado | | Conservar el estado al recargar | [useStorageState](/es/hooks/useStorageState) | Estado persistido en el almacenamiento del navegador | | Responder a un clic fuera de un elemento | [useOutsideClickEffect](/es/hooks/useOutsideClickEffect) | Una suscripción a clics externos | +| Cerrar un menú con un clic externo | [useOutsideClickRef](/es/hooks/useOutsideClickRef) | Una única ref compartida por el activador y su menú | | Mantener un campo sobre el teclado | [useAvoidKeyboard](/es/hooks/useAvoidKeyboard) | Un estilo para posicionar un elemento fijo | | Insertar separadores entre hijos | [Separated](/es/components/Separated) | Separadores sin uno al final | | Conectar varias refs a un elemento | [mergeRefs](/es/utils/mergeRefs) | Un único callback de ref que pasa el elemento a cada ref | diff --git a/docs/ja/use-cases.md b/docs/ja/use-cases.md index ac563fac..2219cb98 100644 --- a/docs/ja/use-cases.md +++ b/docs/ja/use-cases.md @@ -18,6 +18,7 @@ description: 解決したい問題に合う React ユーティリティを選ぶ | コールバックの呼び出し頻度を制限する | [useThrottledCallback](/ja/hooks/useThrottledCallback) | 指定した間隔で呼び出し頻度を制限するコールバック | | 再読み込み後も状態を保持する | [useStorageState](/ja/hooks/useStorageState) | ブラウザストレージに保存される状態 | | 要素の外側のクリックに反応する | [useOutsideClickEffect](/ja/hooks/useOutsideClickEffect) | 外側のクリックの購読 | +| 外側のクリックでメニューを閉じる | [useOutsideClickRef](/ja/hooks/useOutsideClickRef) | トリガーとメニューで共有する 1 つの ref | | 入力欄をキーボードの上に保つ | [useAvoidKeyboard](/ja/hooks/useAvoidKeyboard) | 固定要素の位置を調整するスタイル | | 子要素の間に区切りを入れる | [Separated](/ja/components/Separated) | 末尾には付かない区切り | | 1 つの要素に複数の ref を接続する | [mergeRefs](/ja/utils/mergeRefs) | 各 ref に要素を渡す 1 つの ref コールバック | diff --git a/docs/ko/use-cases.md b/docs/ko/use-cases.md index 57f02cac..56ea62a2 100644 --- a/docs/ko/use-cases.md +++ b/docs/ko/use-cases.md @@ -18,6 +18,7 @@ description: 해결하려는 문제에 맞는 React 유틸리티 선택하기 | 콜백 호출 빈도 제한하기 | [useThrottledCallback](/ko/hooks/useThrottledCallback) | 설정한 간격으로 호출 빈도를 제한하는 콜백 | | 새로고침 후에도 상태 유지하기 | [useStorageState](/ko/hooks/useStorageState) | 브라우저 저장소에 유지되는 상태 | | 요소 바깥 클릭에 반응하기 | [useOutsideClickEffect](/ko/hooks/useOutsideClickEffect) | 요소 바깥 클릭 구독 | +| 바깥 클릭으로 메뉴 닫기 | [useOutsideClickRef](/ko/hooks/useOutsideClickRef) | 트리거와 메뉴가 함께 쓰는 하나의 ref | | 입력창을 키보드 위에 유지하기 | [useAvoidKeyboard](/ko/hooks/useAvoidKeyboard) | 고정 요소의 위치를 조절하는 스타일 | | 자식 요소 사이에 구분자 넣기 | [Separated](/ko/components/Separated) | 마지막 요소 뒤에는 붙지 않는 구분자 | | 한 요소에 여러 ref 연결하기 | [mergeRefs](/ko/utils/mergeRefs) | 각 ref에 요소를 전달하는 하나의 ref 콜백 | diff --git a/docs/use-cases.md b/docs/use-cases.md index 094f6bad..680f89cc 100644 --- a/docs/use-cases.md +++ b/docs/use-cases.md @@ -18,6 +18,7 @@ Call hooks at the top level of a React component or custom hook. In a framework | Limit callback frequency | [useThrottledCallback](/hooks/useThrottledCallback) | A callback limited to the configured interval | | Keep state across reloads | [useStorageState](/hooks/useStorageState) | State persisted in browser storage | | React to a click outside an element | [useOutsideClickEffect](/hooks/useOutsideClickEffect) | An outside-click subscription | +| Close a menu on an outside click | [useOutsideClickRef](/hooks/useOutsideClickRef) | One ref shared by the trigger and its menu | | Keep an input above the keyboard | [useAvoidKeyboard](/hooks/useAvoidKeyboard) | A style for positioning a fixed element | | Insert separators between children | [Separated](/components/Separated) | Separators without a trailing separator | | Attach multiple refs to one element | [mergeRefs](/utils/mergeRefs) | One ref callback that passes the element to each ref | diff --git a/docs/zh-Hans/use-cases.md b/docs/zh-Hans/use-cases.md index 35e59a06..1b436ceb 100644 --- a/docs/zh-Hans/use-cases.md +++ b/docs/zh-Hans/use-cases.md @@ -18,6 +18,7 @@ description: 根据要解决的问题选择 React 工具函数 | 限制回调频率 | [useThrottledCallback](/zh-Hans/hooks/useThrottledCallback) | 按设定间隔限制调用频率的回调 | | 刷新后保留状态 | [useStorageState](/zh-Hans/hooks/useStorageState) | 保存在浏览器存储中的状态 | | 响应元素外部的点击 | [useOutsideClickEffect](/zh-Hans/hooks/useOutsideClickEffect) | 元素外部点击订阅 | +| 点击外部时关闭菜单 | [useOutsideClickRef](/zh-Hans/hooks/useOutsideClickRef) | 触发按钮和菜单共用的一个 ref | | 让输入框保持在键盘上方 | [useAvoidKeyboard](/zh-Hans/hooks/useAvoidKeyboard) | 用于定位固定元素的样式 | | 在子元素之间插入分隔符 | [Separated](/zh-Hans/components/Separated) | 末尾没有分隔符 | | 为一个元素连接多个 ref | [mergeRefs](/zh-Hans/utils/mergeRefs) | 将元素传递给各个 ref 的单个 ref 回调 | diff --git a/packages/plugin/skills/react-simplikit/SKILL.md b/packages/plugin/skills/react-simplikit/SKILL.md index 6f5b4daa..7ed27687 100644 --- a/packages/plugin/skills/react-simplikit/SKILL.md +++ b/packages/plugin/skills/react-simplikit/SKILL.md @@ -1,6 +1,6 @@ --- name: react-simplikit -description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit. +description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useOutsideClickRef, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit. license: MIT metadata: author: toss @@ -40,6 +40,7 @@ Backticks in this table mark catalog entries only. | Effect that runs only when a condition holds | `useConditionalEffect` | | Side effect tied to a DOM ref (attach/detach) | `useRefEffect` | | Click / tap outside an element (close menu, modal) | `useOutsideClickEffect` | +| Click / tap outside a trigger and its menu sharing one ref | `useOutsideClickRef` | | Long press / double click | `useLongPress` / `useDoubleClick` | | Element enters or leaves the viewport | `useIntersectionObserver` | | How long an element stayed visible (impression tracking) | `useImpressionRef` / `ImpressionArea` | @@ -98,6 +99,7 @@ Backticks in this table mark catalog entries only. | [`useMap`](references/useMap.md) | A React hook that manages a key-value Map as state. | | [`useNetworkStatus`](references/useNetworkStatus.md) | `useNetworkStatus` is a React hook that provides access to the Network Information API. | | [`useOutsideClickEffect`](references/useOutsideClickEffect.md) | `useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s). | +| [`useOutsideClickRef`](references/useOutsideClickRef.md) | `useOutsideClickRef` is a React hook that returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to. | | [`usePageVisibility`](references/usePageVisibility.md) | `usePageVisibility` is a React hook that detects page visibility changes. | | [`usePageVisibilityEffect`](references/usePageVisibilityEffect.md) | `usePageVisibilityEffect` is a React hook that listens to changes in the document's visibility state and triggers a callback. | | [`usePreservedCallback`](references/usePreservedCallback.md) | `usePreservedCallback` is a React hook that maintains a stable reference to a callback function while ensuring it always has access to the latest state or props. | diff --git a/packages/plugin/skills/react-simplikit/references/useOutsideClickEffect.md b/packages/plugin/skills/react-simplikit/references/useOutsideClickEffect.md index 66da3362..dab74968 100644 --- a/packages/plugin/skills/react-simplikit/references/useOutsideClickEffect.md +++ b/packages/plugin/skills/react-simplikit/references/useOutsideClickEffect.md @@ -2,6 +2,7 @@ `useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s). It is useful for closing modals, dropdowns, tooltips, and other UI components when clicking outside. +To treat several elements as inside without keeping each of them in state, use [`useOutsideClickRef`](/hooks/useOutsideClickRef), which returns one ref to attach to all of them. ## Interface diff --git a/packages/plugin/skills/react-simplikit/references/useOutsideClickRef.md b/packages/plugin/skills/react-simplikit/references/useOutsideClickRef.md new file mode 100644 index 00000000..29fa8cc7 --- /dev/null +++ b/packages/plugin/skills/react-simplikit/references/useOutsideClickRef.md @@ -0,0 +1,71 @@ +# useOutsideClickRef + +`useOutsideClickRef` is a React hook that returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to. +Attach the same ref to a trigger, its menu and any portal content, and a press that starts inside and ends outside is not counted as an outside click. + +## Interface + +```ts +function useOutsideClickRef(options: Object): (element: Element | null) => void; +``` + +### Parameters + + + +### Return Value + + + +## Example + +```tsx +import { useOutsideClickRef } from 'react-simplikit'; +import { useState } from 'react'; + +function Dropdown({ onClose }: { onClose: () => void }) { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ + enabled: open, + onOutsideClick: () => { + setOpen(false); + onClose(); + }, + }); + + return ( + <> + + {open && } + + ); +} +``` diff --git a/packages/react-simplikit/src/hooks/useOutsideClickEffect/es/useOutsideClickEffect.md b/packages/react-simplikit/src/hooks/useOutsideClickEffect/es/useOutsideClickEffect.md index 3eb22f51..105b3cf2 100644 --- a/packages/react-simplikit/src/hooks/useOutsideClickEffect/es/useOutsideClickEffect.md +++ b/packages/react-simplikit/src/hooks/useOutsideClickEffect/es/useOutsideClickEffect.md @@ -2,6 +2,7 @@ `useOutsideClickEffect` es un Hook de React que ejecuta un callback cuando ocurre un evento de clic fuera de los contenedores especificados. Es útil para cerrar modales, menús desplegables, descripciones emergentes y otros componentes de la interfaz cuando haces clic fuera de ellos. +Para que varios elementos cuenten como interiores sin guardar cada uno de ellos en el estado, usa [`useOutsideClickRef`](/es/hooks/useOutsideClickRef), que devuelve una única ref que conectas a todos ellos. ## Interfaz diff --git a/packages/react-simplikit/src/hooks/useOutsideClickEffect/ja/useOutsideClickEffect.md b/packages/react-simplikit/src/hooks/useOutsideClickEffect/ja/useOutsideClickEffect.md index 4414c4a5..09901414 100644 --- a/packages/react-simplikit/src/hooks/useOutsideClickEffect/ja/useOutsideClickEffect.md +++ b/packages/react-simplikit/src/hooks/useOutsideClickEffect/ja/useOutsideClickEffect.md @@ -2,6 +2,7 @@ `useOutsideClickEffect` は、指定したコンテナーの外側でクリックイベントが発生したときにコールバックを実行する React フックです。 外側のクリックでモーダル、ドロップダウン、ツールチップなどの UI コンポーネントを閉じる場合に役立ちます。 +複数の要素をそれぞれ状態に保持せずに内側として扱うには、それらすべてに接続する 1 つの ref を返す [`useOutsideClickRef`](/ja/hooks/useOutsideClickRef) を使ってください。 ## インターフェース diff --git a/packages/react-simplikit/src/hooks/useOutsideClickEffect/ko/useOutsideClickEffect.md b/packages/react-simplikit/src/hooks/useOutsideClickEffect/ko/useOutsideClickEffect.md index b4c1f077..9dc5f062 100644 --- a/packages/react-simplikit/src/hooks/useOutsideClickEffect/ko/useOutsideClickEffect.md +++ b/packages/react-simplikit/src/hooks/useOutsideClickEffect/ko/useOutsideClickEffect.md @@ -1,6 +1,6 @@ # useOutsideClickEffect -`useOutsideClickEffect`는 지정한 컨테이너 외부에서 클릭 이벤트가 발생하면 콜백을 실행하는 리액트 훅이에요. 외부를 클릭했을 때 모달, 드롭다운, 툴팁 같은 UI 컴포넌트를 닫는 데 유용해요. +`useOutsideClickEffect`는 지정한 컨테이너 외부에서 클릭 이벤트가 발생하면 콜백을 실행하는 리액트 훅이에요. 외부를 클릭했을 때 모달, 드롭다운, 툴팁 같은 UI 컴포넌트를 닫는 데 유용해요. 버튼과 메뉴처럼 여러 요소를 한 영역으로 묶고 그 바깥을 클릭했을 때 콜백을 실행하려면, 모든 요소에 연결할 ref 하나를 반환하는 [`useOutsideClickRef`](/ko/hooks/useOutsideClickRef)를 사용하세요. ## 인터페이스 diff --git a/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.md b/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.md index 66da3362..dab74968 100644 --- a/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.md +++ b/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.md @@ -2,6 +2,7 @@ `useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s). It is useful for closing modals, dropdowns, tooltips, and other UI components when clicking outside. +To treat several elements as inside without keeping each of them in state, use [`useOutsideClickRef`](/hooks/useOutsideClickRef), which returns one ref to attach to all of them. ## Interface diff --git a/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.ts b/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.ts index bdcea4d3..9eab52f4 100644 --- a/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.ts +++ b/packages/react-simplikit/src/hooks/useOutsideClickEffect/useOutsideClickEffect.ts @@ -8,6 +8,7 @@ type OneOrMore = T | T[]; * @description * `useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s). * It is useful for closing modals, dropdowns, tooltips, and other UI components when clicking outside. + * To treat several elements as inside without keeping each of them in state, use [`useOutsideClickRef`](/hooks/useOutsideClickRef), which returns one ref to attach to all of them. * * @param {HTMLElement | (HTMLElement | null)[] | null} container - A single HTML element, an array of HTML elements or `null` values, or `null`. * `null` entries are ignored. If no HTML elements remain, the callback is not executed. diff --git a/packages/react-simplikit/src/hooks/useOutsideClickEffect/zh-Hans/useOutsideClickEffect.md b/packages/react-simplikit/src/hooks/useOutsideClickEffect/zh-Hans/useOutsideClickEffect.md index f41f9855..1601a285 100644 --- a/packages/react-simplikit/src/hooks/useOutsideClickEffect/zh-Hans/useOutsideClickEffect.md +++ b/packages/react-simplikit/src/hooks/useOutsideClickEffect/zh-Hans/useOutsideClickEffect.md @@ -1,6 +1,6 @@ # useOutsideClickEffect -`useOutsideClickEffect` 是一个在点击事件发生于指定容器之外时触发回调的 React Hook。它适用于在点击外部时关闭模态框、下拉菜单、工具提示以及其他 UI 组件。 +`useOutsideClickEffect` 是一个在点击事件发生于指定容器之外时触发回调的 React Hook。它适用于在点击外部时关闭模态框、下拉菜单、工具提示以及其他 UI 组件。如果要将多个元素视为内部,又不想把每个元素都保存在状态中,可以使用 [`useOutsideClickRef`](/zh-Hans/hooks/useOutsideClickRef),它会返回一个可附加到所有这些元素上的 ref。 ## 接口 diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/es/useOutsideClickRef.md b/packages/react-simplikit/src/hooks/useOutsideClickRef/es/useOutsideClickRef.md new file mode 100644 index 00000000..db002b4f --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/es/useOutsideClickRef.md @@ -0,0 +1,71 @@ +# useOutsideClickRef + +`useOutsideClickRef` es un Hook de React que devuelve una ref de callback y ejecuta `onOutsideClick` cuando ocurre un clic fuera de todos los elementos a los que está conectada la ref. +Conecta la misma ref al activador, a su menú y a cualquier contenido de un portal; una pulsación que empieza dentro y termina fuera no cuenta como un clic externo. + +## Interfaz + +```ts +function useOutsideClickRef(options: Object): (element: Element | null) => void; +``` + +### Parámetros + + + +### Valor de retorno + + + +## Ejemplo + +```tsx +import { useOutsideClickRef } from 'react-simplikit'; +import { useState } from 'react'; + +function Dropdown({ onClose }: { onClose: () => void }) { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ + enabled: open, + onOutsideClick: () => { + setOpen(false); + onClose(); + }, + }); + + return ( + <> + + {open &&
    ...
} + + ); +} +``` diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/index.ts b/packages/react-simplikit/src/hooks/useOutsideClickRef/index.ts new file mode 100644 index 00000000..d112cf2e --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/index.ts @@ -0,0 +1 @@ +export { useOutsideClickRef, type UseOutsideClickRefOptions } from './useOutsideClickRef.ts'; diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/ja/useOutsideClickRef.md b/packages/react-simplikit/src/hooks/useOutsideClickRef/ja/useOutsideClickRef.md new file mode 100644 index 00000000..736577a8 --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/ja/useOutsideClickRef.md @@ -0,0 +1,71 @@ +# useOutsideClickRef + +`useOutsideClickRef` は、コールバック ref を返し、その ref を接続したすべての要素の外側でクリックが発生したときに `onOutsideClick` を実行する React フックです。 +トリガー、そのメニュー、ポータル内のコンテンツに同じ ref を接続してください。内側で押し始めて外側で離した操作は、外側のクリックとして扱われません。 + +## インターフェース + +```ts +function useOutsideClickRef(options: Object): (element: Element | null) => void; +``` + +### パラメータ + + + +### 戻り値 + + + +## 使用例 + +```tsx +import { useOutsideClickRef } from 'react-simplikit'; +import { useState } from 'react'; + +function Dropdown({ onClose }: { onClose: () => void }) { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ + enabled: open, + onOutsideClick: () => { + setOpen(false); + onClose(); + }, + }); + + return ( + <> + + {open &&
    ...
} + + ); +} +``` diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/ko/useOutsideClickRef.md b/packages/react-simplikit/src/hooks/useOutsideClickRef/ko/useOutsideClickRef.md new file mode 100644 index 00000000..d9a5f04f --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/ko/useOutsideClickRef.md @@ -0,0 +1,70 @@ +# useOutsideClickRef + +`useOutsideClickRef`는 콜백 ref를 반환하고, ref를 연결한 모든 요소의 외부에서 클릭이 발생하면 `onOutsideClick`을 호출하는 리액트 훅이에요. 트리거와 메뉴, 포털 콘텐츠에 같은 ref를 연결하면 되고, 내부에서 누르기 시작해 외부에서 뗀 경우는 외부 클릭으로 취급하지 않아요. + +## 인터페이스 + +```ts +function useOutsideClickRef(options: Object): (element: Element | null) => void; +``` + +### 파라미터 + + + +### 반환 값 + + + +## 예시 + +```tsx +import { useOutsideClickRef } from 'react-simplikit'; +import { useState } from 'react'; + +function Dropdown({ onClose }: { onClose: () => void }) { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ + enabled: open, + onOutsideClick: () => { + setOpen(false); + onClose(); + }, + }); + + return ( + <> + + {open &&
    ...
} + + ); +} +``` diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.md b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.md new file mode 100644 index 00000000..29fa8cc7 --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.md @@ -0,0 +1,71 @@ +# useOutsideClickRef + +`useOutsideClickRef` is a React hook that returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to. +Attach the same ref to a trigger, its menu and any portal content, and a press that starts inside and ends outside is not counted as an outside click. + +## Interface + +```ts +function useOutsideClickRef(options: Object): (element: Element | null) => void; +``` + +### Parameters + + + +### Return Value + + + +## Example + +```tsx +import { useOutsideClickRef } from 'react-simplikit'; +import { useState } from 'react'; + +function Dropdown({ onClose }: { onClose: () => void }) { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ + enabled: open, + onOutsideClick: () => { + setOpen(false); + onClose(); + }, + }); + + return ( + <> + + {open &&
    ...
} + + ); +} +``` diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ssr.test.ts b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ssr.test.ts new file mode 100644 index 00000000..e6777f84 --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ssr.test.ts @@ -0,0 +1,26 @@ +/** + * @vitest-environment node + * + * SSR environment tests - runs in Node.js where window is truly undefined + */ +import { createElement } from 'react'; +import { renderToString } from 'react-dom/server'; +import { describe, expect, it, vi } from 'vitest'; + +import { useOutsideClickRef } from './useOutsideClickRef.ts'; + +describe('useOutsideClickRef SSR environment', () => { + it('should be safe on server side rendering', () => { + const onOutsideClick = vi.fn(); + + function Component() { + const ref = useOutsideClickRef({ onOutsideClick }); + + return createElement('div', { ref }, 'Inside'); + } + + expect(typeof window).toBe('undefined'); + expect(renderToString(createElement(Component))).toBe('
Inside
'); + expect(onOutsideClick).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.test.tsx b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.test.tsx new file mode 100644 index 00000000..8cae419a --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.test.tsx @@ -0,0 +1,670 @@ +import { StrictMode, Suspense, useState } from 'react'; +import { flushSync } from 'react-dom'; +import { act, fireEvent, render, renderHook, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import { useOutsideClickRef } from './useOutsideClickRef.ts'; + +// `fireEvent.click` defaults to `detail: 0`, which is how keyboard clicks arrive. +// A pointer click carries a click count and is preceded by its own `pointerdown`. +function pointerClick(element: Element) { + fireEvent.pointerDown(element); + fireEvent.click(element, { detail: 1 }); +} + +function Container({ onOutsideClick, enabled }: { onOutsideClick: () => void; enabled?: boolean }) { + const ref = useOutsideClickRef({ onOutsideClick, enabled }); + + return ( + <> +
+ +
+ + + ); +} + +describe('useOutsideClickRef', () => { + it('calls the callback when clicking outside the attached element', () => { + const onOutsideClick = vi.fn(); + render(); + + pointerClick(screen.getByTestId('outside')); + + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('does not call the callback when clicking inside or on a descendant', () => { + const onOutsideClick = vi.fn(); + render(); + + pointerClick(screen.getByTestId('container')); + pointerClick(screen.getByTestId('inside')); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it('treats every element sharing the ref as inside, including svg', () => { + const onOutsideClick = vi.fn(); + + function Shared() { + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( + <> + +
+ Menu +
+ + + + ); + } + + render(); + + pointerClick(screen.getByTestId('trigger')); + pointerClick(screen.getByTestId('menu')); + pointerClick(screen.getByTestId('icon')); + expect(onOutsideClick).not.toHaveBeenCalled(); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('keeps the same ref across renders', () => { + const { result, rerender } = renderHook(() => useOutsideClickRef({ onOutsideClick: () => {} })); + const firstRef = result.current; + + rerender(); + + expect(result.current).toBe(firstRef); + }); + + it('calls the latest callback after re-render', () => { + const first = vi.fn(); + const second = vi.fn(); + const { rerender } = render(); + + rerender(); + pointerClick(screen.getByTestId('outside')); + + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); + + it('keeps the press origin when the callback changes mid-press', () => { + const first = vi.fn(); + const second = vi.fn(); + const { rerender } = render(); + + fireEvent.pointerDown(screen.getByTestId('inside')); + rerender(); + fireEvent.click(screen.getByTestId('outside'), { detail: 1 }); + expect(second).not.toHaveBeenCalled(); + + pointerClick(screen.getByTestId('outside')); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); + + it('still treats the remaining element as inside after one of them unmounts', () => { + const onOutsideClick = vi.fn(); + + function Toggle({ open }: { open: boolean }) { + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( + <> + + {open &&
Menu
} + + + ); + } + + const { rerender } = render(); + rerender(); + + pointerClick(screen.getByTestId('trigger')); + expect(onOutsideClick).not.toHaveBeenCalled(); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('does not call the callback once every attached element has unmounted', () => { + const onOutsideClick = vi.fn(); + + function Menu({ open }: { open: boolean }) { + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( + <> + {open &&
Menu
} + + + ); + } + + const { rerender } = render(); + rerender(); + + pointerClick(screen.getByTestId('outside')); + pointerClick(document.body); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it('calls the callback on every outside click while an always-rendered trigger holds the ref', () => { + const onOutsideClick = vi.fn(); + + function Dropdown({ open }: { open: boolean }) { + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( + <> + + {open &&
Menu
} + + + ); + } + + render(); + + pointerClick(screen.getByTestId('outside')); + pointerClick(screen.getByTestId('outside')); + + expect(onOutsideClick).toHaveBeenCalledTimes(2); + }); + + // React 18 is not installed here, so its `ref(null)` call on detach is made by hand. + it('handles the React 18 null call without knowing which element left (simulated)', () => { + const onOutsideClick = vi.fn(); + const { result } = renderHook(() => useOutsideClickRef({ onOutsideClick })); + const a = document.createElement('div'); + const b = document.createElement('div'); + document.body.append(a, b); + + result.current(a); + result.current(b); + result.current(null); + a.remove(); + + pointerClick(document.body); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + + pointerClick(b); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + + b.remove(); + pointerClick(document.body); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('covers an element the component does not render when the ref is called by hand', () => { + const onOutsideClick = vi.fn(); + const { result } = renderHook(() => useOutsideClickRef({ onOutsideClick })); + const toolbar = document.createElement('div'); + document.body.append(toolbar); + + result.current(toolbar); + + pointerClick(toolbar); + expect(onOutsideClick).not.toHaveBeenCalled(); + + pointerClick(document.body); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + + toolbar.remove(); + }); + + it('drops disconnected elements when another element attaches', () => { + const onOutsideClick = vi.fn(); + const { result } = renderHook(() => useOutsideClickRef({ onOutsideClick })); + const a = document.createElement('div'); + const b = document.createElement('div'); + document.body.append(a, b); + + result.current(a); + a.remove(); + result.current(b); + // `a` is back in the document but not attached again, so only the cleanup on attach makes it count as outside + document.body.append(a); + + pointerClick(a); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + + a.remove(); + b.remove(); + }); + + it('registers listeners once under StrictMode', () => { + const onOutsideClick = vi.fn(); + render( + + + + ); + + pointerClick(screen.getByTestId('inside')); + expect(onOutsideClick).not.toHaveBeenCalled(); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('decides before the target removes itself during the click', () => { + const onOutsideClick = vi.fn(); + render(); + const inside = screen.getByTestId('inside'); + inside.addEventListener('click', () => inside.remove()); + + pointerClick(inside); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it('decides before an inside handler removes the menu during the click', () => { + const onOutsideClick = vi.fn(); + + function Dropdown() { + const [open, setOpen] = useState(true); + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( + <> + + {open && ( +
+ +
+ )} + + ); + } + + render(); + + // A keyboard click has no press origin to fall back on. + fireEvent.click(screen.getByTestId('item')); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it("calls the callback before the clicked element's own handlers", () => { + const calls: string[] = []; + + function Menu() { + const ref = useOutsideClickRef({ onOutsideClick: () => calls.push('outside') }); + + return ( + <> +
Menu
+ + + ); + } + + render(); + + pointerClick(screen.getByTestId('apply')); + + expect(calls).toEqual(['outside', 'apply']); + }); + + it('still calls the callback when an outside handler stops propagation', () => { + const onOutsideClick = vi.fn(); + render(); + const outside = screen.getByTestId('outside'); + outside.addEventListener('click', event => event.stopPropagation()); + + pointerClick(outside); + + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('does not close a menu that mounts during the click that opens it', () => { + const onOutsideClick = vi.fn(); + + function Menu() { + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( +
+ Menu +
+ ); + } + + function App() { + const [open, setOpen] = useState(false); + + return ( + <> + {/* In a browser, React renders a click's update and runs its effects before the click reaches `document`. + `flushSync` does the same here. */} + + {open && } + + ); + } + + render(); + + pointerClick(screen.getByTestId('trigger')); + expect(onOutsideClick).not.toHaveBeenCalled(); + expect(screen.getByTestId('menu')).toBeDefined(); + + pointerClick(screen.getByTestId('trigger')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('does not close a menu whose `enabled` turns true during the opening click', () => { + const onOutsideClick = vi.fn(); + + function Dropdown() { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ onOutsideClick, enabled: open }); + + return ( + <> + + {open && ( +
+ Menu +
+ )} + + + ); + } + + render(); + + pointerClick(screen.getByTestId('trigger')); + expect(onOutsideClick).not.toHaveBeenCalled(); + expect(screen.getByTestId('menu')).toBeDefined(); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + it('keeps the press origin when `enabled` turns true during that press', () => { + const onOutsideClick = vi.fn(); + + function Dropdown() { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ onOutsideClick, enabled: open }); + + return ( + <> + + {open &&
Menu
} + + ); + } + + render(); + + fireEvent.pointerDown(screen.getByTestId('trigger')); + // Dragging from the trigger and releasing elsewhere sends the click to a common ancestor. + fireEvent.click(document.body, { detail: 1 }); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it('does not call the callback while disabled', () => { + const onOutsideClick = vi.fn(); + const { rerender } = render(); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).not.toHaveBeenCalled(); + + rerender(); + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('stops calling the callback once `enabled` turns false', () => { + const onOutsideClick = vi.fn(); + const { rerender } = render(); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + + rerender(); + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('treats a pointer press that starts outside and ends inside as an outside click', () => { + const onOutsideClick = vi.fn(); + render(); + + fireEvent.pointerDown(screen.getByTestId('outside')); + // The browser sends the click to the common ancestor of the press and release targets. + fireEvent.click(document.body, { detail: 1 }); + + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('keeps the press origin when an inside pointerdown handler removes the menu', () => { + const onOutsideClick = vi.fn(); + + function Dropdown() { + const [open, setOpen] = useState(true); + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( + <> + + {open && ( +
+ +
+ )} + + ); + } + + render(); + + fireEvent.pointerDown(screen.getByTestId('item')); + // The pressed item is gone, so the click lands on an ancestor outside every remaining element. + fireEvent.click(document.body, { detail: 1 }); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it('treats a click inside an open shadow root as inside', () => { + const onOutsideClick = vi.fn(); + const { result } = renderHook(() => useOutsideClickRef({ onOutsideClick })); + const host = document.createElement('div'); + document.body.append(host); + const shadowRoot = host.attachShadow({ mode: 'open' }); + const inner = document.createElement('button'); + shadowRoot.append(inner); + + result.current(inner); + + fireEvent.pointerDown(inner, { composed: true }); + fireEvent.click(inner, { detail: 1, composed: true }); + expect(onOutsideClick).not.toHaveBeenCalled(); + + pointerClick(document.body); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + + host.remove(); + }); + + it('does not treat a pointer press that starts inside and ends outside as an outside click', () => { + const onOutsideClick = vi.fn(); + render(); + + fireEvent.pointerDown(screen.getByTestId('inside')); + // The browser sends the click to the common ancestor of the press and release targets. + fireEvent.click(document.body, { detail: 1 }); + expect(onOutsideClick).not.toHaveBeenCalled(); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('ignores a press flag left by a press that never produced a click', () => { + const onOutsideClick = vi.fn(); + render(); + + fireEvent.pointerDown(screen.getByTestId('inside')); + fireEvent.click(screen.getByTestId('outside')); + + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('ignores a press flag left by a cancelled touch press', () => { + const onOutsideClick = vi.fn(); + render(); + + fireEvent.pointerDown(screen.getByTestId('inside')); + fireEvent.pointerCancel(screen.getByTestId('inside')); + fireEvent.click(screen.getByTestId('outside')); + + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('ignores a press flag left by a right-button press', () => { + const onOutsideClick = vi.fn(); + render(); + + fireEvent.pointerDown(screen.getByTestId('inside'), { button: 2 }); + fireEvent.contextMenu(screen.getByTestId('inside')); + fireEvent.click(screen.getByTestId('outside')); + + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + it('calls the callback for a keyboard click outside', () => { + const onOutsideClick = vi.fn(); + render(); + + fireEvent.click(screen.getByTestId('outside')); + + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + // Documents a known limit: the ref ignores `ref(null)`, so a panel that Suspense hides stays attached. + it('keeps an element hidden by Suspense as attached', async () => { + const onOutsideClick = vi.fn(); + const never = new Promise(() => {}); + + function Suspender({ suspend }: { suspend: boolean }) { + if (suspend) { + throw never; + } + + return null; + } + + function App({ suspend }: { suspend: boolean }) { + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( + <> + Loading}> +
+ Panel +
+ +
+ + + ); + } + + const { rerender } = render(); + const panel = screen.getByTestId('panel'); + + await act(async () => { + rerender(); + }); + + expect(panel.isConnected).toBe(true); + expect(panel.style.display).toBe('none'); + + pointerClick(screen.getByTestId('outside')); + expect(onOutsideClick).toHaveBeenCalledTimes(1); + }); + + // Documents a known limit: `ref(null)` cannot tell which element left, so an element the ref moves away from + // stays attached while it is still rendered. A ref cleanup would fix it, but React 18 ignores the cleanup and + // React 19 also runs it when Suspense hides content (see the test above). Revisit once only React 19+ is supported. + it('keeps an element the ref moved away from as attached while it stays rendered', () => { + const onOutsideClick = vi.fn(); + + function List({ selected }: { selected: number }) { + const ref = useOutsideClickRef({ onOutsideClick }); + + return ( +
    + {[0, 1].map(i => ( +
  • + Item {i} +
  • + ))} +
+ ); + } + + const { rerender } = render(); + rerender(); + + pointerClick(screen.getByTestId('item-0')); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it('ignores a click event without a target', () => { + const onOutsideClick = vi.fn(); + render(); + const nullTargetEvent = new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }); + Object.defineProperty(nullTargetEvent, 'target', { value: null }); + + document.dispatchEvent(nullTargetEvent); + + expect(onOutsideClick).not.toHaveBeenCalled(); + }); + + it('removes the listeners on unmount', () => { + const onOutsideClick = vi.fn(); + const { result, unmount } = renderHook(() => useOutsideClickRef({ onOutsideClick })); + // An element that stays in the document keeps the set non-empty, so a leaked listener would still call back. + const toolbar = document.createElement('div'); + document.body.append(toolbar); + result.current(toolbar); + + unmount(); + pointerClick(document.body); + + expect(onOutsideClick).not.toHaveBeenCalled(); + + toolbar.remove(); + }); +}); diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ts b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ts new file mode 100644 index 00000000..ca1c07e2 --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ts @@ -0,0 +1,133 @@ +import { useCallback, useEffect, useRef } from 'react'; + +import { usePreservedCallback } from '../usePreservedCallback/index.ts'; + +export type UseOutsideClickRefOptions = { + onOutsideClick: () => void; + enabled?: boolean; +}; + +/** + * @description + * `useOutsideClickRef` is a React hook that returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to. + * Attach the same ref to a trigger, its menu and any portal content, and a press that starts inside and ends outside is not counted as an outside click. + * + * @param {Object} options - Options for detecting outside clicks. + * @param {() => void} options.onOutsideClick - A function that is executed when a click happens outside every attached element. + * It runs before the clicked element's own `onClick`. + * @param {boolean} [options.enabled=true] - Whether to detect outside clicks. While `false`, `onOutsideClick` is not called. + * + * @returns {(element: Element | null) => void} A callback ref to pass to the `ref` attribute of each element that counts as inside. + * It keeps the same identity across renders. + * + * @example + * import { useOutsideClickRef } from 'react-simplikit'; + * import { useState } from 'react'; + * + * function Dropdown({ onClose }: { onClose: () => void }) { + * const [open, setOpen] = useState(false); + * const ref = useOutsideClickRef({ + * enabled: open, + * onOutsideClick: () => { + * setOpen(false); + * onClose(); + * }, + * }); + * + * return ( + * <> + * + * {open &&
    ...
} + * + * ); + * } + */ +export function useOutsideClickRef({ + onOutsideClick, + enabled = true, +}: UseOutsideClickRefOptions): (element: Element | null) => void { + const elementsRef = useRef>(new Set()); + // Kept outside the click subscription, so a press that starts while `enabled` is turning true + // (e.g. a trigger that opens on `pointerdown`) is still remembered when its click arrives. + const pressStartedInsideRef = useRef(false); + const handleOutsideClick = usePreservedCallback(onOutsideClick); + + useEffect(function subscribePointerDown() { + function handlePointerDown(event: PointerEvent) { + pressStartedInsideRef.current = isEventInside(elementsRef.current, event); + } + + document.addEventListener('pointerdown', handlePointerDown, { capture: true }); + + return () => { + document.removeEventListener('pointerdown', handlePointerDown, { capture: true }); + }; + }, []); + + useEffect( + function subscribeOutsideClick() { + if (!enabled) { + return; + } + + const elements = elementsRef.current; + + // Capture phase: decide before the target's own handlers run, since they may remove the target + // from the document or stop propagation. It also never sees the click that mounted this hook, + // because that click has already passed `document` on its way down. + function handleClick(event: MouseEvent) { + // A click without a click count (keyboard, `element.click()`) has no press of its own, + // so a flag left by a press that never produced a click must not apply to it. + const startedInside = pressStartedInsideRef.current && event.detail > 0; + pressStartedInsideRef.current = false; + + removeDisconnected(elements); + + if (elements.size === 0 || event.target == null) { + return; + } + + if (startedInside || isEventInside(elements, event)) { + return; + } + + handleOutsideClick(); + } + + document.addEventListener('click', handleClick, { capture: true }); + + return () => { + document.removeEventListener('click', handleClick, { capture: true }); + }; + }, + [enabled, handleOutsideClick] + ); + + return useCallback(function attachElement(element: Element | null) { + // React calls a ref that returns no cleanup with `null` on detach (React 18 ignores a returned cleanup anyway), + // so `null` cannot tell which element left. Elements that left the document are dropped later. + if (element == null) { + return; + } + + removeDisconnected(elementsRef.current); + elementsRef.current.add(element); + }, []); +} + +function removeDisconnected(elements: Set) { + elements.forEach(element => { + if (!element.isConnected) { + elements.delete(element); + } + }); +} + +// `composedPath()` includes the nodes inside open shadow roots, which `event.target` hides behind the host. +function isEventInside(elements: Set, event: Event): boolean { + const path = event.composedPath(); + + return Array.from(elements).some(element => path.includes(element)); +} diff --git a/packages/react-simplikit/src/hooks/useOutsideClickRef/zh-Hans/useOutsideClickRef.md b/packages/react-simplikit/src/hooks/useOutsideClickRef/zh-Hans/useOutsideClickRef.md new file mode 100644 index 00000000..bdb2a9da --- /dev/null +++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/zh-Hans/useOutsideClickRef.md @@ -0,0 +1,70 @@ +# useOutsideClickRef + +`useOutsideClickRef` 是一个返回回调 ref 的 React Hook。当点击发生在该 ref 附加到的所有元素之外时,它会调用 `onOutsideClick`。将同一个 ref 附加到触发按钮、其菜单以及 portal 内容上即可;在内部按下、在外部松开的操作不会被视为外部点击。 + +## 接口 + +```ts +function useOutsideClickRef(options: Object): (element: Element | null) => void; +``` + +### 参数 + + + +### 返回值 + + + +## 示例 + +```tsx +import { useOutsideClickRef } from 'react-simplikit'; +import { useState } from 'react'; + +function Dropdown({ onClose }: { onClose: () => void }) { + const [open, setOpen] = useState(false); + const ref = useOutsideClickRef({ + enabled: open, + onOutsideClick: () => { + setOpen(false); + onClose(); + }, + }); + + return ( + <> + + {open &&
    ...
} + + ); +} +``` diff --git a/packages/react-simplikit/src/index.ts b/packages/react-simplikit/src/index.ts index e1c00d3b..3aab6cac 100644 --- a/packages/react-simplikit/src/index.ts +++ b/packages/react-simplikit/src/index.ts @@ -33,6 +33,7 @@ export { useNetworkStatus, } from './hooks/useNetworkStatus/index.ts'; export { useOutsideClickEffect } from './hooks/useOutsideClickEffect/index.ts'; +export { useOutsideClickRef, type UseOutsideClickRefOptions } from './hooks/useOutsideClickRef/index.ts'; export { type PageVisibility, usePageVisibility, type VisibilityState } from './hooks/usePageVisibility/index.ts'; export { usePageVisibilityEffect, useVisibilityEvent } from './hooks/usePageVisibilityEffect/index.ts'; export { usePreservedCallback } from './hooks/usePreservedCallback/index.ts';