useForm.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var __rest = this && this.__rest || function (s, e) {
  2. var t = {};
  3. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  4. if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  5. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  6. }
  7. return t;
  8. };
  9. import * as React from 'react';
  10. import { useForm as useRcForm } from 'rc-field-form';
  11. import { getDOM } from "rc-util/es/Dom/findDOMNode";
  12. import scrollIntoView from 'scroll-into-view-if-needed';
  13. import { getFieldId, toArray } from '../util';
  14. export function toNamePathStr(name) {
  15. const namePath = toArray(name);
  16. return namePath.join('_');
  17. }
  18. function getFieldDOMNode(name, wrapForm) {
  19. const field = wrapForm.getFieldInstance(name);
  20. const fieldDom = getDOM(field);
  21. if (fieldDom) {
  22. return fieldDom;
  23. }
  24. const fieldId = getFieldId(toArray(name), wrapForm.__INTERNAL__.name);
  25. if (fieldId) {
  26. return document.getElementById(fieldId);
  27. }
  28. }
  29. export default function useForm(form) {
  30. const [rcForm] = useRcForm();
  31. const itemsRef = React.useRef({});
  32. const wrapForm = React.useMemo(() => form !== null && form !== void 0 ? form : Object.assign(Object.assign({}, rcForm), {
  33. __INTERNAL__: {
  34. itemRef: name => node => {
  35. const namePathStr = toNamePathStr(name);
  36. if (node) {
  37. itemsRef.current[namePathStr] = node;
  38. } else {
  39. delete itemsRef.current[namePathStr];
  40. }
  41. }
  42. },
  43. scrollToField: (name, options = {}) => {
  44. const {
  45. focus
  46. } = options,
  47. restOpt = __rest(options, ["focus"]);
  48. const node = getFieldDOMNode(name, wrapForm);
  49. if (node) {
  50. scrollIntoView(node, Object.assign({
  51. scrollMode: 'if-needed',
  52. block: 'nearest'
  53. }, restOpt));
  54. // Focus if scroll success
  55. if (focus) {
  56. wrapForm.focusField(name);
  57. }
  58. }
  59. },
  60. focusField: name => {
  61. var _a, _b;
  62. const itemRef = wrapForm.getFieldInstance(name);
  63. if (typeof (itemRef === null || itemRef === void 0 ? void 0 : itemRef.focus) === 'function') {
  64. itemRef.focus();
  65. } else {
  66. (_b = (_a = getFieldDOMNode(name, wrapForm)) === null || _a === void 0 ? void 0 : _a.focus) === null || _b === void 0 ? void 0 : _b.call(_a);
  67. }
  68. },
  69. getFieldInstance: name => {
  70. const namePathStr = toNamePathStr(name);
  71. return itemsRef.current[namePathStr];
  72. }
  73. }), [form, rcForm]);
  74. return [wrapForm];
  75. }