UNPKG

@ariakit/react-core

Version:

Ariakit React core

114 lines (112 loc) 3.19 kB
"use client"; import { useFormContext } from "../__chunks/GSXI3IAI.js"; import { useCollectionItem } from "../__chunks/Y62RTBST.js"; import { useButton } from "../__chunks/XCKGTAUF.js"; import "../__chunks/2W3RN7C5.js"; import "../__chunks/OE2EFRVA.js"; import "../__chunks/SWN3JYXT.js"; import "../__chunks/5CPL3B7G.js"; import { createElement, createHook, forwardRef } from "../__chunks/VOQWLFSQ.js"; import { useEvent } from "../__chunks/5GGHRIN3.js"; import "../__chunks/SK3NAZA3.js"; import { __objRest, __spreadProps, __spreadValues } from "../__chunks/3YLGPPWQ.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(_a) { var _b = _a, { store, value, name: nameProp, getItem: getItemProp, autoFocusOnClick = true } = _b, props = __objRest(_b, [ "store", "value", "name", "getItem", "autoFocusOnClick" ]); 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 _a2; if (!shouldFocus) return; const items = getFirstFieldsByName(store == null ? void 0 : store.getState().items, name); const element = (_a2 = items == null ? void 0 : items[items.length - 1]) == null ? void 0 : _a2.element; if (!element) return; element.focus(); setShouldFocus(false); }, [store, shouldFocus, name]); const getItem = useCallback( (item) => { const nextItem = __spreadProps(__spreadValues({}, 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 = __spreadProps(__spreadValues({}, props), { onClick }); props = useButton(props); props = useCollectionItem(__spreadProps(__spreadValues({ store }, props), { getItem })); return props; } ); var FormPush = forwardRef(function FormPush2(props) { const htmlProps = useFormPush(props); return createElement(TagName, htmlProps); }); export { FormPush, useFormPush };