@vulcanjs/react-ui 0.6.6-y.11 → 0.6.6-y.14

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -588,7 +588,9 @@ var FormContext = /* @__PURE__ */ React.createContext(void 0);
588
588
  var useFormContext = /* @__PURE__ */ __name(() => {
589
589
  const formContext = useContext(FormContext);
590
590
  if (!formContext)
591
- throw new Error("A component is trying to access form context but it is undefined. Please wrap your component with a <Form>.");
591
+ throw new Error(`A component is trying to access form context but it is undefined. Please wrap your component with a <Form>.
592
+ You may be importing "FormContext" from different packages or have accidentaly made a copy of it?
593
+ FormContext is exposed by "@vulcanjs/react-ui".`);
592
594
  return formContext;
593
595
  }, "useFormContext");
594
596
 
@@ -597,12 +599,12 @@ init_esm_shims();
597
599
 
598
600
  // components/form/core/Form/Form.tsx
599
601
  init_esm_shims();
600
- import React12, { useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
602
+ import React5, { useEffect as useEffect2, useRef as useRef2, useState } from "react";
601
603
  import { runCallbacks, getErrors } from "@vulcanjs/core";
602
604
  import { useIntlContext as useIntlContext2 } from "@vulcanjs/react-i18n";
603
605
  import { removeProperty } from "@vulcanjs/utils";
604
606
  import cloneDeep from "lodash/cloneDeep.js";
605
- import compact3 from "lodash/compact.js";
607
+ import compact2 from "lodash/compact.js";
606
608
  import get2 from "lodash/get.js";
607
609
  import isObject from "lodash/isObject.js";
608
610
  import mapValues from "lodash/mapValues.js";
@@ -1152,12 +1154,10 @@ var useWarnOnUnsaved = /* @__PURE__ */ __name(({ isChanged, warnUnsavedChanges }
1152
1154
  });
1153
1155
  }, "useWarnOnUnsaved");
1154
1156
 
1155
- // components/VulcanComponents/index.ts
1156
- init_esm_shims();
1157
-
1158
- // components/VulcanComponents/Provider.tsx
1157
+ // components/VulcanComponents/Consumer.tsx
1159
1158
  init_esm_shims();
1160
- import React5 from "react";
1159
+ import { deprecate } from "@vulcanjs/utils";
1160
+ import React4, { useContext as useContext2 } from "react";
1161
1161
 
1162
1162
  // components/VulcanComponents/Context.ts
1163
1163
  init_esm_shims();
