UNPKG

@ariakit/react-core

Version:

Ariakit React core

104 lines (102 loc) 2.87 kB
"use client"; import { useFormContext } from "../__chunks/ICLJE26C.js"; import { useCollectionItem } from "../__chunks/DTXGDDAC.js"; import { useButton } from "../__chunks/J4DPQC5Y.js"; import "../__chunks/WJ7PHYH7.js"; import "../__chunks/US3TW2XI.js"; import "../__chunks/SWN3JYXT.js"; import "../__chunks/45YOMIF3.js"; import { createElement, createHook, forwardRef } from "../__chunks/ILRXHV7V.js"; import { useEvent } from "../__chunks/K2XTQB3X.js"; import "../__chunks/YXGXYGQX.js"; // src/form/form-push.tsx import { invariant } from "@ariakit/core/utils/misc"; import { useCallback, useEffect, useState } from "react"; var TagName = "button"; function getFirstFieldsByName(items, name) { if (!items) return []; const fields = []; for (const item of items) { if (item.type !== "field") continue; if (!item.name.startsWith(name)) continue; const nameWithIndex = item.name.replace(/(\.\d+)\..+$/, "$1"); const regex = new RegExp(`^${nameWithIndex}`); if (!fields.some((i) => regex.test(i.name))) { fields.push(item); } } return fields; } var useFormPush = createHook( function useFormPush2({ store, value, name: nameProp, getItem: getItemProp, autoFocusOnClick = true, ...props }) { const context = useFormContext(); store = store || context; invariant( store, process.env.NODE_ENV !== "production" && "FormPush must be wrapped in a Form component." ); const name = `${nameProp}`; const [shouldFocus, setShouldFocus] = useState(false); useEffect(() => { var _a; if (!shouldFocus) return; const items = getFirstFieldsByName(store == null ? void 0 : store.getState().items, name); const element = (_a = items == null ? void 0 : items[items.length - 1]) == null ? void 0 : _a.element; if (!element) return; element.focus(); setShouldFocus(false); }, [store, shouldFocus, name]); const getItem = useCallback( (item) => { const nextItem = { ...item, type: "button", name }; if (getItemProp) { return getItemProp(nextItem); } return nextItem; }, [name, getItemProp] ); const onClickProp = props.onClick; const onClick = useEvent((event) => { onClickProp == null ? void 0 : onClickProp(event); if (event.defaultPrevented) return; store == null ? void 0 : store.pushValue(name, value); if (!autoFocusOnClick) return; setShouldFocus(true); }); props = { ...props, onClick }; props = useButton(props); props = useCollectionItem({ store, ...props, getItem }); return props; } ); var FormPush = forwardRef(function FormPush2(props) { const htmlProps = useFormPush(props); return createElement(TagName, htmlProps); }); export { FormPush, useFormPush };