drf-react-by-schema 0.27.18 → 0.28.1

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.
Files changed (78) hide show
  1. package/README.md +11 -0
  2. package/dist/@types/index.d.ts +3 -5
  3. package/dist/@types/index.d.ts.map +1 -1
  4. package/dist/api.d.ts +17 -15
  5. package/dist/api.d.ts.map +1 -1
  6. package/dist/api.js +3 -1
  7. package/dist/components/DataGridBySchemaEditable/BooleanInputCell.d.ts +3 -3
  8. package/dist/components/DataGridBySchemaEditable/BooleanInputCell.d.ts.map +1 -1
  9. package/dist/components/DataGridBySchemaEditable/BooleanInputCell.js +1 -1
  10. package/dist/components/DataGridBySchemaEditable/ConditionalEditWrapper.d.ts +2 -2
  11. package/dist/components/DataGridBySchemaEditable/ConditionalEditWrapper.d.ts.map +1 -1
  12. package/dist/components/DataGridBySchemaEditable/ConditionalEditWrapper.js +3 -3
  13. package/dist/components/DataGridBySchemaEditable/DataGridDesktop.d.ts.map +1 -1
  14. package/dist/components/DataGridBySchemaEditable/DataGridDesktop.js +13 -1
  15. package/dist/components/DataGridBySchemaEditable/FileInputCell.d.ts +3 -3
  16. package/dist/components/DataGridBySchemaEditable/FileInputCell.d.ts.map +1 -1
  17. package/dist/components/DataGridBySchemaEditable/FileInputCell.js +1 -1
  18. package/dist/components/DataGridBySchemaEditable/GeoEditCell.d.ts +10 -0
  19. package/dist/components/DataGridBySchemaEditable/GeoEditCell.d.ts.map +1 -0
  20. package/dist/components/DataGridBySchemaEditable/GeoEditCell.js +81 -0
  21. package/dist/components/DataGridBySchemaEditable/GeoThumbCell.d.ts +11 -0
  22. package/dist/components/DataGridBySchemaEditable/GeoThumbCell.d.ts.map +1 -0
  23. package/dist/components/DataGridBySchemaEditable/GeoThumbCell.js +84 -0
  24. package/dist/components/DataGridBySchemaEditable/GridDateInput.d.ts +2 -2
  25. package/dist/components/DataGridBySchemaEditable/GridDateInput.d.ts.map +1 -1
  26. package/dist/components/DataGridBySchemaEditable/GridDateInput.js +4 -5
  27. package/dist/components/DataGridBySchemaEditable/GridDateTimeInput.d.ts +2 -2
  28. package/dist/components/DataGridBySchemaEditable/GridDateTimeInput.d.ts.map +1 -1
  29. package/dist/components/DataGridBySchemaEditable/GridDateTimeInput.js +4 -5
  30. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.d.ts +2 -2
  31. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.d.ts.map +1 -1
  32. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.js +4 -5
  33. package/dist/components/DataGridBySchemaEditable/GridGenericInput.d.ts +1 -1
  34. package/dist/components/DataGridBySchemaEditable/GridGenericInput.d.ts.map +1 -1
  35. package/dist/components/DataGridBySchemaEditable/GridGenericInput.js +1 -1
  36. package/dist/components/DataGridBySchemaEditable/GridPatternInput.d.ts +2 -2
  37. package/dist/components/DataGridBySchemaEditable/GridPatternInput.d.ts.map +1 -1
  38. package/dist/components/DataGridBySchemaEditable/GridPatternInput.js +4 -5
  39. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.d.ts +1 -1
  40. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.d.ts.map +1 -1
  41. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.js +1 -1
  42. package/dist/components/DataGridBySchemaEditable/geoConstants.d.ts +5 -0
  43. package/dist/components/DataGridBySchemaEditable/geoConstants.d.ts.map +1 -0
  44. package/dist/components/DataGridBySchemaEditable/geoConstants.js +6 -0
  45. package/dist/components/DataGridBySchemaEditable/hooks/useProcessRowUpdate.d.ts +1 -1
  46. package/dist/components/DataGridBySchemaEditable/hooks/useProcessRowUpdate.d.ts.map +1 -1
  47. package/dist/components/DataGridBySchemaEditable/hooks/useProcessRowUpdate.js +14 -19
  48. package/dist/components/DataGridBySchemaEditable/utils/columnFactory.d.ts +1 -1
  49. package/dist/components/DataGridBySchemaEditable/utils/columnFactory.d.ts.map +1 -1
  50. package/dist/components/DataGridBySchemaEditable/utils/columnFactory.js +41 -26
  51. package/dist/components/DataGridBySchemaEditable/utils.d.ts +3 -2
  52. package/dist/components/DataGridBySchemaEditable/utils.d.ts.map +1 -1
  53. package/dist/components/forms/DialogFormBySchema.d.ts.map +1 -1
  54. package/dist/components/forms/DialogFormBySchema.js +27 -2
  55. package/dist/components/forms/FieldBySchema.d.ts.map +1 -1
  56. package/dist/components/forms/FieldBySchema.js +7 -0
  57. package/dist/components/forms/Form.d.ts.map +1 -1
  58. package/dist/components/forms/Form.js +69 -40
  59. package/dist/components/forms/inputs/EditableAutocompleteFieldBySchema.d.ts +4 -5
  60. package/dist/components/forms/inputs/EditableAutocompleteFieldBySchema.d.ts.map +1 -1
  61. package/dist/components/forms/inputs/EditableAutocompleteFieldBySchema.js +2 -2
  62. package/dist/components/forms/inputs/GeometryFieldBySchema.d.ts +8 -0
  63. package/dist/components/forms/inputs/GeometryFieldBySchema.d.ts.map +1 -0
  64. package/dist/components/forms/inputs/GeometryFieldBySchema.js +57 -0
  65. package/dist/components/forms/inputs/MapGeometryPicker.d.ts +18 -0
  66. package/dist/components/forms/inputs/MapGeometryPicker.d.ts.map +1 -0
  67. package/dist/components/forms/inputs/MapGeometryPicker.js +248 -0
  68. package/dist/context/APIWrapper.d.ts.map +1 -1
  69. package/dist/context/APIWrapper.js +10 -2
  70. package/dist/index.d.ts +7 -7
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +12 -11
  73. package/dist/styles/theme.d.ts +1 -1
  74. package/dist/styles/theme.d.ts.map +1 -1
  75. package/dist/utils/utils.d.ts +39 -5
  76. package/dist/utils/utils.d.ts.map +1 -1
  77. package/dist/utils/utils.js +114 -19
  78. package/package.json +36 -2