@@ -1184,9 +1184,6 @@ var VulcanComponentsContext = React3.createContext(new Proxy({
1184
1184
  VulcanComponentsContext.displayName = "VulcanComponentsContext";
1185
1185
 
1186
1186
  // components/VulcanComponents/Consumer.tsx
1187
- init_esm_shims();
1188
- import { deprecate } from "@vulcanjs/utils";
1189
- import React4, { useContext as useContext2 } from "react";
1190
1187
  function _extends() {
1191
1188
  _extends = Object.assign || function(target) {
1192
1189
  for (var i = 1; i < arguments.length; i++) {
@@ -1215,8 +1212,7 @@ var withVulcanComponents = /* @__PURE__ */ __name((C) => (props) => {
1215
1212
  }, props));
1216
1213
  }, "withVulcanComponents");
1217
1214
 
1218
- // components/VulcanComponents/Provider.tsx
1219
- import { debugVulcan } from "@vulcanjs/utils";
1215
+ // components/form/core/Form/Form.tsx
1220
1216
  function _extends2() {
1221
1217
  _extends2 = Object.assign || function(target) {
1222
1218
  for (var i = 1; i < arguments.length; i++) {
@@ -1232,180 +1228,549 @@ function _extends2() {
1232
1228
  return _extends2.apply(this, arguments);
1233
1229
  }
1234
1230
  __name(_extends2, "_extends");
1235
- var debugComponents = debugVulcan("components");
1236
- var VulcanComponentsProvider = /* @__PURE__ */ __name((_a) => {
1237
- var _b = _a, { value } = _b, props = __objRest(_b, ["value"]);
1238
- const currentComponents = useVulcanComponents();
1239
- debugComponents("Current components __not_initialized?", currentComponents.__not_initialized);
1240
- const mergedComponents = __spreadValues(__spreadValues({}, (currentComponents == null ? void 0 : currentComponents.__not_initialized) ? {} : currentComponents || {}), value || {});
1241
- debugComponents("Merged components", mergedComponents);
1242
- Object.keys(mergedComponents).forEach((componentName) => {
1243
- if (mergedComponents[componentName]) {
1244
- mergedComponents[componentName].displayName = "Vulcan." + componentName;
1245
- } else {
1246
- console.warn(`Encountered an undefined component: ${componentName}.
1247
- The component may not be registered, or import failed.
1248
- For instance due to an infinite import loop when importing
1249
- "useVulcanComponents" from index instead of Consumer.`);
1231
+ var compactParent = /* @__PURE__ */ __name((object, path) => {
1232
+ const parentPath = getParentPath(path);
1233
+ const compactIfArray = /* @__PURE__ */ __name((x) => Array.isArray(x) ? compact2(x) : x, "compactIfArray");
1234
+ update(object, parentPath, compactIfArray);
1235
+ }, "compactParent");
1236
+ var getDefaultValues = /* @__PURE__ */ __name((convertedSchema) => {
1237
+ return pickBy(mapValues(convertedSchema, (field) => field.defaultValue), (value) => value);
1238
+ }, "getDefaultValues");
1239
+ var compactObject = /* @__PURE__ */ __name((o) => omitBy(o, (f) => f === null || f === void 0), "compactObject");
1240
+ var getInitialStateFromProps = /* @__PURE__ */ __name((nextProps) => {
1241
+ const schema = nextProps.schema || nextProps.model.schema;
1242
+ const convertedSchema = convertSchema(schema);
1243
+ const formType = nextProps.document ? "edit" : "new";
1244
+ const defaultValues = formType === "new" ? getDefaultValues(convertedSchema) : {};
1245
+ const initialDocument = merge2({}, defaultValues, nextProps.prefilledProps, compactObject(nextProps.document));
1246
+ Object.keys(convertedSchema).forEach((key) => {
1247
+ let minCount = convertedSchema[key].minCount;
1248
+ if (minCount) {
1249
+ initialDocument[key] = initialDocument[key] || [];
1250
+ while (initialDocument[key].length < minCount)
1251
+ initialDocument[key].push({});
1250
1252
  }
1251
1253
  });
1252
- return /* @__PURE__ */ React5.createElement(VulcanComponentsContext.Provider, _extends2({
1253
- value: mergedComponents
1254
- }, props));
1255
- }, "VulcanComponentsProvider");
1256
-
1257
- // components/VulcanComponents/typings.ts
1258
- init_esm_shims();
1259
- import React6 from "react";
1260
-
1261
- // components/VulcanComponents/defaultVulcanComponents/index.ts
1262
- init_esm_shims();
1263
-
1264
- // components/core/LoadingButton.tsx
1265
- init_esm_shims();
1266
- import React7 from "react";
1267
- function _extends3() {
1268
- _extends3 = Object.assign || function(target) {
1269
- for (var i = 1; i < arguments.length; i++) {
1270
- var source = arguments[i];
1271
- for (var key in source) {
1272
- if (Object.prototype.hasOwnProperty.call(source, key)) {
1273
- target[key] = source[key];
1274
- }
1275
- }
1276
- }
1277
- return target;
1254
+ removeProperty(initialDocument, "__typename");
1255
+ return {
1256
+ disabled: nextProps.disabled,
1257
+ errors: [],
1258
+ deletedValues: [],
1259
+ currentValues: {},
1260
+ originalSchema: convertSchema(schema, {
1261
+ removeArrays: false
1262
+ }),
1263
+ schema: convertedSchema,
1264
+ flatSchema: convertSchema(schema, {
1265
+ flatten: true
1266
+ }),
1267
+ initialDocument,
1268
+ currentDocument: initialDocument
1278
1269
  };
1279
- return _extends3.apply(this, arguments);
1280
- }
1281
- __name(_extends3, "_extends");
1282
- var LoadingButton = /* @__PURE__ */ __name((_a) => {
1283
- var _b = _a, { loading, label, onClick, children, className = "" } = _b, rest = __objRest(_b, ["loading", "label", "onClick", "children", "className"]);
1284
- const Components2 = useVulcanComponents();
1285
- const wrapperStyle = {
1286
- position: "relative"
1270
+ }, "getInitialStateFromProps");
1271
+ var getChildrenProps = /* @__PURE__ */ __name((props, state, options, callbacks) => {
1272
+ const { currentUser, repeatErrors, submitLabel, cancelLabel, revertLabel, cancelCallback, revertCallback, id, model, prefilledProps, itemProperties, contextName, showRemove, showDelete } = props;
1273
+ const { disabled, currentDocument } = state;
1274
+ const { formType } = options;
1275
+ const { deleteDocument } = callbacks;
1276
+ const commonProps = {
1277
+ document: currentDocument,
1278
+ formType,
1279
+ currentUser,
1280
+ disabled,
1281
+ prefilledProps,
1282
+ itemProperties,
1283
+ contextName
1287
1284
  };
1288
- const labelStyle = loading ? {
1289
- opacity: 0.5
1290
- } : {};
1291
- const loadingStyle = loading ? {
1292
- position: "absolute",
1293
- top: 0,
1294
- bottom: 0,
1295
- left: 0,
1296
- right: 0,
1297
- display: "flex",
1298
- justifyContent: "center",
1299
- alignItems: "center"
1300
- } : {
1301
- display: "none"
1285
+ const docClassName = `document-${formType}`;
1286
+ const modelName = model.name.toLowerCase();
1287
+ const formProps = {
1288
+ className: `${docClassName} ${docClassName}-${modelName}`,
1289
+ id
1290
+ };
1291
+ const formGroupProps = /* @__PURE__ */ __name((group) => __spreadValues(__spreadProps(__spreadValues({
1292
+ key: group.name
1293
+ }, group), {
1294
+ group: omit(group, [
1295
+ "fields"
1296
+ ])
1297
+ }), commonProps), "formGroupProps");
1298
+ const formSubmitProps = {
1299
+ model,
1300
+ currentUser,
1301
+ submitLabel,
1302
+ cancelLabel,
1303
+ revertLabel,
1304
+ cancelCallback,
1305
+ revertCallback,
1306
+ document: currentDocument,
1307
+ deleteDocument: formType === "edit" && showRemove && showDelete && deleteDocument || null
1308
+ };
1309
+ const formLayoutProps = {
1310
+ formProps,
1311
+ repeatErrors,
1312
+ submitProps: formSubmitProps,
1313
+ commonProps
1302
1314
  };
1303
- return /* @__PURE__ */ React7.createElement(Components2.Button, _extends3({
1304
- className: `loading-button ${loading ? "loading-button-loading" : "loading-button-notloading"} ${className}`,
1305
- onClick
1306
- }, rest), /* @__PURE__ */ React7.createElement("span", {
1307
- style: wrapperStyle
1308
- }, /* @__PURE__ */ React7.createElement("span", {
1309
- style: labelStyle
1310
- }, label || children), /* @__PURE__ */ React7.createElement("span", {
1311
- style: loadingStyle
1312
- }, /* @__PURE__ */ React7.createElement(Components2.Loading, null))));
1313
- }, "LoadingButton");
1314
-
1315
- // components/core/MutationButton.tsx
1316
- init_esm_shims();
1317
- import React8, { useState } from "react";
1318
- import { useMutation } from "@apollo/client";
1319
-
1320
- // ../../node_modules/graphql-tag/lib/index.js
1321
- init_esm_shims();
1322
-
1323
- // ../../node_modules/tslib/modules/index.js
1324
- init_esm_shims();
1325
- var import_tslib = __toESM(require_tslib(), 1);
1326
- var { __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __createBinding, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet, __classPrivateFieldIn } = import_tslib.default;
1327
-
1328
- // ../../node_modules/graphql/index.mjs
1329
- init_esm_shims();
1330
-
1331
- // ../../node_modules/graphql/language/parser.mjs
1332
- init_esm_shims();
1333
-
1334
- // ../../node_modules/graphql/error/syntaxError.mjs
1335
- init_esm_shims();
1336
-
1337
- // ../../node_modules/graphql/error/GraphQLError.mjs
1338
- init_esm_shims();
1339
-
1340
- // ../../node_modules/graphql/jsutils/isObjectLike.mjs
1341
- init_esm_shims();
1342
- function _typeof(obj) {
1343
- "@babel/helpers - typeof";
1344
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
1345
- _typeof = /* @__PURE__ */ __name(function _typeof5(obj2) {
1346
- return typeof obj2;
1347
- }, "_typeof");
1348
- } else {
1349
- _typeof = /* @__PURE__ */ __name(function _typeof5(obj2) {
1350
- return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
1351
- }, "_typeof");
1352
- }
1353
- return _typeof(obj);
1354
- }
1355
- __name(_typeof, "_typeof");
1356
- function isObjectLike(value) {
1357
- return _typeof(value) == "object" && value !== null;
1358
- }
1359
- __name(isObjectLike, "isObjectLike");
1360
-
1361
- // ../../node_modules/graphql/polyfills/symbols.mjs
1362
- init_esm_shims();
1363
- var SYMBOL_ITERATOR = typeof Symbol === "function" && Symbol.iterator != null ? Symbol.iterator : "@@iterator";
1364
- var SYMBOL_ASYNC_ITERATOR = typeof Symbol === "function" && Symbol.asyncIterator != null ? Symbol.asyncIterator : "@@asyncIterator";
1365
- var SYMBOL_TO_STRING_TAG = typeof Symbol === "function" && Symbol.toStringTag != null ? Symbol.toStringTag : "@@toStringTag";
1366
-
1367
- // ../../node_modules/graphql/language/location.mjs
1368
- init_esm_shims();
1369
- function getLocation(source, position) {
1370
- var lineRegexp = /\r\n|[\n\r]/g;
1371
- var line = 1;
1372
- var column = position + 1;
1373
- var match;
1374
- while ((match = lineRegexp.exec(source.body)) && match.index < position) {
1375
- line += 1;
1376
- column = position + 1 - (match.index + match[0].length);
1377
- }
1378
1315
  return {
1379
- line,
1380
- column
1316
+ commonProps,
1317
+ formSubmitProps,
1318
+ formGroupProps,
1319
+ formLayoutProps
1381
1320
  };
1382
- }
1383
- __name(getLocation, "getLocation");
1384
-
1385
- // ../../node_modules/graphql/language/printLocation.mjs
1386
- init_esm_shims();
1387
- function printLocation(location) {
1388
- return printSourceLocation(location.source, getLocation(location.source, location.start));
1389
- }
1390
- __name(printLocation, "printLocation");
1391
- function printSourceLocation(source, sourceLocation) {
1392
- var firstLineColumnOffset = source.locationOffset.column - 1;
1393
- var body = whitespace(firstLineColumnOffset) + source.body;
1394
- var lineIndex = sourceLocation.line - 1;
1395
- var lineOffset = source.locationOffset.line - 1;
1396
- var lineNum = sourceLocation.line + lineOffset;
1397
- var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
1398
- var columnNum = sourceLocation.column + columnOffset;
1399
- var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");
1400
- var lines = body.split(/\r\n|[\n\r]/g);
1401
- var locationLine = lines[lineIndex];
1402
- if (locationLine.length > 120) {
1403
- var subLineIndex = Math.floor(columnNum / 80);
1404
- var subLineColumnNum = columnNum % 80;
1405
- var subLines = [];
1406
- for (var i = 0; i < locationLine.length; i += 80) {
1407
- subLines.push(locationLine.slice(i, i + 80));
1408
- }
1321
+ }, "getChildrenProps");
1322
+ var FormWarnUnsaved = /* @__PURE__ */ __name(({ isChanged, warnUnsavedChanges, children }) => {
1323
+ useWarnOnUnsaved({
1324
+ isChanged,
1325
+ warnUnsavedChanges
1326
+ });
1327
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, children);
1328
+ }, "FormWarnUnsaved");
1329
+ var getData = /* @__PURE__ */ __name((customArgs, props, state, { submitFormCallbacks, form }) => {
1330
+ const { currentDocument } = state;
1331
+ const { model, prefilledProps } = props;
1332
+ let data = prefilledProps || {};
1333
+ data = omitBy(data, (value, key) => key.endsWith(".$"));
1334
+ const args = __spreadValues({
1335
+ schema: model.schema,
1336
+ excludeRemovedFields: false,
1337
+ excludeHiddenFields: false,
1338
+ replaceIntlFields: true,
1339
+ addExtraFields: false
1340
+ }, customArgs);
1341
+ const fields = getFieldNames(props, currentDocument, args);
1342
+ data = __spreadValues(__spreadValues({}, data), pick2(currentDocument, ...fields));
1343
+ state.deletedValues.forEach((path) => {
1344
+ if (path.includes(".")) {
1345
+ compactParent(data, path);
1346
+ }
1347
+ });
1348
+ data = runCallbacks({
1349
+ callbacks: submitFormCallbacks,
1350
+ iterator: data,
1351
+ args: [
1352
+ {}
1353
+ ]
1354
+ });
1355
+ return data;
1356
+ }, "getData");
1357
+ var Form = /* @__PURE__ */ __name((props) => {
1358
+ const { initCallback, createDocument, updateDocument, deleteDocument } = props;
1359
+ const initialState = getInitialStateFromProps(props);
1360
+ const { schema, originalSchema, flatSchema, initialDocument } = initialState;
1361
+ const isFirstRender = useRef2(true);
1362
+ useEffect2(() => {
1363
+ if (isFirstRender.current) {
1364
+ isFirstRender.current = false;
1365
+ return;
1366
+ }
1367
+ if (initCallback)
1368
+ initCallback(initialState.currentDocument);
1369
+ }, [
1370
+ initCallback
1371
+ ]);
1372
+ const defaultProps = {
1373
+ layout: "horizontal",
1374
+ prefilledProps: {},
1375
+ repeatErrors: false,
1376
+ showRemove: true,
1377
+ showDelete: true
1378
+ };
1379
+ const allProps = __spreadValues(__spreadValues({}, defaultProps), props);
1380
+ const defaultValues = {};
1381
+ const submitFormCallbacks = [];
1382
+ const successFormCallbacks = [];
1383
+ const failureFormCallbacks = [];
1384
+ const intl = useIntlContext2();
1385
+ const [errors, setErrors] = useState([]);
1386
+ const throwError = /* @__PURE__ */ __name((error) => {
1387
+ let formErrors = getErrors(error);
1388
+ console.log(formErrors);
1389
+ setErrors((prevErrors) => [
1390
+ ...prevErrors,
1391
+ ...formErrors
1392
+ ]);
1393
+ }, "throwError");
1394
+ const clearFieldErrors = /* @__PURE__ */ __name((path) => {
1395
+ setErrors((prevErrors) => prevErrors.filter((error) => error.path !== path));
1396
+ }, "clearFieldErrors");
1397
+ const [deletedValues, setDeletedValues] = useState([]);
1398
+ const addToDeletedValues = /* @__PURE__ */ __name((name) => {
1399
+ setDeletedValues((prevDeletedValues) => [
1400
+ ...prevDeletedValues,
1401
+ name
1402
+ ]);
1403
+ }, "addToDeletedValues");
1404
+ const [callbacks, setCallbacks] = useState({
1405
+ submitFormCallbacks: [],
1406
+ successFormCallbacks: [],
1407
+ failureFormCallbacks: []
1408
+ });
1409
+ const addToSubmitForm = /* @__PURE__ */ __name((callback) => {
1410
+ setCallbacks((cbs) => __spreadValues({}, cbs));
1411
+ }, "addToSubmitForm");
1412
+ const addToSuccessForm = /* @__PURE__ */ __name((callback) => {
1413
+ setCallbacks((cbs) => __spreadProps(__spreadValues({}, cbs), {
1414
+ successFormCallbacks: [
1415
+ ...cbs.successFormCallbacks,
1416
+ callback
1417
+ ]
1418
+ }));
1419
+ }, "addToSuccessForm");
1420
+ const addToFailureForm = /* @__PURE__ */ __name((callback) => {
1421
+ setCallbacks((cbs) => __spreadProps(__spreadValues({}, cbs), {
1422
+ failureFormCallbacks: [
1423
+ ...cbs.failureFormCallbacks,
1424
+ callback
1425
+ ]
1426
+ }));
1427
+ }, "addToFailureForm");
1428
+ const clearFormCallbacks = /* @__PURE__ */ __name(() => {
1429
+ setCallbacks({
1430
+ submitFormCallbacks: [],
1431
+ successFormCallbacks: [],
1432
+ failureFormCallbacks: []
1433
+ });
1434
+ }, "clearFormCallbacks");
1435
+ const [currentValues, setCurrentValues] = useState({});
1436
+ const submitFormContext = /* @__PURE__ */ __name((formType) => (event) => {
1437
+ submitForm(formType)(event);
1438
+ }, "submitFormContext");
1439
+ const [currentDocument, setCurrentDocument] = useState(initialDocument);
1440
+ const updateCurrentValues = /* @__PURE__ */ __name((newValues, options = {}) => {
1441
+ const { mode = "overwrite" } = options;
1442
+ const { changeCallback } = props;
1443
+ const newState = {
1444
+ currentValues: cloneDeep(currentValues),
1445
+ currentDocument: cloneDeep(currentDocument),
1446
+ deletedValues: cloneDeep(deletedValues)
1447
+ };
1448
+ Object.keys(newValues).forEach((key) => {
1449
+ const path = key;
1450
+ let value = newValues[key];
1451
+ if (isEmptyValue(value)) {
1452
+ unset(newState.currentValues, path);
1453
+ set2(newState.currentDocument, path, null);
1454
+ newState.deletedValues = [
1455
+ ...newState.deletedValues,
1456
+ path
1457
+ ];
1458
+ } else {
1459
+ set2(newState.currentValues, path, value);
1460
+ if (mode === "merge" && (Array.isArray(value) || isObject(value))) {
1461
+ const oldValue = get2(newState.currentDocument, path);
1462
+ set2(newState.currentDocument, path, merge2(oldValue, value));
1463
+ } else {
1464
+ set2(newState.currentDocument, path, value);
1465
+ }
1466
+ newState.deletedValues = without(newState.deletedValues, path);
1467
+ }
1468
+ });
1469
+ if (changeCallback)
1470
+ changeCallback(newState.currentDocument);
1471
+ setCurrentValues(newState.currentValues);
1472
+ setCurrentDocument(newState.currentDocument);
1473
+ setDeletedValues(newState.deletedValues);
1474
+ }, "updateCurrentValues");
1475
+ const refetchForm = /* @__PURE__ */ __name(() => {
1476
+ if (props.refetch) {
1477
+ props.refetch();
1478
+ }
1479
+ }, "refetchForm");
1480
+ const [disabled, setDisabled] = useState(false);
1481
+ const [success, setSuccess] = useState(false);
1482
+ const clearForm = /* @__PURE__ */ __name((options = {}) => {
1483
+ const { document: optionsDocument } = options;
1484
+ const document = optionsDocument ? merge2({}, props.prefilledProps, optionsDocument) : null;
1485
+ setErrors([]);
1486
+ setCurrentValues({});
1487
+ setDeletedValues([]);
1488
+ setCurrentDocument(document || initialDocument);
1489
+ setDisabled(false);
1490
+ }, "clearForm");
1491
+ const newMutationSuccessCallback = /* @__PURE__ */ __name(function(result) {
1492
+ mutationSuccessCallback(result, "new");
1493
+ }, "newMutationSuccessCallback");
1494
+ const editMutationSuccessCallback = /* @__PURE__ */ __name(function(result) {
1495
+ mutationSuccessCallback(result, "edit");
1496
+ }, "editMutationSuccessCallback");
1497
+ const formRef = useRef2(null);
1498
+ const mutationSuccessCallback = /* @__PURE__ */ __name(function(result, mutationType) {
1499
+ setDisabled(false);
1500
+ setSuccess(true);
1501
+ if (mutationType === "new")
1502
+ refetchForm();
1503
+ let { document } = result;
1504
+ if (formRef.current) {
1505
+ clearForm({
1506
+ document: mutationType === "edit" ? document : void 0
1507
+ });
1508
+ }
1509
+ document = runCallbacks({
1510
+ callbacks: successFormCallbacks,
1511
+ iterator: document,
1512
+ args: [
1513
+ {
1514
+ form: formRef.current
1515
+ }
1516
+ ]
1517
+ });
1518
+ if (props.successCallback)
1519
+ props.successCallback(document, {
1520
+ form: this
1521
+ });
1522
+ }, "mutationSuccessCallback");
1523
+ const mutationErrorCallback = /* @__PURE__ */ __name((document, error) => {
1524
+ setDisabled(false);
1525
+ console.error("// graphQL Error");
1526
+ console.error(error);
1527
+ runCallbacks({
1528
+ callbacks: failureFormCallbacks,
1529
+ iterator: error,
1530
+ args: [
1531
+ {
1532
+ error,
1533
+ form: formRef.current
1534
+ }
1535
+ ]
1536
+ });
1537
+ if (!isEmpty(error)) {
1538
+ throwError(error);
1539
+ }
1540
+ if (props.errorCallback)
1541
+ props.errorCallback(document, error, {
1542
+ form: void 0
1543
+ });
1544
+ }, "mutationErrorCallback");
1545
+ const submitForm = /* @__PURE__ */ __name((formType) => async (event) => {
1546
+ var _a, _b;
1547
+ event && event.preventDefault();
1548
+ event && event.stopPropagation();
1549
+ const { contextName } = props;
1550
+ if (disabled) {
1551
+ return;
1552
+ }
1553
+ setErrors([]);
1554
+ setDisabled(true);
1555
+ let data = getData({
1556
+ replaceIntlFields: true,
1557
+ addExtraFields: false,
1558
+ mutableFields
1559
+ }, props, {
1560
+ currentDocument,
1561
+ deletedValues
1562
+ }, {
1563
+ form: formRef.current,
1564
+ submitFormCallbacks
1565
+ });
1566
+ if (props.submitCallback) {
1567
+ data = props.submitCallback(data) || data;
1568
+ }
1569
+ if (formType === "new") {
1570
+ try {
1571
+ const result = await createDocument({
1572
+ input: {
1573
+ data,
1574
+ contextName
1575
+ }
1576
+ });
1577
+ if ((_a = result.errors) == null ? void 0 : _a.length) {
1578
+ mutationErrorCallback(document1, result.errors[0]);
1579
+ } else {
1580
+ newMutationSuccessCallback(result);
1581
+ }
1582
+ } catch (error) {
1583
+ mutationErrorCallback(document1, error);
1584
+ }
1585
+ } else {
1586
+ try {
1587
+ const documentId = currentDocument._id;
1588
+ const result = await updateDocument({
1589
+ input: {
1590
+ id: documentId,
1591
+ data,
1592
+ contextName
1593
+ }
1594
+ });
1595
+ if ((_b = result.errors) == null ? void 0 : _b.length) {
1596
+ mutationErrorCallback(document1, result.errors[0]);
1597
+ } else {
1598
+ editMutationSuccessCallback(result);
1599
+ }
1600
+ } catch (error) {
1601
+ mutationErrorCallback(document1, error);
1602
+ }
1603
+ }
1604
+ }, "submitForm");
1605
+ const deleteDocumentWithConfirm = /* @__PURE__ */ __name(() => {
1606
+ const document = currentDocument;
1607
+ const documentId = props.document._id;
1608
+ const documentTitle = document.title || document.name || "";
1609
+ const deleteDocumentConfirm = intl.formatMessage({
1610
+ id: "forms.delete_confirm"
1611
+ }, {
1612
+ title: documentTitle
1613
+ });
1614
+ if (window.confirm(deleteDocumentConfirm)) {
1615
+ deleteDocument({
1616
+ input: {
1617
+ id: documentId
1618
+ }
1619
+ }).then((mutationResult) => {
1620
+ if (props.removeSuccessCallback)
1621
+ props.removeSuccessCallback({
1622
+ documentId,
1623
+ documentTitle
1624
+ });
1625
+ refetchForm();
1626
+ }).catch((error) => {
1627
+ console.log(error);
1628
+ });
1629
+ }
1630
+ }, "deleteDocumentWithConfirm");
1631
+ const { successComponent, document: document1, currentUser, model, warnUnsavedChanges } = props;
1632
+ const FormComponents = useVulcanComponents();
1633
+ const formType1 = document1 ? "edit" : "new";
1634
+ const mutableFields = formType1 === "edit" ? getEditableFields(schema, currentUser, initialDocument) : getInsertableFields(schema, currentUser);
1635
+ const { formLayoutProps, formGroupProps } = getChildrenProps(props, {
1636
+ disabled,
1637
+ currentDocument
1638
+ }, {
1639
+ formType: formType1
1640
+ }, {
1641
+ deleteDocument: deleteDocumentWithConfirm
1642
+ });
1643
+ const isChanged = isNotSameDocument(initialDocument, currentDocument);
1644
+ return success && successComponent ? successComponent : /* @__PURE__ */ React5.createElement(FormWarnUnsaved, {
1645
+ isChanged,
1646
+ warnUnsavedChanges
1647
+ }, /* @__PURE__ */ React5.createElement(FormContext.Provider, {
1648
+ value: {
1649
+ throwError,
1650
+ clearForm,
1651
+ refetchForm,
1652
+ isChanged,
1653
+ submitForm: submitFormContext(formType1),
1654
+ addToDeletedValues,
1655
+ updateCurrentValues,
1656
+ getDocument: () => currentDocument,
1657
+ getLabel: (fieldName, fieldLocale) => getLabel(model, flatSchema, intl, fieldName, fieldLocale),
1658
+ initialDocument,
1659
+ addToSubmitForm,
1660
+ addToSuccessForm,
1661
+ addToFailureForm,
1662
+ clearFormCallbacks,
1663
+ errors,
1664
+ currentValues,
1665
+ deletedValues,
1666
+ clearFieldErrors
1667
+ }
1668
+ }, /* @__PURE__ */ React5.createElement(FormComponents.FormLayout, _extends2({}, formLayoutProps), getFieldGroups(props, {
1669
+ currentDocument,
1670
+ schema,
1671
+ flatSchema,
1672
+ originalSchema
1673
+ }, intl, mutableFields, intl.formatMessage).map((group, i) => /* @__PURE__ */ React5.createElement(FormComponents.FormGroup, _extends2({
1674
+ key: i
1675
+ }, formGroupProps(group)))))));
1676
+ }, "Form");
1677
+
1678
+ // components/form/core/Form/typings.ts
1679
+ init_esm_shims();
1680
+
1681
+ // components/form/core/FormContainer.tsx
1682
+ init_esm_shims();
1683
+ import React8 from "react";
1684
+
1685
+ // ../../node_modules/graphql-tag/lib/index.js
1686
+ init_esm_shims();
1687
+
1688
+ // ../../node_modules/tslib/modules/index.js
1689
+ init_esm_shims();
1690
+ var import_tslib = __toESM(require_tslib(), 1);
1691
+ var { __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __createBinding, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet, __classPrivateFieldIn } = import_tslib.default;
1692
+
1693
+ // ../../node_modules/graphql/index.mjs
1694
+ init_esm_shims();
1695
+
1696
+ // ../../node_modules/graphql/language/parser.mjs
1697
+ init_esm_shims();
1698
+
1699
+ // ../../node_modules/graphql/error/syntaxError.mjs
1700
+ init_esm_shims();
1701
+
1702
+ // ../../node_modules/graphql/error/GraphQLError.mjs
1703
+ init_esm_shims();
1704
+
1705
+ // ../../node_modules/graphql/jsutils/isObjectLike.mjs
1706
+ init_esm_shims();
1707
+ function _typeof(obj) {
1708
+ "@babel/helpers - typeof";
1709
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
1710
+ _typeof = /* @__PURE__ */ __name(function _typeof5(obj2) {
1711
+ return typeof obj2;
1712
+ }, "_typeof");
1713
+ } else {
1714
+ _typeof = /* @__PURE__ */ __name(function _typeof5(obj2) {
1715
+ return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
1716
+ }, "_typeof");
1717
+ }
1718
+ return _typeof(obj);
1719
+ }
1720
+ __name(_typeof, "_typeof");
1721
+ function isObjectLike(value) {
1722
+ return _typeof(value) == "object" && value !== null;
1723
+ }
1724
+ __name(isObjectLike, "isObjectLike");
1725
+
1726
+ // ../../node_modules/graphql/polyfills/symbols.mjs
1727
+ init_esm_shims();
1728
+ var SYMBOL_ITERATOR = typeof Symbol === "function" && Symbol.iterator != null ? Symbol.iterator : "@@iterator";
1729
+ var SYMBOL_ASYNC_ITERATOR = typeof Symbol === "function" && Symbol.asyncIterator != null ? Symbol.asyncIterator : "@@asyncIterator";
1730
+ var SYMBOL_TO_STRING_TAG = typeof Symbol === "function" && Symbol.toStringTag != null ? Symbol.toStringTag : "@@toStringTag";
1731
+
1732
+ // ../../node_modules/graphql/language/location.mjs
1733
+ init_esm_shims();
1734
+ function getLocation(source, position) {
1735
+ var lineRegexp = /\r\n|[\n\r]/g;
1736
+ var line = 1;
1737
+ var column = position + 1;
1738
+ var match;
1739
+ while ((match = lineRegexp.exec(source.body)) && match.index < position) {
1740
+ line += 1;
1741
+ column = position + 1 - (match.index + match[0].length);
1742
+ }
1743
+ return {
1744
+ line,
1745
+ column
1746
+ };
1747
+ }
1748
+ __name(getLocation, "getLocation");
1749
+
1750
+ // ../../node_modules/graphql/language/printLocation.mjs
1751
+ init_esm_shims();
1752
+ function printLocation(location) {
1753
+ return printSourceLocation(location.source, getLocation(location.source, location.start));
1754
+ }
1755
+ __name(printLocation, "printLocation");
1756
+ function printSourceLocation(source, sourceLocation) {
1757
+ var firstLineColumnOffset = source.locationOffset.column - 1;
1758
+ var body = whitespace(firstLineColumnOffset) + source.body;
1759
+ var lineIndex = sourceLocation.line - 1;
1760
+ var lineOffset = source.locationOffset.line - 1;
1761
+ var lineNum = sourceLocation.line + lineOffset;
1762
+ var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
1763
+ var columnNum = sourceLocation.column + columnOffset;
1764
+ var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");
1765
+ var lines = body.split(/\r\n|[\n\r]/g);
1766
+ var locationLine = lines[lineIndex];
1767
+ if (locationLine.length > 120) {
1768
+ var subLineIndex = Math.floor(columnNum / 80);
1769
+ var subLineColumnNum = columnNum % 80;
1770
+ var subLines = [];
1771
+ for (var i = 0; i < locationLine.length; i += 80) {
1772
+ subLines.push(locationLine.slice(i, i + 80));
1773
+ }
1409
1774
  return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function(subLine) {
1410
1775
  return ["", subLine];
1411
1776
  }), [[" ", whitespace(subLineColumnNum - 1) + "^"], ["", subLines[subLineIndex + 1]]]));
@@ -3547,150 +3912,68 @@ function parseDocument(source) {
3547
3912
  var cacheKey = normalize(source);
3548
3913
  if (!docCache.has(cacheKey)) {
3549
3914
  var parsed = parse(source, {
3550
- experimentalFragmentVariables,
3551
- allowLegacyFragmentVariables: experimentalFragmentVariables
3552
- });
3553
- if (!parsed || parsed.kind !== "Document") {
3554
- throw new Error("Not a valid GraphQL document.");
3555
- }
3556
- docCache.set(cacheKey, stripLoc(processFragments(parsed)));
3557
- }
3558
- return docCache.get(cacheKey);
3559
- }
3560
- __name(parseDocument, "parseDocument");
3561
- function gql(literals) {
3562
- var args = [];
3563
- for (var _i = 1; _i < arguments.length; _i++) {
3564
- args[_i - 1] = arguments[_i];
3565
- }
3566
- if (typeof literals === "string") {
3567
- literals = [
3568
- literals
3569
- ];
3570
- }
3571
- var result = literals[0];
3572
- args.forEach(function(arg, i) {
3573
- if (arg && arg.kind === "Document") {
3574
- result += arg.loc.source.body;
3575
- } else {
3576
- result += arg;
3577
- }
3578
- result += literals[i + 1];
3579
- });
3580
- return parseDocument(result);
3581
- }
3582
- __name(gql, "gql");
3583
- function resetCaches() {
3584
- docCache.clear();
3585
- fragmentSourceMap.clear();
3586
- }
3587
- __name(resetCaches, "resetCaches");
3588
- function disableFragmentWarnings() {
3589
- printFragmentWarnings = false;
3590
- }
3591
- __name(disableFragmentWarnings, "disableFragmentWarnings");
3592
- function enableExperimentalFragmentVariables() {
3593
- experimentalFragmentVariables = true;
3594
- }
3595
- __name(enableExperimentalFragmentVariables, "enableExperimentalFragmentVariables");
3596
- function disableExperimentalFragmentVariables() {
3597
- experimentalFragmentVariables = false;
3598
- }
3599
- __name(disableExperimentalFragmentVariables, "disableExperimentalFragmentVariables");
3600
- var extras = {
3601
- gql,
3602
- resetCaches,
3603
- disableFragmentWarnings,
3604
- enableExperimentalFragmentVariables,
3605
- disableExperimentalFragmentVariables
3606
- };
3607
- (function(gql_1) {
3608
- gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;
3609
- })(gql || (gql = {}));
3610
- gql["default"] = gql;
3611
- var lib_default = gql;
3612
-
3613
- // components/core/MutationButton.tsx
3614
- function _extends4() {
3615
- _extends4 = Object.assign || function(target) {
3616
- for (var i = 1; i < arguments.length; i++) {
3617
- var source = arguments[i];
3618
- for (var key in source) {
3619
- if (Object.prototype.hasOwnProperty.call(source, key)) {
3620
- target[key] = source[key];
3621
- }
3622
- }
3623
- }
3624
- return target;
3625
- };
3626
- return _extends4.apply(this, arguments);
3627
- }
3628
- __name(_extends4, "_extends");
3629
- var MutationButton = /* @__PURE__ */ __name((props) => {
3630
- const Components2 = useVulcanComponents();
3631
- const [loading, setLoading] = useState(false);
3632
- const [error1, setError] = useState();
3633
- const {
3634
- mutation,
3635
- loadingButtonProps = {},
3636
- label
3637
- } = props;
3638
- let { mutationArguments } = props;
3639
- const mutationAsNode = typeof mutation === "string" ? lib_default`
3640
- ${mutation}
3641
- ` : mutation;
3642
- const [mutationFunc] = useMutation(mutationAsNode);
3643
- const handleClick = /* @__PURE__ */ __name(async (e) => {
3644
- e.preventDefault();
3645
- setLoading(true);
3646
- setError(void 0);
3647
- const {
3648
- submitCallback,
3649
- successCallback,
3650
- errorCallback
3651
- } = props;
3652
- try {
3653
- if (submitCallback) {
3654
- const callbackReturn = await submitCallback(mutationArguments);
3655
- if (callbackReturn && callbackReturn.mutationArguments) {
3656
- mutationArguments = callbackReturn.mutationArguments;
3657
- }
3658
- }
3659
- const result = await mutationFunc({
3660
- variables: mutationArguments
3661
- });
3662
- if (successCallback) {
3663
- await successCallback(result);
3664
- }
3665
- } catch (error) {
3666
- setError(error);
3667
- if (errorCallback) {
3668
- await errorCallback(error);
3669
- }
3670
- } finally {
3671
- setLoading(false);
3672
- }
3673
- }, "handleClick");
3674
- const loadingButton = /* @__PURE__ */ React8.createElement(Components2.LoadingButton, _extends4({
3675
- loading,
3676
- onClick: handleClick,
3677
- label
3678
- }, loadingButtonProps));
3679
- if (error1) {
3680
- return /* @__PURE__ */ React8.createElement(Components2.TooltipTrigger, {
3681
- trigger: loadingButton,
3682
- defaultShow: true
3683
- }, error1.message.replace("GraphQL error: ", ""));
3915
+ experimentalFragmentVariables,
3916
+ allowLegacyFragmentVariables: experimentalFragmentVariables
3917
+ });
3918
+ if (!parsed || parsed.kind !== "Document") {
3919
+ throw new Error("Not a valid GraphQL document.");
3920
+ }
3921
+ docCache.set(cacheKey, stripLoc(processFragments(parsed)));
3684
3922
  }
3685
- return loadingButton;
3686
- }, "MutationButton");
3687
-
3688
- // components/form/core/index.ts
3689
- init_esm_shims();
3690
-
3691
- // components/form/core/FormContainer.tsx
3692
- init_esm_shims();
3693
- import React11 from "react";
3923
+ return docCache.get(cacheKey);
3924
+ }
3925
+ __name(parseDocument, "parseDocument");
3926
+ function gql(literals) {
3927
+ var args = [];
3928
+ for (var _i = 1; _i < arguments.length; _i++) {
3929
+ args[_i - 1] = arguments[_i];
3930
+ }
3931
+ if (typeof literals === "string") {
3932
+ literals = [
3933
+ literals
3934
+ ];
3935
+ }
3936
+ var result = literals[0];
3937
+ args.forEach(function(arg, i) {
3938
+ if (arg && arg.kind === "Document") {
3939
+ result += arg.loc.source.body;
3940
+ } else {
3941
+ result += arg;
3942
+ }
3943
+ result += literals[i + 1];
3944
+ });
3945
+ return parseDocument(result);
3946
+ }
3947
+ __name(gql, "gql");
3948
+ function resetCaches() {
3949
+ docCache.clear();
3950
+ fragmentSourceMap.clear();
3951
+ }
3952
+ __name(resetCaches, "resetCaches");
3953
+ function disableFragmentWarnings() {
3954
+ printFragmentWarnings = false;
3955
+ }
3956
+ __name(disableFragmentWarnings, "disableFragmentWarnings");
3957
+ function enableExperimentalFragmentVariables() {
3958
+ experimentalFragmentVariables = true;
3959
+ }
3960
+ __name(enableExperimentalFragmentVariables, "enableExperimentalFragmentVariables");
3961
+ function disableExperimentalFragmentVariables() {
3962
+ experimentalFragmentVariables = false;
3963
+ }
3964
+ __name(disableExperimentalFragmentVariables, "disableExperimentalFragmentVariables");
3965
+ var extras = {
3966
+ gql,
3967
+ resetCaches,
3968
+ disableFragmentWarnings,
3969
+ enableExperimentalFragmentVariables,
3970
+ disableExperimentalFragmentVariables
3971
+ };
3972
+ (function(gql_1) {
3973
+ gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;
3974
+ })(gql || (gql = {}));
3975
+ gql["default"] = gql;
3976
+ var lib_default = gql;
3694
3977
 
3695
3978
  // components/form/utils/formFragments.ts
3696
3979
  init_esm_shims();
@@ -3699,7 +3982,7 @@ import _intersection from "lodash/intersection.js";
3699
3982
  import { getCreateableFields, getUpdateableFields, getFragmentFieldNames } from "@vulcanjs/schema";
3700
3983
  import { getFieldFragment } from "@vulcanjs/graphql";
3701
3984
  import { capitalize as capitalize2 } from "@vulcanjs/utils";
3702
- import compact2 from "lodash/compact.js";
3985
+ import compact3 from "lodash/compact.js";
3703
3986
  var intlSuffix = "_intl";
3704
3987
  var getFragmentName = /* @__PURE__ */ __name((formType, multiTypeName, fragmentType) => [
3705
3988
  multiTypeName,
@@ -3815,7 +4098,7 @@ var getFormFragments = /* @__PURE__ */ __name(({ formType = "new", model, fields
3815
4098
  throw new Error(`Model ${model.name} with fields ${mutationFieldNames} yield an empty mutation fragment.`);
3816
4099
  }
3817
4100
  const generatedMutationFragment = lib_default(mutationFragmentText);
3818
- const extraQueries = compact2(getQueryFieldNames({
4101
+ const extraQueries = compact3(getQueryFieldNames({
3819
4102
  schema,
3820
4103
  options: {
3821
4104
  formType
@@ -3838,7 +4121,7 @@ var formFragments_default = getFormFragments;
3838
4121
  import { getFragmentName as getFragmentName2 } from "@vulcanjs/graphql";
3839
4122
  import { capitalize as capitalize3 } from "@vulcanjs/utils";
3840
4123
  import { useSingle, useCreate, useUpdate, useDelete } from "@vulcanjs/react-hooks";
3841
- import { debugVulcan as debugVulcan2 } from "@vulcanjs/utils";
4124
+ import { debugVulcan } from "@vulcanjs/utils";
3842
4125
 
3843
4126
  // components/VulcanCurrentUser/index.ts
3844
4127
  init_esm_shims();
@@ -3849,209 +4132,21 @@ import { useContext as useContext3 } from "react";
3849
4132
 
3850
4133
  // components/VulcanCurrentUser/Context.ts
3851
4134
  init_esm_shims();
3852
- import React9 from "react";
3853
- var VulcanCurrentUserContext = React9.createContext({
3854
- currentUser: null,
3855
- loading: false
3856
- });
3857
-
3858
- // components/VulcanCurrentUser/Consumer.tsx
3859
- var VulcanCurrentUserConsumer = VulcanCurrentUserContext.Consumer;
3860
- var useVulcanCurrentUser = /* @__PURE__ */ __name(() => useContext3(VulcanCurrentUserContext), "useVulcanCurrentUser");
3861
-
3862
- // components/VulcanCurrentUser/Provider.tsx
3863
- init_esm_shims();
3864
- import React10 from "react";
3865
- function _extends5() {
3866
- _extends5 = Object.assign || function(target) {
3867
- for (var i = 1; i < arguments.length; i++) {
3868
- var source = arguments[i];
3869
- for (var key in source) {
3870
- if (Object.prototype.hasOwnProperty.call(source, key)) {
3871
- target[key] = source[key];
3872
- }
3873
- }
3874
- }
3875
- return target;
3876
- };
3877
- return _extends5.apply(this, arguments);
3878
- }
3879
- __name(_extends5, "_extends");
3880
- var VulcanCurrentUserProvider = /* @__PURE__ */ __name((_a) => {
3881
- var _b = _a, { value } = _b, props = __objRest(_b, ["value"]);
3882
- return /* @__PURE__ */ React10.createElement(VulcanCurrentUserContext.Provider, _extends5({
3883
- value
3884
- }, props));
3885
- }, "VulcanCurrentUserProvider");
3886
-
3887
- // components/form/core/FormContainer.tsx
3888
- function _extends6() {
3889
- _extends6 = Object.assign || function(target) {
3890
- for (var i = 1; i < arguments.length; i++) {
3891
- var source = arguments[i];
3892
- for (var key in source) {
3893
- if (Object.prototype.hasOwnProperty.call(source, key)) {
3894
- target[key] = source[key];
3895
- }
3896
- }
3897
- }
3898
- return target;
3899
- };
3900
- return _extends6.apply(this, arguments);
3901
- }
3902
- __name(_extends6, "_extends");
3903
- var debugForm = debugVulcan2("form");
3904
- var useFragments = /* @__PURE__ */ __name((props, formType) => {
3905
- let queryFragment;
3906
- let queryFragmentName;
3907
- let mutationFragment;
3908
- let mutationFragmentName;
3909
- if (props.queryFragment) {
3910
- if (typeof props.queryFragment === "string") {
3911
- queryFragment = lib_default`
3912
- ${props.queryFragment}
3913
- `;
3914
- if (!props.queryFragmentName)
3915
- throw new Error("When using a string queryFragment, queryFragmentName is mandatory");
3916
- queryFragmentName = props.queryFragmentName;
3917
- } else {
3918
- queryFragment = props.queryFragment;
3919
- queryFragmentName = props.queryFragmentName || getFragmentName2(props.queryFragment);
3920
- }
3921
- }
3922
- if (props.mutationFragment) {
3923
- if (typeof props.mutationFragment === "string") {
3924
- mutationFragment = lib_default`
3925
- ${props.mutationFragment}
3926
- `;
3927
- if (!props.mutationFragmentName)
3928
- throw new Error("When using a string mutationFragment, mutationFragmentName is mandatory");
3929
- queryFragmentName = props.mutationFragmentName;
3930
- } else {
3931
- mutationFragment = props.mutationFragment;
3932
- mutationFragmentName = props.mutationFragmentName || getFragmentName2(props.mutationFragment);
3933
- }
3934
- }
3935
- let autoFormFragments;
3936
- if (!props.queryFragment || !props.mutationFragment) {
3937
- const { model, fields, addFields } = props;
3938
- autoFormFragments = formFragments_default({
3939
- formType,
3940
- model,
3941
- fields,
3942
- addFields
3943
- });
3944
- }
3945
- if (!props.queryFragment) {
3946
- queryFragment = autoFormFragments.queryFragment;
3947
- queryFragmentName = autoFormFragments.queryFragmentName;
3948
- }
3949
- if (!props.mutationFragment) {
3950
- mutationFragment = autoFormFragments.mutationFragment;
3951
- mutationFragmentName = autoFormFragments.mutationFragmentName;
3952
- }
3953
- return {
3954
- mutationFragment,
3955
- mutationFragmentName,
3956
- queryFragment,
3957
- queryFragmentName
3958
- };
3959
- }, "useFragments");
3960
- var FormContainer = /* @__PURE__ */ __name((props) => {
3961
- const { model, documentId, slug, fields, addFields, currentUser: currentUserFromProps, loadingCurrentUser: loadingCurrentUserFromProps } = props;
3962
- const { schema } = model;
3963
- const isEdit = documentId || slug;
3964
- const selector = {
3965
- documentId,
3966
- slug
3967
- };
3968
- const formType = isEdit ? "edit" : "new";
3969
- const VulcanComponents = useVulcanComponents();
3970
- const prefix = `${model.name}${capitalize3(formType)}`;
3971
- const childProps = {
3972
- formType,
3973
- schema
3974
- };
3975
- const { mutationFragment, mutationFragmentName, queryFragment, queryFragmentName } = useFragments(props, formType);
3976
- const mutationOptions = {
3977
- model,
3978
- fragment: mutationFragment,
3979
- fragmentName: mutationFragmentName
3980
- };
3981
- const queryOptions = {
3982
- model,
3983
- fragment: queryFragment,
3984
- fragmentName: queryFragmentName,
3985
- input: {
3986
- id: documentId,
3987
- enableCache: false
3988
- },
3989
- queryOptions: {
3990
- fetchPolicy: "network-only",
3991
- pollInterval: 0,
3992
- skip: formType === "new"
3993
- }
3994
- };
3995
- const { data, document: document1, loading, refetch } = useSingle(queryOptions);
3996
- if (formType !== "new") {
3997
- debugForm("useSingle result", "data", data, "document", document1, "loading", loading);
3998
- }
3999
- const [createDocument] = useCreate(mutationOptions);
4000
- const [updateDocument] = useUpdate(mutationOptions);
4001
- const [deleteDocument] = useDelete(mutationOptions);
4002
- const { currentUser: currentUserFromContext, loading: loadingCurrentUserFromContext } = useVulcanCurrentUser();
4003
- const shouldGetCurrentUserFromProps = typeof currentUserFromProps !== "undefined";
4004
- const currentUser = shouldGetCurrentUserFromProps ? currentUserFromProps : currentUserFromContext;
4005
- const loadingCurrentUser = shouldGetCurrentUserFromProps ? loadingCurrentUserFromProps : loadingCurrentUserFromContext;
4006
- const createAndReturnDocument = /* @__PURE__ */ __name(async (variables) => {
4007
- const result = await createDocument(variables);
4008
- const { errors, document } = result;
4009
- return {
4010
- document,
4011
- errors
4012
- };
4013
- }, "createAndReturnDocument");
4014
- const updateAndReturnDocument = /* @__PURE__ */ __name(async (variables) => {
4015
- const result = await updateDocument(variables);
4016
- const { errors, document } = result;
4017
- return {
4018
- document,
4019
- errors
4020
- };
4021
- }, "updateAndReturnDocument");
4022
- const deleteDocumentAndRefetch = /* @__PURE__ */ __name(async (variables) => {
4023
- await deleteDocument(variables);
4024
- }, "deleteDocumentAndRefetch");
4025
- if (isEdit && loading) {
4026
- return /* @__PURE__ */ React11.createElement(VulcanComponents.Loading, null);
4027
- }
4028
- return /* @__PURE__ */ React11.createElement(VulcanComponents.Form, _extends6({
4029
- document: document1,
4030
- loading: loading || loadingCurrentUser,
4031
- createDocument: createAndReturnDocument,
4032
- updateDocument: updateAndReturnDocument,
4033
- deleteDocument: deleteDocumentAndRefetch,
4034
- refetch,
4035
- currentUser
4036
- }, childProps, props));
4037
- }, "FormContainer");
4038
- var SmartForm = FormContainer;
4135
+ import React6 from "react";
4136
+ var VulcanCurrentUserContext = React6.createContext({
4137
+ currentUser: null,
4138
+ loading: false
4139
+ });
4039
4140
 
4040
- // components/VulcanComponents/defaultVulcanComponents/index.ts
4041
- var defaultFormComponents = {
4042
- Form,
4043
- SmartForm: FormContainer
4044
- };
4045
- var defaultDatatableComponents = {};
4046
- var defaultCellComponents = {};
4047
- var defaultCoreComponents = {
4048
- MutationButton,
4049
- LoadingButton
4050
- };
4141
+ // components/VulcanCurrentUser/Consumer.tsx
4142
+ var VulcanCurrentUserConsumer = VulcanCurrentUserContext.Consumer;
4143
+ var useVulcanCurrentUser = /* @__PURE__ */ __name(() => useContext3(VulcanCurrentUserContext), "useVulcanCurrentUser");
4051
4144
 
4052
- // components/form/core/Form/Form.tsx
4053
- function _extends7() {
4054
- _extends7 = Object.assign || function(target) {
4145
+ // components/VulcanCurrentUser/Provider.tsx
4146
+ init_esm_shims();
4147
+ import React7 from "react";
4148
+ function _extends3() {
4149
+ _extends3 = Object.assign || function(target) {
4055
4150
  for (var i = 1; i < arguments.length; i++) {
4056
4151
  var source = arguments[i];
4057
4152
  for (var key in source) {
@@ -4062,459 +4157,364 @@ function _extends7() {
4062
4157
  }
4063
4158
  return target;
4064
4159
  };
4065
- return _extends7.apply(this, arguments);
4160
+ return _extends3.apply(this, arguments);
4066
4161
  }
4067
- __name(_extends7, "_extends");
4068
- var compactParent = /* @__PURE__ */ __name((object, path) => {
4069
- const parentPath = getParentPath(path);
4070
- const compactIfArray = /* @__PURE__ */ __name((x) => Array.isArray(x) ? compact3(x) : x, "compactIfArray");
4071
- update(object, parentPath, compactIfArray);
4072
- }, "compactParent");
4073
- var getDefaultValues = /* @__PURE__ */ __name((convertedSchema) => {
4074
- return pickBy(mapValues(convertedSchema, (field) => field.defaultValue), (value) => value);
4075
- }, "getDefaultValues");
4076
- var compactObject = /* @__PURE__ */ __name((o) => omitBy(o, (f) => f === null || f === void 0), "compactObject");
4077
- var getInitialStateFromProps = /* @__PURE__ */ __name((nextProps) => {
4078
- const schema = nextProps.schema || nextProps.model.schema;
4079
- const convertedSchema = convertSchema(schema);
4080
- const formType = nextProps.document ? "edit" : "new";
4081
- const defaultValues = formType === "new" ? getDefaultValues(convertedSchema) : {};
4082
- const initialDocument = merge2({}, defaultValues, nextProps.prefilledProps, compactObject(nextProps.document));
4083
- Object.keys(convertedSchema).forEach((key) => {
4084
- let minCount = convertedSchema[key].minCount;
4085
- if (minCount) {
4086
- initialDocument[key] = initialDocument[key] || [];
4087
- while (initialDocument[key].length < minCount)
4088
- initialDocument[key].push({});
4089
- }
4090
- });
4091
- removeProperty(initialDocument, "__typename");
4092
- return {
4093
- disabled: nextProps.disabled,
4094
- errors: [],
4095
- deletedValues: [],
4096
- currentValues: {},
4097
- originalSchema: convertSchema(schema, {
4098
- removeArrays: false
4099
- }),
4100
- schema: convertedSchema,
4101
- flatSchema: convertSchema(schema, {
4102
- flatten: true
4103
- }),
4104
- initialDocument,
4105
- currentDocument: initialDocument
4106
- };
4107
- }, "getInitialStateFromProps");
4108
- var getChildrenProps = /* @__PURE__ */ __name((props, state, options, callbacks) => {
4109
- const { currentUser, repeatErrors, submitLabel, cancelLabel, revertLabel, cancelCallback, revertCallback, id, model, prefilledProps, itemProperties, contextName, showRemove, showDelete } = props;
4110
- const { disabled, currentDocument } = state;
4111
- const { formType } = options;
4112
- const { deleteDocument } = callbacks;
4113
- const commonProps = {
4114
- document: currentDocument,
4115
- formType,
4116
- currentUser,
4117
- disabled,
4118
- prefilledProps,
4119
- itemProperties,
4120
- contextName
4121
- };
4122
- const docClassName = `document-${formType}`;
4123
- const modelName = model.name.toLowerCase();
4124
- const formProps = {
4125
- className: `${docClassName} ${docClassName}-${modelName}`,
4126
- id
4127
- };
4128
- const formGroupProps = /* @__PURE__ */ __name((group) => __spreadValues(__spreadProps(__spreadValues({
4129
- key: group.name
4130
- }, group), {
4131
- group: omit(group, [
4132
- "fields"
4133
- ])
4134
- }), commonProps), "formGroupProps");
4135
- const formSubmitProps = {
4136
- model,
4137
- currentUser,
4138
- submitLabel,
4139
- cancelLabel,
4140
- revertLabel,
4141
- cancelCallback,
4142
- revertCallback,
4143
- document: currentDocument,
4144
- deleteDocument: formType === "edit" && showRemove && showDelete && deleteDocument || null
4145
- };
4146
- const formLayoutProps = {
4147
- formProps,
4148
- repeatErrors,
4149
- submitProps: formSubmitProps,
4150
- commonProps
4151
- };
4152
- return {
4153
- commonProps,
4154
- formSubmitProps,
4155
- formGroupProps,
4156
- formLayoutProps
4157
- };
4158
- }, "getChildrenProps");
4159
- var FormWarnUnsaved = /* @__PURE__ */ __name(({ isChanged, warnUnsavedChanges, children }) => {
4160
- useWarnOnUnsaved({
4161
- isChanged,
4162
- warnUnsavedChanges
4163
- });
4164
- return /* @__PURE__ */ React12.createElement(React12.Fragment, null, children);
4165
- }, "FormWarnUnsaved");
4166
- var getData = /* @__PURE__ */ __name((customArgs, props, state, { submitFormCallbacks, form }) => {
4167
- const { currentDocument } = state;
4168
- const { model, prefilledProps } = props;
4169
- let data = prefilledProps || {};
4170
- data = omitBy(data, (value, key) => key.endsWith(".$"));
4171
- const args = __spreadValues({
4172
- schema: model.schema,
4173
- excludeRemovedFields: false,
4174
- excludeHiddenFields: false,
4175
- replaceIntlFields: true,
4176
- addExtraFields: false
4177
- }, customArgs);
4178
- const fields = getFieldNames(props, currentDocument, args);
4179
- data = __spreadValues(__spreadValues({}, data), pick2(currentDocument, ...fields));
4180
- state.deletedValues.forEach((path) => {
4181
- if (path.includes(".")) {
4182
- compactParent(data, path);
4183
- }
4184
- });
4185
- data = runCallbacks({
4186
- callbacks: submitFormCallbacks,
4187
- iterator: data,
4188
- args: [
4189
- {}
4190
- ]
4191
- });
4192
- return data;
4193
- }, "getData");
4194
- var Form = /* @__PURE__ */ __name((props) => {
4195
- const { initCallback, createDocument, updateDocument, deleteDocument } = props;
4196
- const initialState = getInitialStateFromProps(props);
4197
- const { schema, originalSchema, flatSchema, initialDocument } = initialState;
4198
- const isFirstRender = useRef2(true);
4199
- useEffect2(() => {
4200
- if (isFirstRender.current) {
4201
- isFirstRender.current = false;
4202
- return;
4203
- }
4204
- if (initCallback)
4205
- initCallback(initialState.currentDocument);
4206
- }, [
4207
- initCallback
4208
- ]);
4209
- const defaultProps = {
4210
- layout: "horizontal",
4211
- prefilledProps: {},
4212
- repeatErrors: false,
4213
- showRemove: true,
4214
- showDelete: true
4215
- };
4216
- const allProps = __spreadValues(__spreadValues({}, defaultProps), props);
4217
- const defaultValues = {};
4218
- const submitFormCallbacks = [];
4219
- const successFormCallbacks = [];
4220
- const failureFormCallbacks = [];
4221
- const intl = useIntlContext2();
4222
- const [errors, setErrors] = useState2([]);
4223
- const throwError = /* @__PURE__ */ __name((error) => {
4224
- let formErrors = getErrors(error);
4225
- console.log(formErrors);
4226
- setErrors((prevErrors) => [
4227
- ...prevErrors,
4228
- ...formErrors
4229
- ]);
4230
- }, "throwError");
4231
- const clearFieldErrors = /* @__PURE__ */ __name((path) => {
4232
- setErrors((prevErrors) => prevErrors.filter((error) => error.path !== path));
4233
- }, "clearFieldErrors");
4234
- const [deletedValues, setDeletedValues] = useState2([]);
4235
- const addToDeletedValues = /* @__PURE__ */ __name((name) => {
4236
- setDeletedValues((prevDeletedValues) => [
4237
- ...prevDeletedValues,
4238
- name
4239
- ]);
4240
- }, "addToDeletedValues");
4241
- const [callbacks, setCallbacks] = useState2({
4242
- submitFormCallbacks: [],
4243
- successFormCallbacks: [],
4244
- failureFormCallbacks: []
4245
- });
4246
- const addToSubmitForm = /* @__PURE__ */ __name((callback) => {
4247
- setCallbacks((cbs) => __spreadValues({}, cbs));
4248
- }, "addToSubmitForm");
4249
- const addToSuccessForm = /* @__PURE__ */ __name((callback) => {
4250
- setCallbacks((cbs) => __spreadProps(__spreadValues({}, cbs), {
4251
- successFormCallbacks: [
4252
- ...cbs.successFormCallbacks,
4253
- callback
4254
- ]
4255
- }));
4256
- }, "addToSuccessForm");
4257
- const addToFailureForm = /* @__PURE__ */ __name((callback) => {
4258
- setCallbacks((cbs) => __spreadProps(__spreadValues({}, cbs), {
4259
- failureFormCallbacks: [
4260
- ...cbs.failureFormCallbacks,
4261
- callback
4262
- ]
4263
- }));
4264
- }, "addToFailureForm");
4265
- const clearFormCallbacks = /* @__PURE__ */ __name(() => {
4266
- setCallbacks({
4267
- submitFormCallbacks: [],
4268
- successFormCallbacks: [],
4269
- failureFormCallbacks: []
4270
- });
4271
- }, "clearFormCallbacks");
4272
- const [currentValues, setCurrentValues] = useState2({});
4273
- const submitFormContext = /* @__PURE__ */ __name((formType) => (event) => {
4274
- submitForm(formType)(event);
4275
- }, "submitFormContext");
4276
- const [currentDocument, setCurrentDocument] = useState2(initialDocument);
4277
- const updateCurrentValues = /* @__PURE__ */ __name((newValues, options = {}) => {
4278
- const { mode = "overwrite" } = options;
4279
- const { changeCallback } = props;
4280
- const newState = {
4281
- currentValues: cloneDeep(currentValues),
4282
- currentDocument: cloneDeep(currentDocument),
4283
- deletedValues: cloneDeep(deletedValues)
4284
- };
4285
- Object.keys(newValues).forEach((key) => {
4286
- const path = key;
4287
- let value = newValues[key];
4288
- if (isEmptyValue(value)) {
4289
- unset(newState.currentValues, path);
4290
- set2(newState.currentDocument, path, null);
4291
- newState.deletedValues = [
4292
- ...newState.deletedValues,
4293
- path
4294
- ];
4295
- } else {
4296
- set2(newState.currentValues, path, value);
4297
- if (mode === "merge" && (Array.isArray(value) || isObject(value))) {
4298
- const oldValue = get2(newState.currentDocument, path);
4299
- set2(newState.currentDocument, path, merge2(oldValue, value));
4300
- } else {
4301
- set2(newState.currentDocument, path, value);
4162
+ __name(_extends3, "_extends");
4163
+ var VulcanCurrentUserProvider = /* @__PURE__ */ __name((_a) => {
4164
+ var _b = _a, { value } = _b, props = __objRest(_b, ["value"]);
4165
+ return /* @__PURE__ */ React7.createElement(VulcanCurrentUserContext.Provider, _extends3({
4166
+ value
4167
+ }, props));
4168
+ }, "VulcanCurrentUserProvider");
4169
+
4170
+ // components/form/core/FormContainer.tsx
4171
+ function _extends4() {
4172
+ _extends4 = Object.assign || function(target) {
4173
+ for (var i = 1; i < arguments.length; i++) {
4174
+ var source = arguments[i];
4175
+ for (var key in source) {
4176
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
4177
+ target[key] = source[key];
4302
4178
  }
4303
- newState.deletedValues = without(newState.deletedValues, path);
4304
4179
  }
4305
- });
4306
- if (changeCallback)
4307
- changeCallback(newState.currentDocument);
4308
- setCurrentValues(newState.currentValues);
4309
- setCurrentDocument(newState.currentDocument);
4310
- setDeletedValues(newState.deletedValues);
4311
- }, "updateCurrentValues");
4312
- const refetchForm = /* @__PURE__ */ __name(() => {
4313
- if (props.refetch) {
4314
- props.refetch();
4315
- }
4316
- }, "refetchForm");
4317
- const [disabled, setDisabled] = useState2(false);
4318
- const [success, setSuccess] = useState2(false);
4319
- const clearForm = /* @__PURE__ */ __name((options = {}) => {
4320
- const { document: optionsDocument } = options;
4321
- const document = optionsDocument ? merge2({}, props.prefilledProps, optionsDocument) : null;
4322
- setErrors([]);
4323
- setCurrentValues({});
4324
- setDeletedValues([]);
4325
- setCurrentDocument(document || initialDocument);
4326
- setDisabled(false);
4327
- }, "clearForm");
4328
- const newMutationSuccessCallback = /* @__PURE__ */ __name(function(result) {
4329
- mutationSuccessCallback(result, "new");
4330
- }, "newMutationSuccessCallback");
4331
- const editMutationSuccessCallback = /* @__PURE__ */ __name(function(result) {
4332
- mutationSuccessCallback(result, "edit");
4333
- }, "editMutationSuccessCallback");
4334
- const formRef = useRef2(null);
4335
- const mutationSuccessCallback = /* @__PURE__ */ __name(function(result, mutationType) {
4336
- setDisabled(false);
4337
- setSuccess(true);
4338
- if (mutationType === "new")
4339
- refetchForm();
4340
- let { document } = result;
4341
- if (formRef.current) {
4342
- clearForm({
4343
- document: mutationType === "edit" ? document : void 0
4344
- });
4345
4180
  }
4346
- document = runCallbacks({
4347
- callbacks: successFormCallbacks,
4348
- iterator: document,
4349
- args: [
4350
- {
4351
- form: formRef.current
4352
- }
4353
- ]
4354
- });
4355
- if (props.successCallback)
4356
- props.successCallback(document, {
4357
- form: this
4358
- });
4359
- }, "mutationSuccessCallback");
4360
- const mutationErrorCallback = /* @__PURE__ */ __name((document, error) => {
4361
- setDisabled(false);
4362
- console.error("// graphQL Error");
4363
- console.error(error);
4364
- runCallbacks({
4365
- callbacks: failureFormCallbacks,
4366
- iterator: error,
4367
- args: [
4368
- {
4369
- error,
4370
- form: formRef.current
4371
- }
4372
- ]
4373
- });
4374
- if (!isEmpty(error)) {
4375
- throwError(error);
4181
+ return target;
4182
+ };
4183
+ return _extends4.apply(this, arguments);
4184
+ }
4185
+ __name(_extends4, "_extends");
4186
+ var debugForm = debugVulcan("form");
4187
+ var useFragments = /* @__PURE__ */ __name((props, formType) => {
4188
+ let queryFragment;
4189
+ let queryFragmentName;
4190
+ let mutationFragment;
4191
+ let mutationFragmentName;
4192
+ if (props.queryFragment) {
4193
+ if (typeof props.queryFragment === "string") {
4194
+ queryFragment = lib_default`
4195
+ ${props.queryFragment}
4196
+ `;
4197
+ if (!props.queryFragmentName)
4198
+ throw new Error("When using a string queryFragment, queryFragmentName is mandatory");
4199
+ queryFragmentName = props.queryFragmentName;
4200
+ } else {
4201
+ queryFragment = props.queryFragment;
4202
+ queryFragmentName = props.queryFragmentName || getFragmentName2(props.queryFragment);
4376
4203
  }
4377
- if (props.errorCallback)
4378
- props.errorCallback(document, error, {
4379
- form: void 0
4380
- });
4381
- }, "mutationErrorCallback");
4382
- const submitForm = /* @__PURE__ */ __name((formType) => async (event) => {
4383
- var _a, _b;
4384
- event && event.preventDefault();
4385
- event && event.stopPropagation();
4386
- const { contextName } = props;
4387
- if (disabled) {
4388
- return;
4204
+ }
4205
+ if (props.mutationFragment) {
4206
+ if (typeof props.mutationFragment === "string") {
4207
+ mutationFragment = lib_default`
4208
+ ${props.mutationFragment}
4209
+ `;
4210
+ if (!props.mutationFragmentName)
4211
+ throw new Error("When using a string mutationFragment, mutationFragmentName is mandatory");
4212
+ queryFragmentName = props.mutationFragmentName;
4213
+ } else {
4214
+ mutationFragment = props.mutationFragment;
4215
+ mutationFragmentName = props.mutationFragmentName || getFragmentName2(props.mutationFragment);
4389
4216
  }
4390
- setErrors([]);
4391
- setDisabled(true);
4392
- let data = getData({
4393
- replaceIntlFields: true,
4394
- addExtraFields: false,
4395
- mutableFields
4396
- }, props, {
4397
- currentDocument,
4398
- deletedValues
4399
- }, {
4400
- form: formRef.current,
4401
- submitFormCallbacks
4217
+ }
4218
+ let autoFormFragments;
4219
+ if (!props.queryFragment || !props.mutationFragment) {
4220
+ const { model, fields, addFields } = props;
4221
+ autoFormFragments = formFragments_default({
4222
+ formType,
4223
+ model,
4224
+ fields,
4225
+ addFields
4402
4226
  });
4403
- if (props.submitCallback) {
4404
- data = props.submitCallback(data) || data;
4227
+ }
4228
+ if (!props.queryFragment) {
4229
+ queryFragment = autoFormFragments.queryFragment;
4230
+ queryFragmentName = autoFormFragments.queryFragmentName;
4231
+ }
4232
+ if (!props.mutationFragment) {
4233
+ mutationFragment = autoFormFragments.mutationFragment;
4234
+ mutationFragmentName = autoFormFragments.mutationFragmentName;
4235
+ }
4236
+ return {
4237
+ mutationFragment,
4238
+ mutationFragmentName,
4239
+ queryFragment,
4240
+ queryFragmentName
4241
+ };
4242
+ }, "useFragments");
4243
+ var FormContainer = /* @__PURE__ */ __name((props) => {
4244
+ const { model, documentId, slug, fields, addFields, currentUser: currentUserFromProps, loadingCurrentUser: loadingCurrentUserFromProps } = props;
4245
+ const { schema } = model;
4246
+ const isEdit = documentId || slug;
4247
+ const selector = {
4248
+ documentId,
4249
+ slug
4250
+ };
4251
+ const formType = isEdit ? "edit" : "new";
4252
+ const VulcanComponents = useVulcanComponents();
4253
+ const prefix = `${model.name}${capitalize3(formType)}`;
4254
+ const childProps = {
4255
+ formType,
4256
+ schema
4257
+ };
4258
+ const { mutationFragment, mutationFragmentName, queryFragment, queryFragmentName } = useFragments(props, formType);
4259
+ const mutationOptions = {
4260
+ model,
4261
+ fragment: mutationFragment,
4262
+ fragmentName: mutationFragmentName
4263
+ };
4264
+ const queryOptions = {
4265
+ model,
4266
+ fragment: queryFragment,
4267
+ fragmentName: queryFragmentName,
4268
+ input: {
4269
+ id: documentId,
4270
+ enableCache: false
4271
+ },
4272
+ queryOptions: {
4273
+ fetchPolicy: "network-only",
4274
+ pollInterval: 0,
4275
+ skip: formType === "new"
4405
4276
  }
4406
- if (formType === "new") {
4407
- try {
4408
- const result = await createDocument({
4409
- input: {
4410
- data,
4411
- contextName
4412
- }
4413
- });
4414
- if ((_a = result.errors) == null ? void 0 : _a.length) {
4415
- mutationErrorCallback(document1, result.errors[0]);
4416
- } else {
4417
- newMutationSuccessCallback(result);
4277
+ };
4278
+ const { data, document: document1, loading, refetch } = useSingle(queryOptions);
4279
+ if (formType !== "new") {
4280
+ debugForm("useSingle result", "data", data, "document", document1, "loading", loading);
4281
+ }
4282
+ const [createDocument] = useCreate(mutationOptions);
4283
+ const [updateDocument] = useUpdate(mutationOptions);
4284
+ const [deleteDocument] = useDelete(mutationOptions);
4285
+ const { currentUser: currentUserFromContext, loading: loadingCurrentUserFromContext } = useVulcanCurrentUser();
4286
+ const shouldGetCurrentUserFromProps = typeof currentUserFromProps !== "undefined";
4287
+ const currentUser = shouldGetCurrentUserFromProps ? currentUserFromProps : currentUserFromContext;
4288
+ const loadingCurrentUser = shouldGetCurrentUserFromProps ? loadingCurrentUserFromProps : loadingCurrentUserFromContext;
4289
+ const createAndReturnDocument = /* @__PURE__ */ __name(async (variables) => {
4290
+ const result = await createDocument(variables);
4291
+ const { errors, document } = result;
4292
+ return {
4293
+ document,
4294
+ errors
4295
+ };
4296
+ }, "createAndReturnDocument");
4297
+ const updateAndReturnDocument = /* @__PURE__ */ __name(async (variables) => {
4298
+ const result = await updateDocument(variables);
4299
+ const { errors, document } = result;
4300
+ return {
4301
+ document,
4302
+ errors
4303
+ };
4304
+ }, "updateAndReturnDocument");
4305
+ const deleteDocumentAndRefetch = /* @__PURE__ */ __name(async (variables) => {
4306
+ await deleteDocument(variables);
4307
+ }, "deleteDocumentAndRefetch");
4308
+ if (isEdit && loading) {
4309
+ return /* @__PURE__ */ React8.createElement(VulcanComponents.Loading, null);
4310
+ }
4311
+ return /* @__PURE__ */ React8.createElement(VulcanComponents.Form, _extends4({
4312
+ document: document1,
4313
+ loading: loading || loadingCurrentUser,
4314
+ createDocument: createAndReturnDocument,
4315
+ updateDocument: updateAndReturnDocument,
4316
+ deleteDocument: deleteDocumentAndRefetch,
4317
+ refetch,
4318
+ currentUser
4319
+ }, childProps, props));
4320
+ }, "FormContainer");
4321
+ var SmartForm = FormContainer;
4322
+
4323
+ // components/VulcanComponents/index.ts
4324
+ init_esm_shims();
4325
+
4326
+ // components/VulcanComponents/Provider.tsx
4327
+ init_esm_shims();
4328
+ import React9 from "react";
4329
+ import { debugVulcan as debugVulcan2 } from "@vulcanjs/utils";
4330
+ function _extends5() {
4331
+ _extends5 = Object.assign || function(target) {
4332
+ for (var i = 1; i < arguments.length; i++) {
4333
+ var source = arguments[i];
4334
+ for (var key in source) {
4335
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
4336
+ target[key] = source[key];
4418
4337
  }
4419
- } catch (error) {
4420
- mutationErrorCallback(document1, error);
4421
4338
  }
4339
+ }
4340
+ return target;
4341
+ };
4342
+ return _extends5.apply(this, arguments);
4343
+ }
4344
+ __name(_extends5, "_extends");
4345
+ var debugComponents = debugVulcan2("components");
4346
+ var VulcanComponentsProvider = /* @__PURE__ */ __name((_a) => {
4347
+ var _b = _a, { value } = _b, props = __objRest(_b, ["value"]);
4348
+ const currentComponents = useVulcanComponents();
4349
+ debugComponents("Current components __not_initialized?", currentComponents.__not_initialized);
4350
+ const mergedComponents = __spreadValues(__spreadValues({}, (currentComponents == null ? void 0 : currentComponents.__not_initialized) ? {} : currentComponents || {}), value || {});
4351
+ debugComponents("Merged components", mergedComponents);
4352
+ Object.keys(mergedComponents).forEach((componentName) => {
4353
+ if (mergedComponents[componentName]) {
4354
+ mergedComponents[componentName].displayName = "Vulcan." + componentName;
4422
4355
  } else {
4423
- try {
4424
- const documentId = currentDocument._id;
4425
- const result = await updateDocument({
4426
- input: {
4427
- id: documentId,
4428
- data,
4429
- contextName
4430
- }
4431
- });
4432
- if ((_b = result.errors) == null ? void 0 : _b.length) {
4433
- mutationErrorCallback(document1, result.errors[0]);
4434
- } else {
4435
- editMutationSuccessCallback(result);
4356
+ console.warn(`Encountered an undefined component: ${componentName}.
4357
+ The component may not be registered, or import failed.
4358
+ For instance due to an infinite import loop when importing
4359
+ "useVulcanComponents" from index instead of Consumer.`);
4360
+ }
4361
+ });
4362
+ return /* @__PURE__ */ React9.createElement(VulcanComponentsContext.Provider, _extends5({
4363
+ value: mergedComponents
4364
+ }, props));
4365
+ }, "VulcanComponentsProvider");
4366
+
4367
+ // components/VulcanComponents/typings.ts
4368
+ init_esm_shims();
4369
+ import React10 from "react";
4370
+
4371
+ // components/VulcanComponents/defaultVulcanComponents/index.ts
4372
+ init_esm_shims();
4373
+
4374
+ // components/core/LoadingButton.tsx
4375
+ init_esm_shims();
4376
+ import React11 from "react";
4377
+ function _extends6() {
4378
+ _extends6 = Object.assign || function(target) {
4379
+ for (var i = 1; i < arguments.length; i++) {
4380
+ var source = arguments[i];
4381
+ for (var key in source) {
4382
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
4383
+ target[key] = source[key];
4436
4384
  }
4437
- } catch (error) {
4438
- mutationErrorCallback(document1, error);
4439
4385
  }
4440
4386
  }
4441
- }, "submitForm");
4442
- const deleteDocumentWithConfirm = /* @__PURE__ */ __name(() => {
4443
- const document = currentDocument;
4444
- const documentId = props.document._id;
4445
- const documentTitle = document.title || document.name || "";
4446
- const deleteDocumentConfirm = intl.formatMessage({
4447
- id: "forms.delete_confirm"
4448
- }, {
4449
- title: documentTitle
4450
- });
4451
- if (window.confirm(deleteDocumentConfirm)) {
4452
- deleteDocument({
4453
- input: {
4454
- id: documentId
4387
+ return target;
4388
+ };
4389
+ return _extends6.apply(this, arguments);
4390
+ }
4391
+ __name(_extends6, "_extends");
4392
+ var LoadingButton = /* @__PURE__ */ __name((_a) => {
4393
+ var _b = _a, { loading, label, onClick, children, className = "" } = _b, rest = __objRest(_b, ["loading", "label", "onClick", "children", "className"]);
4394
+ const Components2 = useVulcanComponents();
4395
+ const wrapperStyle = {
4396
+ position: "relative"
4397
+ };
4398
+ const labelStyle = loading ? {
4399
+ opacity: 0.5
4400
+ } : {};
4401
+ const loadingStyle = loading ? {
4402
+ position: "absolute",
4403
+ top: 0,
4404
+ bottom: 0,
4405
+ left: 0,
4406
+ right: 0,
4407
+ display: "flex",
4408
+ justifyContent: "center",
4409
+ alignItems: "center"
4410
+ } : {
4411
+ display: "none"
4412
+ };
4413
+ return /* @__PURE__ */ React11.createElement(Components2.Button, _extends6({
4414
+ className: `loading-button ${loading ? "loading-button-loading" : "loading-button-notloading"} ${className}`,
4415
+ onClick
4416
+ }, rest), /* @__PURE__ */ React11.createElement("span", {
4417
+ style: wrapperStyle
4418
+ }, /* @__PURE__ */ React11.createElement("span", {
4419
+ style: labelStyle
4420
+ }, label || children), /* @__PURE__ */ React11.createElement("span", {
4421
+ style: loadingStyle
4422
+ }, /* @__PURE__ */ React11.createElement(Components2.Loading, null))));
4423
+ }, "LoadingButton");
4424
+
4425
+ // components/core/MutationButton.tsx
4426
+ init_esm_shims();
4427
+ import React12, { useState as useState2 } from "react";
4428
+ import { useMutation } from "@apollo/client";
4429
+ function _extends7() {
4430
+ _extends7 = Object.assign || function(target) {
4431
+ for (var i = 1; i < arguments.length; i++) {
4432
+ var source = arguments[i];
4433
+ for (var key in source) {
4434
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
4435
+ target[key] = source[key];
4455
4436
  }
4456
- }).then((mutationResult) => {
4457
- if (props.removeSuccessCallback)
4458
- props.removeSuccessCallback({
4459
- documentId,
4460
- documentTitle
4461
- });
4462
- refetchForm();
4463
- }).catch((error) => {
4464
- console.log(error);
4465
- });
4437
+ }
4466
4438
  }
4467
- }, "deleteDocumentWithConfirm");
4468
- const { successComponent, document: document1, currentUser, model, warnUnsavedChanges } = props;
4469
- const FormComponents = useVulcanComponents();
4470
- const formType1 = document1 ? "edit" : "new";
4471
- const mutableFields = formType1 === "edit" ? getEditableFields(schema, currentUser, initialDocument) : getInsertableFields(schema, currentUser);
4472
- const { formLayoutProps, formGroupProps } = getChildrenProps(props, {
4473
- disabled,
4474
- currentDocument
4475
- }, {
4476
- formType: formType1
4477
- }, {
4478
- deleteDocument: deleteDocumentWithConfirm
4479
- });
4480
- const isChanged = isNotSameDocument(initialDocument, currentDocument);
4481
- return success && successComponent ? successComponent : /* @__PURE__ */ React12.createElement(FormWarnUnsaved, {
4482
- isChanged,
4483
- warnUnsavedChanges
4484
- }, /* @__PURE__ */ React12.createElement(FormContext.Provider, {
4485
- value: {
4486
- throwError,
4487
- clearForm,
4488
- refetchForm,
4489
- isChanged,
4490
- submitForm: submitFormContext(formType1),
4491
- addToDeletedValues,
4492
- updateCurrentValues,
4493
- getDocument: () => currentDocument,
4494
- getLabel: (fieldName, fieldLocale) => getLabel(model, flatSchema, intl, fieldName, fieldLocale),
4495
- initialDocument,
4496
- addToSubmitForm,
4497
- addToSuccessForm,
4498
- addToFailureForm,
4499
- clearFormCallbacks,
4500
- errors,
4501
- currentValues,
4502
- deletedValues,
4503
- clearFieldErrors
4439
+ return target;
4440
+ };
4441
+ return _extends7.apply(this, arguments);
4442
+ }
4443
+ __name(_extends7, "_extends");
4444
+ var MutationButton = /* @__PURE__ */ __name((props) => {
4445
+ const Components2 = useVulcanComponents();
4446
+ const [loading, setLoading] = useState2(false);
4447
+ const [error1, setError] = useState2();
4448
+ const {
4449
+ mutation,
4450
+ loadingButtonProps = {},
4451
+ label
4452
+ } = props;
4453
+ let { mutationArguments } = props;
4454
+ const mutationAsNode = typeof mutation === "string" ? lib_default`
4455
+ ${mutation}
4456
+ ` : mutation;
4457
+ const [mutationFunc] = useMutation(mutationAsNode);
4458
+ const handleClick = /* @__PURE__ */ __name(async (e) => {
4459
+ e.preventDefault();
4460
+ setLoading(true);
4461
+ setError(void 0);
4462
+ const {
4463
+ submitCallback,
4464
+ successCallback,
4465
+ errorCallback
4466
+ } = props;
4467
+ try {
4468
+ if (submitCallback) {
4469
+ const callbackReturn = await submitCallback(mutationArguments);
4470
+ if (callbackReturn && callbackReturn.mutationArguments) {
4471
+ mutationArguments = callbackReturn.mutationArguments;
4472
+ }
4473
+ }
4474
+ const result = await mutationFunc({
4475
+ variables: mutationArguments
4476
+ });
4477
+ if (successCallback) {
4478
+ await successCallback(result);
4479
+ }
4480
+ } catch (error) {
4481
+ setError(error);
4482
+ if (errorCallback) {
4483
+ await errorCallback(error);
4484
+ }
4485
+ } finally {
4486
+ setLoading(false);
4504
4487
  }
4505
- }, /* @__PURE__ */ React12.createElement(FormComponents.FormLayout, _extends7({}, formLayoutProps), getFieldGroups(props, {
4506
- currentDocument,
4507
- schema,
4508
- flatSchema,
4509
- originalSchema
4510
- }, intl, mutableFields, intl.formatMessage).map((group, i) => /* @__PURE__ */ React12.createElement(FormComponents.FormGroup, _extends7({
4511
- key: i
4512
- }, formGroupProps(group)))))));
4513
- }, "Form");
4488
+ }, "handleClick");
4489
+ const loadingButton = /* @__PURE__ */ React12.createElement(Components2.LoadingButton, _extends7({
4490
+ loading,
4491
+ onClick: handleClick,
4492
+ label
4493
+ }, loadingButtonProps));
4494
+ if (error1) {
4495
+ return /* @__PURE__ */ React12.createElement(Components2.TooltipTrigger, {
4496
+ trigger: loadingButton,
4497
+ defaultShow: true
4498
+ }, error1.message.replace("GraphQL error: ", ""));
4499
+ }
4500
+ return loadingButton;
4501
+ }, "MutationButton");
4514
4502
 
4515
- // components/form/core/Form/typings.ts
4503
+ // components/form/core/index.ts
4516
4504
  init_esm_shims();
4517
4505
 
4506
+ // components/VulcanComponents/defaultVulcanComponents/index.ts
4507
+ var defaultFormComponents = {
4508
+ Form,
4509
+ SmartForm: FormContainer
4510
+ };
4511
+ var defaultDatatableComponents = {};
4512
+ var defaultCellComponents = {};
4513
+ var defaultCoreComponents = {
4514
+ MutationButton,
4515
+ LoadingButton
4516
+ };
4517
+
4518
4518
  // componentsHelpers.tsx
4519
4519
  init_esm_shims();
4520
4520
  import React13 from "react";