@@ -32,20 +32,31 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
35
44
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
45
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
46
  };
38
47
  Object.defineProperty(exports, "__esModule", { value: true });
39
48
  exports.default = DialogFormBySchema;
40
49
  const react_1 = __importStar(require("react"));
50
+ const axios_1 = __importDefault(require("axios"));
41
51
  const react_hook_form_1 = require("react-hook-form");
42
52
  const yup_1 = require("@hookform/resolvers/yup");
43
53
  const Box_1 = __importDefault(require("@mui/material/Box"));
44
54
  const Button_1 = __importDefault(require("@mui/material/Button"));
45
55
  const styles_1 = require("../../styles");
46
56
  const FormBySchema_1 = __importDefault(require("./FormBySchema"));
57
+ const utils_1 = require("../../utils");
47
58
  function DialogFormBySchema({ schema, validationSchema, initialValues, onEditModelSave, setDialog, getAutoComplete, fieldsLayout, hiddenFields, isCancelDisabled, forceSaveEnabled, optionsAC, }) {
48
- const { control, handleSubmit, reset, getValues, setValue, formState: { errors, isDirty }, } = (0, react_hook_form_1.useForm)({
59
+ const { control, handleSubmit, reset, getValues, setValue, setError, formState: { errors, isDirty }, } = (0, react_hook_form_1.useForm)({
49
60
  mode: 'onBlur',
50
61
  resolver: validationSchema ? (0, yup_1.yupResolver)(validationSchema) : undefined,
51
62
  });
@@ -53,10 +64,24 @@ function DialogFormBySchema({ schema, validationSchema, initialValues, onEditMod
53
64
  reset(initialValues);
54
65
  // eslint-disable-next-line react-hooks/exhaustive-deps
55
66
  }, []);
67
+ // Wrap the provided save handler so DRF field validation errors (e.g.
68
+ // raised in a serializer's `validate()`) are mapped onto the dialog fields,
69
+ // rendered exactly like yup errors.
70
+ const handleSubmitWrapper = (0, react_1.useCallback)((data) => __awaiter(this, void 0, void 0, function* () {
71
+ var _a;
72
+ const result = yield onEditModelSave(data);
73
+ if (axios_1.default.isAxiosError(result)) {
74
+ const fieldErrors = (0, utils_1.getFieldErrorsFromResponse)((_a = result.response) === null || _a === void 0 ? void 0 : _a.data, schema);
75
+ Object.entries(fieldErrors).forEach(([field, { type, message }]) => {
76
+ setError(field, { type, message });
77
+ });
78
+ }
79
+ return result;
80
+ }), [onEditModelSave, schema, setError]);
56
81
  if (!schema) {
57
82
  return react_1.default.createElement(react_1.default.Fragment, null, "Houve um erro ao carregar este formul\u00E1rio!");
58
83
  }
59
- return (react_1.default.createElement(react_1.default.Fragment, null, initialValues && control && (react_1.default.createElement("form", { onSubmit: handleSubmit(onEditModelSave) },
84
+ return (react_1.default.createElement(react_1.default.Fragment, null, initialValues && control && (react_1.default.createElement("form", { onSubmit: handleSubmit(handleSubmitWrapper) },
60
85
  react_1.default.createElement(Box_1.default, null,
61
86
  react_1.default.createElement(FormBySchema_1.default, { control: control, errors: errors, schema: schema, getValues: getValues, setValue: setValue, optionsAC: optionsAC, isolatedGetAutoComplete: getAutoComplete, fieldsLayout: fieldsLayout, hiddenFields: hiddenFields, relatedEditable: false })),
62
87
  react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.flexRow },
@@ -1 +1 @@
1
- {"version":3,"file":"FieldBySchema.d.ts","sourceRoot":"","sources":["../../../src/components/forms/FieldBySchema.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAc,kBAAkB,EAAQ,MAAM,cAAc,CAAC;AAYpE,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,EACpC,IAAI,EACJ,MAAM,EACN,OAAO,EACP,MAAM,EACN,SAAiB,EACjB,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,QAAiB,EACjB,KAAK,EACL,SAAS,EACT,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,EAAE,EACF,OAAO,EACP,YAAoB,EACpB,KAAK,EACL,aAAa,EACb,YAAgB,EAChB,SAAS,EACT,GAAG,KAAK,EACT,EAAE,kBAAkB,qBA0MpB"}
1
+ {"version":3,"file":"FieldBySchema.d.ts","sourceRoot":"","sources":["../../../src/components/forms/FieldBySchema.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAc,kBAAkB,EAAqB,MAAM,cAAc,CAAC;AAajF,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,EACpC,IAAI,EACJ,MAAM,EACN,OAAO,EACP,MAAM,EACN,SAAiB,EACjB,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,QAAiB,EACjB,KAAK,EACL,SAAS,EACT,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,EAAE,EACF,OAAO,EACP,YAAoB,EACpB,KAAK,EACL,aAAa,EACb,YAAgB,EAChB,SAAS,EACT,GAAG,KAAK,EACT,EAAE,kBAAkB,qBA8NpB"}
@@ -25,6 +25,7 @@ const FloatFieldBySchema_1 = __importDefault(require("./inputs/FloatFieldBySchem
25
25
  const TextFieldBySchema_1 = __importDefault(require("./inputs/TextFieldBySchema"));
26
26
  const FileFieldBySchema_1 = __importDefault(require("./inputs/FileFieldBySchema"));
27
27
  const PatternFieldBySchema_1 = __importDefault(require("./inputs/PatternFieldBySchema"));
28
+ const GeometryFieldBySchema_1 = __importDefault(require("./inputs/GeometryFieldBySchema"));
28
29
  function FieldBySchema(_a) {
29
30
  var _b, _c, _d;
30
31
  var { name, schema, control, errors, multiline = false, setValue, getValues, fieldKey, labelKey = 'nome', index, optionsAC, optionsModel, getOptionLabel, renderOption, onEditModel, fieldsLayout, sx, options, isSemaphoric = false, label, onValueChange, decimalScale = 2, autoFocus } = _a, other = __rest(_a, ["name", "schema", "control", "errors", "multiline", "setValue", "getValues", "fieldKey", "labelKey", "index", "optionsAC", "optionsModel", "getOptionLabel", "renderOption", "onEditModel", "fieldsLayout", "sx", "options", "isSemaphoric", "label", "onValueChange", "decimalScale", "autoFocus"]);
@@ -59,6 +60,12 @@ function FieldBySchema(_a) {
59
60
  case 'image':
60
61
  case 'image upload':
61
62
  return (react_1.default.createElement(FileFieldBySchema_1.default, Object.assign({ name: name, schema: schema, control: control, errors: errors, fieldKey: fieldKey, index: index, sx: sx, onValueChange: onValueChange, autoFocus: autoFocus }, other)));
63
+ case 'point':
64
+ case 'polygon':
65
+ case 'multipoint':
66
+ case 'multipolygon':
67
+ case 'geometrycollection':
68
+ return (react_1.default.createElement(GeometryFieldBySchema_1.default, Object.assign({ name: name, schema: schema, control: control, errors: errors, geometry: fieldSchema.type, fieldKey: fieldKey, index: index, sx: sx, onValueChange: onValueChange, autoFocus: autoFocus }, other)));
62
69
  case 'number':
63
70
  case 'integer':
64
71
  case 'password':
@@ -1 +1 @@
1
- {"version":3,"file":"Form.d.ts","sourceRoot":"","sources":["../../../src/components/forms/Form.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAkD,MAAM,OAAO,CAAC;AACvE,OAAc,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAW,eAAe,EAAsB,MAAM,iBAAiB,CAAC;AAG/E,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,uBAAuB,EACvB,WAAW,EACX,eAAe,EACf,eAAe,EAEf,EAAE,EACF,IAAI,EACJ,SAAS,EACT,eAAe,EACf,QAAQ,EACR,eAAe,EACf,SAAS,EACT,MAAM,EACN,WAAW,EACZ,MAAM,cAAc,CAAC;AAKtB,OAAoB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAM9D,UAAU,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,CAAE,SAAQ,IAAI,CACvD,gBAAgB,CAAC,CAAC,CAAC,EACnB,cAAc,GAAG,WAAW,CAC7B;IACC,KAAK,EAAE,MAAM,CAAC;IACd,K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EACjB,eAAe,EAEf,KAAK,EACL,aAAa,EACb,SAAS,EACT,cAAc,EAEd,WAAW,EACX,aAAa,EAEb,gBAAgB,GACjB,EAAE,SAAS,CAAC,CAAC,CAAC,GACb,IAAI,CACF,uBAAuB,EACrB,IAAI,GACJ,SAAS,GACT,SAAS,GACT,SAAS,GACT,aAAa,GACb,iBAAiB,GACjB,qBAAqB,CACxB,qBAsVF;AAED,eAAe,IAAI,CAAC"}
@@ -67,9 +67,12 @@ function Form({ model, objId, defaults, objTitleField, onSave, onDelete, onCance
67
67
  const customExitRef = (0, react_1.useRef)(customExit);
68
68
  const methods = (0, react_hook_form_1.useForm)({
69
69
  mode: 'onBlur',
70
- resolver: (pageForm === null || pageForm === void 0 ? void 0 : pageForm.validationSchema) ? (0, yup_1.yupResolver)(pageForm.validationSchema) : undefined,
70
+ // yupResolver infers against untyped base `Item`; reassert to generic `Item<T>`.
71
+ resolver: (pageForm === null || pageForm === void 0 ? void 0 : pageForm.validationSchema)
72
+ ? (0, yup_1.yupResolver)(pageForm.validationSchema)
73
+ : undefined,
71
74
  });
72
- const { control, handleSubmit, reset, getValues, setValue, formState: { errors, isDirty }, register, watch, } = methods;
75
+ const { control, handleSubmit, reset, getValues, setValue, setError, formState: { errors, isDirty }, register, watch, } = methods;
73
76
  const stableDefaults = (0, useDeepMemo_1.useDeepMemo)(defaults);
74
77
  const stableExtraValidators = (0, useDeepMemo_1.useDeepMemo)(extraValidators);
75
78
  const FinalFormActions = CustomFormActions || FormActions_1.default;
@@ -120,47 +123,71 @@ function Form({ model, objId, defaults, objTitleField, onSave, onDelete, onCance
120
123
  genericNavigate(-1);
121
124
  }, [exitPath, genericNavigate]);
122
125
  const localOnSubmit = (0, react_1.useCallback)((data, event) => __awaiter(this, void 0, void 0, function* () {
126
+ var _a, _b;
123
127
  const currentId = objId || (0, utils_1.getTmpId)();
124
128
  const response = yield onSubmit(model, currentId, data, event);
125
- if (!axios_1.default.isAxiosError(response)) {
126
- const newId = response;
127
- const buttonType = (event === null || event === void 0 ? void 0 : event.nativeEvent.submitter.name) || _types_1.FormSaveActions.EXIT_ON_SAVE;
128
- switch (buttonType) {
129
- case _types_1.FormSaveActions.SAVE_AND_CREATE_NEW:
130
- loadData(undefined);
131
- break;
132
- case _types_1.FormSaveActions.SAVE_AND_CONTINUE:
133
- reset(Object.assign(Object.assign({}, data), { id: newId }));
134
- break;
135
- case _types_1.FormSaveActions.EXIT_ON_SAVE:
136
- default:
137
- resetPageForm();
138
- break;
139
- }
140
- // In case the user wants to do something else after saving
141
- if (onSaveRef.current) {
142
- onSaveRef.current(currentId, newId, buttonType);
143
- }
144
- const goToEdit = (id = 'novo') => {
145
- const populatedEditPath = editPath
146
- ? (0, utils_2.buildEditPath)(editPath, id)
147
- : `${window.location.pathname.replace(/\/[^\/]+\/?$/, '/')}${id}`;
148
- genericNavigate(populatedEditPath);
149
- };
150
- switch (buttonType) {
151
- case _types_1.FormSaveActions.SAVE_AND_CREATE_NEW:
152
- goToEdit();
153
- break;
154
- case _types_1.FormSaveActions.SAVE_AND_CONTINUE:
155
- goToEdit(newId);
156
- break;
157
- case _types_1.FormSaveActions.EXIT_ON_SAVE:
158
- default:
159
- exit(newId);
160
- break;
129
+ if (axios_1.default.isAxiosError(response)) {
130
+ // Map DRF field validation errors (e.g. raised in a serializer's
131
+ // `validate()`) onto the corresponding form fields so they are shown
132
+ // underlined with the message right below them, just like yup errors.
133
+ const fieldErrors = (0, utils_1.getFieldErrorsFromResponse)((_a = response.response) === null || _a === void 0 ? void 0 : _a.data, (_b = pageForm === null || pageForm === void 0 ? void 0 : pageForm.schema) !== null && _b !== void 0 ? _b : undefined);
134
+ const entries = Object.entries(fieldErrors);
135
+ if (entries.length > 0) {
136
+ entries.forEach(([field, { type, message }]) => {
137
+ setError(field, { type, message });
138
+ });
161
139
  }
140
+ return;
141
+ }
142
+ const newId = response;
143
+ const buttonType = (event === null || event === void 0 ? void 0 : event.nativeEvent.submitter.name) || _types_1.FormSaveActions.EXIT_ON_SAVE;
144
+ switch (buttonType) {
145
+ case _types_1.FormSaveActions.SAVE_AND_CREATE_NEW:
146
+ loadData(undefined);
147
+ break;
148
+ case _types_1.FormSaveActions.SAVE_AND_CONTINUE:
149
+ reset(Object.assign(Object.assign({}, data), { id: newId }));
150
+ break;
151
+ case _types_1.FormSaveActions.EXIT_ON_SAVE:
152
+ default:
153
+ resetPageForm();
154
+ break;
155
+ }
156
+ // In case the user wants to do something else after saving
157
+ if (onSaveRef.current) {
158
+ onSaveRef.current(currentId, newId, buttonType);
159
+ }
160
+ const goToEdit = (id = 'novo') => {
161
+ const populatedEditPath = editPath
162
+ ? (0, utils_2.buildEditPath)(editPath, id)
163
+ : `${window.location.pathname.replace(/\/[^\/]+\/?$/, '/')}${id}`;
164
+ genericNavigate(populatedEditPath);
165
+ };
166
+ switch (buttonType) {
167
+ case _types_1.FormSaveActions.SAVE_AND_CREATE_NEW:
168
+ goToEdit();
169
+ break;
170
+ case _types_1.FormSaveActions.SAVE_AND_CONTINUE:
171
+ goToEdit(newId);
172
+ break;
173
+ case _types_1.FormSaveActions.EXIT_ON_SAVE:
174
+ default:
175
+ exit(newId);
176
+ break;
162
177
  }
163
- }), [loadData, model, objId, onSubmit, reset, resetPageForm, exit, editPath, genericNavigate]);
178
+ }), [
179
+ loadData,
180
+ model,
181
+ objId,
182
+ onSubmit,
183
+ pageForm,
184
+ reset,
185
+ resetPageForm,
186
+ exit,
187
+ editPath,
188
+ genericNavigate,
189
+ setError,
190
+ ]);
164
191
  const updateFormTools = (0, react_1.useCallback)(() => {
165
192
  const currentFormTools = formToolsRef.current;
166
193
  if (!currentFormTools ||
@@ -229,7 +256,9 @@ function Form({ model, objId, defaults, objTitleField, onSave, onDelete, onCance
229
256
  react_1.default.createElement("form", { onSubmit: handleSubmit(localOnSubmit) },
230
257
  react_1.default.createElement(FinalFormActions, { formDisabled: !isDirty, model: model, objId: objId, saveAndContinue: saveAndContinue, onCancel: onCancel, onDelete: onDelete, exit: exit, title: title, labelSave: labelSave, labelSaveAndContinue: labelSaveAndContinue, labelSaveAndCreateNew: labelSaveAndCreateNew, labelCancel: labelCancel, labelRemove: labelRemove }),
231
258
  react_1.default.createElement(FormBySchema_1.default, { fieldsLayout: fieldsLayout, hiddenFields: hiddenFields, control: control, register: register, errors: errors, schema: pageForm.schema, getValues: getValues, setValue: setValue, multiline: multiline, fieldKey: fieldKey, labelKey: labelKey, optionsAC: optionsAC, setOptionsAC: setOptionsAC, optionsModel: optionsModel, getOptionLabel: getOptionLabel, renderOption: renderOption, onEditModel: onEditModel, options: options, isSemaphoric: isSemaphoric, label: label, decimalScale: decimalScale, customFieldFormLayouts: customFieldFormLayouts, fieldsProps: fieldsProps, isolatedGetAutoComplete: isolatedGetAutoComplete, relatedEditable: relatedEditable, autoFocusField: autoFocusField, elevation: elevation, sxRow: sxRow, sxRowMultiple: sxRowMultiple, sxSection: sxSection, sxSectionTitle: sxSectionTitle, conditionalVisible: conditionalVisible, watchedValues: watchedValues }),
232
- watchValues && onWatchChange && (react_1.default.createElement(FormWatcher_1.default, { control: control, watch: watchValues, onChange: onWatchChange })),
259
+ watchValues && onWatchChange && (react_1.default.createElement(FormWatcher_1.default, {
260
+ // FormWatcher only uses useWatch; align control to Control<GenericValue>.
261
+ control: control, watch: watchValues, onChange: onWatchChange })),
233
262
  react_1.default.createElement(FinalFormActions, { bottom: true, formDisabled: !isDirty, model: model, objId: objId, saveAndContinue: saveAndContinue, onCancel: onCancel, onDelete: onDelete, exit: exit, title: title, labelSave: labelSave, labelSaveAndContinue: labelSaveAndContinue, labelSaveAndCreateNew: labelSaveAndCreateNew, labelCancel: labelCancel, labelRemove: labelRemove }))));
234
263
  }
235
264
  exports.default = Form;
@@ -1,15 +1,14 @@
1
1
  import React from 'react';
2
- import { Controller } from 'react-hook-form';
3
- import { Item } from '../../../@types';
2
+ import Autocomplete from '@mui/material/Autocomplete';
4
3
  declare const EditableAutocompleteFieldBySchema: React.ForwardRefExoticComponent<Omit<import("../../../@types").CommonFieldProps<void>, "value" | "onEditModel"> & {
5
4
  onEditModel?: <U extends import("../../../@types").TField = void>(x: import("../../../@types").OnEditModelType<U>) => void;
6
5
  name: string;
7
6
  schema: {
8
7
  [x: string]: import("../../../@types").Field;
9
8
  };
10
- control: Controller<Item<T>, import("../../../@types").GenericValue, Item<T>>;
11
- errors: Controller<Item<T>>;
9
+ control: import("react-hook-form").Control<Record<string, any>, any, Record<string, any>>;
10
+ errors: import("react-hook-form").FieldErrors<Record<string, any>>;
12
11
  autoFocus?: boolean;
13
- } & React.RefAttributes<any>>;
12
+ } & React.RefAttributes<typeof Autocomplete>>;
14
13
  export default EditableAutocompleteFieldBySchema;
15
14
  //# sourceMappingURL=EditableAutocompleteFieldBySchema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"EditableAutocompleteFieldBySchema.d.ts","sourceRoot":"","sources":["../../../../src/components/forms/inputs/EditableAutocompleteFieldBySchema.tsx"],"names":[],"mappings":"AAAA,OAAO,KAA8B,MAAM,OAAO,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAO7C,OAAO,EAAE,IAAI,EAAkC,MAAM,iBAAiB,CAAC;AAOvE,QAAA,MAAM,iCAAiC;;;;;;;;;6BA6WtC,CAAC;AAGF,eAAe,iCAAiC,CAAC"}
1
+ {"version":3,"file":"EditableAutocompleteFieldBySchema.d.ts","sourceRoot":"","sources":["../../../../src/components/forms/inputs/EditableAutocompleteFieldBySchema.tsx"],"names":[],"mappings":"AAAA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAGnD,OAAO,YAAqC,MAAM,4BAA4B,CAAC;AAY/E,QAAA,MAAM,iCAAiC;;;;;;;;;6CA6WtC,CAAC;AAGF,eAAe,iCAAiC,CAAC"}
@@ -170,7 +170,7 @@ const EditableAutocompleteFieldBySchema = react_1.default.forwardRef((_a, _) =>
170
170
  if (onValueChange) {
171
171
  onValueChange(e);
172
172
  }
173
- }, renderInput: (params) => (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { label: label, required: (0, utils_1.isFieldRequired)(fieldSchema), margin: "normal", error: error, autoFocus: autoFocus, helperText: helperText, InputProps: Object.assign(Object.assign({}, params.InputProps), { endAdornment: (react_1.default.createElement(react_1.default.Fragment, null,
173
+ }, renderInput: (params) => (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { label: label, required: (0, utils_1.isFieldRequired)(fieldSchema) && !multiple, margin: "normal", error: error, autoFocus: autoFocus, helperText: helperText, InputProps: Object.assign(Object.assign({}, params.InputProps), { endAdornment: (react_1.default.createElement(react_1.default.Fragment, null,
174
174
  !multiple && field.value && (react_1.default.createElement(IconButton_1.default, { size: "small", "aria-label": "Editar", onClick: () => {
175
175
  if ((0, utils_1.isTmpId)(field.value.id)) {
176
176
  setDialog({
@@ -266,7 +266,7 @@ const EditableAutocompleteFieldBySchema = react_1.default.forwardRef((_a, _) =>
266
266
  if (onValueChange) {
267
267
  onValueChange(e);
268
268
  }
269
- }, renderInput: (params) => (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { label: label, required: (0, utils_1.isFieldRequired)(fieldSchema), margin: "normal", error: error, autoFocus: autoFocus, helperText: helperText }, other))), getOptionKey: ({ id }) => id, getOptionLabel: getOptionLabel, renderOption: renderOption }))) }));
269
+ }, renderInput: (params) => (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { label: label, required: (0, utils_1.isFieldRequired)(fieldSchema) && !multiple, margin: "normal", error: error, autoFocus: autoFocus, helperText: helperText }, other))), getOptionKey: ({ id }) => id, getOptionLabel: getOptionLabel, renderOption: renderOption }))) }));
270
270
  });
271
271
  EditableAutocompleteFieldBySchema.displayName = 'EditableAutocompleteFieldBySchema';
272
272
  exports.default = EditableAutocompleteFieldBySchema;
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+ import { FieldBySchemaProps, GeometryFieldType, TField } from '../../../@types';
3
+ export interface GeometryFieldBySchemaProps<T extends TField = void> extends FieldBySchemaProps<T> {
4
+ geometry: GeometryFieldType;
5
+ height?: number;
6
+ }
7
+ export default function GeometryFieldBySchema({ name, schema, control, errors, geometry, fieldKey, index, sx, autoFocus, disabled, height, onValueChange, ...other }: GeometryFieldBySchemaProps): React.JSX.Element | undefined;
8
+ //# sourceMappingURL=GeometryFieldBySchema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GeometryFieldBySchema.d.ts","sourceRoot":"","sources":["../../../../src/components/forms/inputs/GeometryFieldBySchema.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAU1B,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGhF,MAAM,WAAW,0BAA0B,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,CAAE,SAAQ,kBAAkB,CAAC,CAAC,CAAC;IAChG,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,CAAC,OAAO,UAAU,qBAAqB,CAAC,EAC5C,IAAI,EACJ,MAAM,EACN,OAAO,EACP,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,KAAK,EACL,EAAc,EACd,SAAS,EACT,QAAQ,EACR,MAAM,EACN,aAAa,EACb,GAAG,KAAK,EACT,EAAE,0BAA0B,iCAqE5B"}
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.default = GeometryFieldBySchema;
18
+ const react_1 = __importDefault(require("react"));
19
+ const react_hook_form_1 = require("react-hook-form");
20
+ const TextField_1 = __importDefault(require("@mui/material/TextField"));
21
+ const utils_1 = require("../../../utils");
22
+ const MapGeometryPicker_1 = __importDefault(require("./MapGeometryPicker"));
23
+ function GeometryFieldBySchema(_a) {
24
+ var _b;
25
+ var { name, schema, control, errors, geometry, fieldKey, index, sx = { mr: 2 }, autoFocus, disabled, height, onValueChange } = _a, other = __rest(_a, ["name", "schema", "control", "errors", "geometry", "fieldKey", "index", "sx", "autoFocus", "disabled", "height", "onValueChange"]);
26
+ if (!(name in schema)) {
27
+ console.error(`GeometryFieldBySchema: could not find schema for ${name}! Not rendering`);
28
+ return;
29
+ }
30
+ const fieldSchema = schema[name];
31
+ if (fieldKey && index && index >= 0) {
32
+ name = `${fieldKey}.${index}.${name}`;
33
+ }
34
+ const { error, helperText } = fieldKey && index && index >= 0
35
+ ? (0, utils_1.errorProps)({ fieldKey, index, fieldKeyProp: name, errors })
36
+ : {
37
+ error: errors && Boolean(errors[name]),
38
+ helperText: errors && errors[name] ? (_b = errors[name]) === null || _b === void 0 ? void 0 : _b.message : fieldSchema.help_text || '',
39
+ };
40
+ const mapAvailable = Boolean((0, utils_1.getMapLibraries)());
41
+ const multiline = geometry !== 'point';
42
+ return (react_1.default.createElement(react_hook_form_1.Controller, { name: name, control: control, render: ({ field }) => {
43
+ const currentValue = (0, utils_1.geometryValueToString)(field.value);
44
+ if (mapAvailable) {
45
+ return (react_1.default.createElement(MapGeometryPicker_1.default, { geometry: geometry, value: currentValue, onChange: (geoJSON) => {
46
+ field.onChange(geoJSON);
47
+ if (onValueChange)
48
+ onValueChange(geoJSON);
49
+ }, label: fieldSchema.label, error: error, helperText: helperText, height: height }));
50
+ }
51
+ return (react_1.default.createElement(TextField_1.default, Object.assign({}, other, { id: name, value: currentValue, label: fieldSchema.label, required: (0, utils_1.isFieldRequired)(fieldSchema), disabled: fieldSchema.disabled === true || disabled, onChange: (e) => {
52
+ field.onChange(e.target.value);
53
+ if (onValueChange)
54
+ onValueChange(e);
55
+ }, margin: "normal", fullWidth: true, multiline: multiline, minRows: multiline ? 4 : 0, error: error, helperText: helperText, sx: sx, autoFocus: autoFocus })));
56
+ } }));
57
+ }
@@ -0,0 +1,18 @@
1
+ import React from 'react';
2
+ import { SxProps, Theme } from '@mui/material/styles';
3
+ import 'leaflet/dist/leaflet.css';
4
+ import 'leaflet-draw/dist/leaflet.draw.css';
5
+ import { GeometryFieldType } from '../../../@types';
6
+ interface MapGeometryPickerProps {
7
+ geometry: GeometryFieldType;
8
+ value: string;
9
+ label?: string;
10
+ onChange: (geoJSON: string | null) => void;
11
+ error?: boolean;
12
+ helperText?: string;
13
+ sx?: SxProps<Theme>;
14
+ height?: number;
15
+ }
16
+ export default function MapGeometryPicker({ geometry, value, label, onChange, error, helperText, sx, height, }: MapGeometryPickerProps): React.JSX.Element;
17
+ export {};
18
+ //# sourceMappingURL=MapGeometryPicker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MapGeometryPicker.d.ts","sourceRoot":"","sources":["../../../../src/components/forms/inputs/MapGeometryPicker.tsx"],"names":[],"mappings":"AAAA,OAAO,KAA4B,MAAM,OAAO,CAAC;AAIjD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,0BAA0B,CAAC;AAClC,OAAO,oCAAoC,CAAC;AAE5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGpD,UAAU,sBAAsB;IAC9B,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,CAAC;IAC3C,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,EAAE,CAAC,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AA4LD,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,EACxC,QAAQ,EACR,KAAK,EACL,KAAK,EACL,QAAQ,EACR,KAAK,EACL,UAAU,EACV,EAAE,EACF,MAAY,GACb,EAAE,sBAAsB,qBAwDxB"}
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.default = MapGeometryPicker;
40
+ const react_1 = __importStar(require("react"));
41
+ const Box_1 = __importDefault(require("@mui/material/Box"));
42
+ const TextField_1 = __importDefault(require("@mui/material/TextField"));
43
+ const FormHelperText_1 = __importDefault(require("@mui/material/FormHelperText"));
44
+ const react_leaflet_1 = require("react-leaflet");
45
+ const leaflet_1 = __importDefault(require("leaflet"));
46
+ require("leaflet/dist/leaflet.css");
47
+ require("leaflet-draw/dist/leaflet.draw.css");
48
+ const utils_1 = require("../../../utils");
49
+ // Build the drf-react-by-schema geometry out of leaflet-draw features. Leaflet
50
+ // already parses/produces GeoJSON (L.geoJSON, FeatureGroup.toGeoJSON), so here
51
+ // we only reshape the resulting features into the right geometry type.
52
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
+ function buildOutput(geometry, features) {
54
+ const geoms = features.map((f) => f === null || f === void 0 ? void 0 : f.geometry).filter((g) => g);
55
+ if (geometry === 'point') {
56
+ const point = geoms.find((g) => g.type === 'Point');
57
+ return point ? { type: 'Point', coordinates: point.coordinates } : null;
58
+ }
59
+ if (geometry === 'polygon') {
60
+ const polygon = geoms.find((g) => g.type === 'Polygon');
61
+ return polygon ? { type: 'Polygon', coordinates: polygon.coordinates } : null;
62
+ }
63
+ if (geometry === 'multipoint') {
64
+ const coords = geoms.filter((g) => g.type === 'Point').map((g) => g.coordinates);
65
+ return coords.length ? { type: 'MultiPoint', coordinates: coords } : null;
66
+ }
67
+ if (geometry === 'multipolygon') {
68
+ const coords = geoms.filter((g) => g.type === 'Polygon').map((g) => g.coordinates);
69
+ return coords.length ? { type: 'MultiPolygon', coordinates: coords } : null;
70
+ }
71
+ // geometrycollection: points and polygons drawn together
72
+ const list = geoms.filter((g) => g.type === 'Point' || g.type === 'Polygon');
73
+ return list.length ? { type: 'GeometryCollection', geometries: list } : null;
74
+ }
75
+ // Counts the markers/polygons currently drawn so single-instance fields can
76
+ // hide their "add" tool once one shape already exists.
77
+ function layerCounts(featureGroup) {
78
+ let markers = 0;
79
+ let polygons = 0;
80
+ featureGroup.eachLayer((layer) => {
81
+ if (layer instanceof leaflet_1.default.Marker)
82
+ markers += 1;
83
+ else if (layer instanceof leaflet_1.default.Polygon)
84
+ polygons += 1;
85
+ });
86
+ return { markers, polygons };
87
+ }
88
+ // Which draw tools each geometry allows.
89
+ const markerEnabledFor = (g) => g === 'point' || g === 'multipoint' || g === 'geometrycollection';
90
+ const polygonEnabledFor = (g) => g === 'polygon' || g === 'multipolygon' || g === 'geometrycollection';
91
+ // Attaches leaflet-draw to the react-leaflet map and emits GeoJSON on changes.
92
+ // Per-geometry behavior:
93
+ // point / polygon -> single instance (add hidden once one exists; move/remove)
94
+ // multipoint -> many draggable/removable points
95
+ // multipolygon -> many editable/removable polygons
96
+ // geometrycollection -> many points AND many polygons
97
+ function DrawEditor({ geometry, value, onChange, }) {
98
+ const map = (0, react_leaflet_1.useMap)();
99
+ const featureGroupRef = (0, react_1.useRef)(null);
100
+ const drawControlRef = (0, react_1.useRef)(null);
101
+ const lastEmittedRef = (0, react_1.useRef)('__init__');
102
+ const onChangeRef = (0, react_1.useRef)(onChange);
103
+ onChangeRef.current = onChange;
104
+ const geometryRef = (0, react_1.useRef)(geometry);
105
+ geometryRef.current = geometry;
106
+ // Hides the add tool for single-instance fields once a shape exists; existing
107
+ // shapes stay draggable (points) / editable (polygons) and removable.
108
+ const updateCap = () => {
109
+ const featureGroup = featureGroupRef.current;
110
+ const drawControl = drawControlRef.current;
111
+ if (!featureGroup || !drawControl)
112
+ return;
113
+ const g = geometryRef.current;
114
+ const { markers, polygons } = layerCounts(featureGroup);
115
+ const single = isSingle(g);
116
+ const capMarker = single && g === 'point' && markers > 0;
117
+ const capPolygon = single && g === 'polygon' && polygons > 0;
118
+ drawControl.setDrawingOptions({
119
+ marker: markerEnabledFor(g) && !capMarker ? {} : false,
120
+ polygon: polygonEnabledFor(g) && !capPolygon ? {} : false,
121
+ polyline: false,
122
+ rectangle: false,
123
+ circle: false,
124
+ circlemarker: false,
125
+ });
126
+ };
127
+ const emit = () => {
128
+ var _a;
129
+ const featureGroup = featureGroupRef.current;
130
+ if (!featureGroup)
131
+ return;
132
+ const g = geometryRef.current;
133
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
134
+ const output = buildOutput(g, ((_a = featureGroup.toGeoJSON()) === null || _a === void 0 ? void 0 : _a.features) || []);
135
+ const text = output ? JSON.stringify(output) : '';
136
+ lastEmittedRef.current = text;
137
+ onChangeRef.current(text || null);
138
+ updateCap();
139
+ };
140
+ // Markers are draggable so an existing point can be moved; drag-end updates value.
141
+ const applyBehaviors = (layer) => {
142
+ if (layer instanceof leaflet_1.default.Marker) {
143
+ layer.options.draggable = true;
144
+ layer.on('dragend', emit);
145
+ }
146
+ };
147
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
148
+ const addGeoJSON = (data) => {
149
+ const featureGroup = featureGroupRef.current;
150
+ if (!featureGroup || !data)
151
+ return;
152
+ leaflet_1.default.geoJSON(data).eachLayer((layer) => {
153
+ featureGroup.addLayer(layer);
154
+ applyBehaviors(layer);
155
+ });
156
+ const bounds = featureGroup.getBounds();
157
+ if (bounds.isValid())
158
+ map.fitBounds(bounds, { padding: [40, 40] });
159
+ };
160
+ (0, react_1.useEffect)(() => {
161
+ const featureGroup = new leaflet_1.default.FeatureGroup().addTo(map);
162
+ featureGroupRef.current = featureGroup;
163
+ const g = geometryRef.current;
164
+ const drawControl = new leaflet_1.default.Control.Draw({
165
+ draw: {
166
+ marker: markerEnabledFor(g) ? {} : false,
167
+ polygon: polygonEnabledFor(g) ? {} : false,
168
+ polyline: false,
169
+ rectangle: false,
170
+ circle: false,
171
+ circlemarker: false,
172
+ },
173
+ edit: { featureGroup },
174
+ });
175
+ drawControlRef.current = drawControl;
176
+ map.addControl(drawControl);
177
+ map.on(leaflet_1.default.Draw.Event.CREATED,
178
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
179
+ (e) => {
180
+ featureGroup.addLayer(e.layer);
181
+ applyBehaviors(e.layer);
182
+ emit();
183
+ });
184
+ map.on(leaflet_1.default.Draw.Event.EDITED, emit);
185
+ map.on(leaflet_1.default.Draw.Event.DELETED, emit);
186
+ const initial = (0, utils_1.parseGeoJSON)(geometry, value);
187
+ if (initial)
188
+ addGeoJSON(initial);
189
+ updateCap();
190
+ return () => {
191
+ map.removeControl(drawControl);
192
+ map.removeLayer(featureGroup);
193
+ featureGroupRef.current = null;
194
+ drawControlRef.current = null;
195
+ };
196
+ // eslint-disable-next-line react-hooks/exhaustive-deps
197
+ }, []);
198
+ // Sync externally-driven value (reset after save/edit elsewhere). Avoids the
199
+ // feedback loop when this component itself emitted the change. Malformed text
200
+ // keeps the last valid geometry on the map (an error is shown in the field);
201
+ // only a legitimate empty value clears the features.
202
+ (0, react_1.useEffect)(() => {
203
+ const normalized = value || '';
204
+ if (normalized === lastEmittedRef.current)
205
+ return;
206
+ lastEmittedRef.current = normalized;
207
+ const featureGroup = featureGroupRef.current;
208
+ if (!featureGroup)
209
+ return;
210
+ const geo = (0, utils_1.parseGeoJSON)(geometry, value);
211
+ if (geo) {
212
+ featureGroup.clearLayers();
213
+ addGeoJSON(geo);
214
+ }
215
+ else if (normalized.trim() === '') {
216
+ featureGroup.clearLayers();
217
+ updateCap();
218
+ }
219
+ // malformed non-empty text: keep current features, error is shown in the field
220
+ // eslint-disable-next-line react-hooks/exhaustive-deps
221
+ }, [value, geometry, map]);
222
+ return null;
223
+ }
224
+ function MapGeometryPicker({ geometry, value, label, onChange, error, helperText, sx, height = 340, }) {
225
+ const valueText = value || '';
226
+ // Malformed detection: non-empty text that isn't GeoJSON (or of the wrong
227
+ // geometry type). Invalid input is flagged as an error instead of silently
228
+ // wiping the features from the map.
229
+ const malformed = valueText.trim() !== '' && !(0, utils_1.parseGeoJSON)(geometry, valueText);
230
+ return (react_1.default.createElement(Box_1.default, { sx: Object.assign({ mt: 1, mb: 1, width: '100%' }, sx) },
231
+ react_1.default.createElement(Box_1.default, { "data-testid": `map-${geometry}`, sx: {
232
+ height,
233
+ width: '100%',
234
+ overflow: 'hidden',
235
+ borderRadius: 1,
236
+ border: (t) => `1px solid ${error ? t.palette.error.main : t.palette.divider}`,
237
+ zIndex: 1 /* keep leaflet controls above MUI overlays */,
238
+ } },
239
+ react_1.default.createElement(react_leaflet_1.MapContainer, { center: [-14.235, -51.9253], zoom: 4, style: { height: '100%', width: '100%' }, zoomControl: true },
240
+ react_1.default.createElement(react_leaflet_1.TileLayer, { attribution: "\u00A9 OpenStreetMap contributors", url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" }),
241
+ react_1.default.createElement(DrawEditor, { geometry: geometry, value: value, onChange: onChange }))),
242
+ react_1.default.createElement(TextField_1.default, { value: value, onChange: (e) => onChange(e.target.value || null), variant: "outlined", margin: "dense", fullWidth: true, size: "small", label: geometry === 'point' ? 'Coordenadas (GeoJSON)' : 'GeoJSON (cole aqui)', multiline: geometry !== 'point', minRows: geometry !== 'point' ? 3 : 1, sx: { mt: 1 }, error: malformed, helperText: malformed
243
+ ? 'Dados malformados, corrija o GeoJSON para refletir no mapa.'
244
+ : 'O GeoJSON abaixo é sincronizado com o mapa.' }),
245
+ label && react_1.default.createElement(FormHelperText_1.default, { sx: { mt: 0.5 } }, label),
246
+ (helperText || error) && (react_1.default.createElement(FormHelperText_1.default, { error: error, sx: { mt: 0.5 } }, helperText))));
247
+ }
248
+ const isSingle = (g) => g === 'point' || g === 'polygon';