model.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. import isEqual from 'lodash/isEqual';
  2. import {action, computed, makeObservable, observable, ObservableMap} from 'mobx';
  3. import {addErrorMessage, saveOnBlurUndoMessage} from 'sentry/actionCreators/indicator';
  4. import {APIRequestMethod, Client} from 'sentry/api';
  5. import FormState from 'sentry/components/forms/state';
  6. import {t} from 'sentry/locale';
  7. import type {Choice} from 'sentry/types';
  8. import {defined} from 'sentry/utils';
  9. type Snapshot = Map<string, FieldValue>;
  10. type SaveSnapshot = (() => number) | null;
  11. export type FieldValue = string | number | boolean | Choice | undefined; // is undefined valid here?
  12. export type FormOptions = {
  13. /**
  14. * Does the form support undo?
  15. */
  16. allowUndo?: boolean;
  17. /**
  18. * API endpoint use when saving the form model
  19. */
  20. apiEndpoint?: string;
  21. /**
  22. * API method used to save the form model
  23. */
  24. apiMethod?: APIRequestMethod;
  25. /**
  26. * Options passed to the API Client
  27. */
  28. apiOptions?: ConstructorParameters<typeof Client>[0];
  29. /**
  30. * Initial form data
  31. */
  32. initialData?: Record<string, FieldValue>;
  33. /**
  34. * Callback triggered when a field changes value
  35. */
  36. onFieldChange?: (id: string, finalValue: FieldValue) => void;
  37. /**
  38. * Callback triggered when form submission fails
  39. */
  40. onSubmitError?: (error: any, instance: FormModel, id?: string) => void;
  41. /**
  42. * Callback triggered when the form is successfully submitted
  43. */
  44. onSubmitSuccess?: (
  45. response: any,
  46. instance: FormModel,
  47. id?: string,
  48. change?: {new: FieldValue; old: FieldValue}
  49. ) => void;
  50. /**
  51. * Should the form reset when an error occurs?
  52. */
  53. resetOnError?: boolean;
  54. /**
  55. * Should the form save on blur?
  56. */
  57. saveOnBlur?: boolean;
  58. /**
  59. * Custom transformer function used before the API request
  60. */
  61. transformData?: (data: Record<string, any>, instance: FormModel) => Record<string, any>;
  62. };
  63. class FormModel {
  64. /**
  65. * Map of field name -> value
  66. */
  67. fields: ObservableMap<string, FieldValue> = observable.map();
  68. /**
  69. * Errors for individual fields
  70. * Note we don't keep error in `this.fieldState` so that we can easily
  71. * See if the form is in an "error" state with the `isError` getter
  72. */
  73. errors = new Map();
  74. /**
  75. * State of individual fields
  76. *
  77. * Map of field name -> object
  78. */
  79. fieldState = new Map();
  80. /**
  81. * State of the form as a whole
  82. */
  83. formState: FormState | undefined;
  84. /**
  85. * Holds field properties as declared in <Form>
  86. * Does not need to be observable since these props should never change
  87. */
  88. fieldDescriptor = new Map();
  89. /**
  90. * Holds a list of `fields` states
  91. */
  92. snapshots: Array<Snapshot> = [];
  93. /**
  94. * POJO of field name -> value
  95. * It holds field values "since last save"
  96. */
  97. initialData: Record<string, FieldValue> = {};
  98. api: Client;
  99. // TODO(epurkhiser): it looks like this can goa away, along with mapFormErrors,
  100. // unclear why this is part of the form model
  101. formErrors: any;
  102. options: FormOptions;
  103. constructor({initialData, apiOptions, ...options}: FormOptions = {}) {
  104. makeObservable(this, {
  105. fields: observable,
  106. errors: observable,
  107. fieldState: observable,
  108. formState: observable,
  109. isError: computed,
  110. isSaving: computed,
  111. formData: computed,
  112. formChanged: computed,
  113. resetForm: action,
  114. setFieldDescriptor: action,
  115. removeField: action,
  116. setValue: action,
  117. validateField: action,
  118. updateShowSaveState: action,
  119. updateShowReturnButtonState: action,
  120. undo: action,
  121. saveForm: action,
  122. saveField: action,
  123. saveFieldRequest: action,
  124. handleBlurField: action,
  125. setFormSaving: action,
  126. handleSaveField: action,
  127. handleCancelSaveField: action,
  128. setFieldState: action,
  129. setSaving: action,
  130. setError: action,
  131. validateForm: action,
  132. handleErrorResponse: action,
  133. submitSuccess: action,
  134. submitError: action,
  135. });
  136. this.options = options ?? {};
  137. if (initialData) {
  138. this.setInitialData(initialData);
  139. }
  140. this.api = new Client(apiOptions);
  141. }
  142. /**
  143. * Reset state of model
  144. */
  145. reset() {
  146. this.api.clear();
  147. this.fieldDescriptor.clear();
  148. this.resetForm();
  149. }
  150. resetForm() {
  151. this.fields.clear();
  152. this.errors.clear();
  153. this.fieldState.clear();
  154. this.snapshots = [];
  155. this.initialData = {};
  156. }
  157. /**
  158. * Deep equality comparison between last saved state and current fields state
  159. */
  160. get formChanged() {
  161. return !isEqual(this.initialData, Object.fromEntries(this.fields.toJSON()));
  162. }
  163. get formData() {
  164. return this.fields;
  165. }
  166. /**
  167. * Is form saving
  168. */
  169. get isSaving() {
  170. return this.formState === FormState.SAVING;
  171. }
  172. /**
  173. * Does form have any errors
  174. */
  175. get isError() {
  176. return !!this.errors.size;
  177. }
  178. /**
  179. * Sets initial form data
  180. *
  181. * Also resets snapshots
  182. */
  183. setInitialData(initialData?: Record<string, FieldValue>) {
  184. this.fields.replace(initialData || {});
  185. this.initialData = Object.fromEntries(this.fields.toJSON()) || {};
  186. this.snapshots = [new Map(this.fields.entries())];
  187. }
  188. /**
  189. * Set form options
  190. */
  191. setFormOptions(options: FormOptions) {
  192. this.options = {...this.options, ...options} || {};
  193. }
  194. /**
  195. * Set field properties
  196. */
  197. setFieldDescriptor(id: string, props) {
  198. // TODO(TS): add type to props
  199. this.fieldDescriptor.set(id, props);
  200. // Set default value iff initialData for field is undefined
  201. // This must take place before checking for `props.setValue` so that it can
  202. // be applied to `defaultValue`
  203. if (
  204. typeof props.defaultValue !== 'undefined' &&
  205. typeof this.initialData[id] === 'undefined'
  206. ) {
  207. this.initialData[id] =
  208. typeof props.defaultValue === 'function'
  209. ? props.defaultValue()
  210. : props.defaultValue;
  211. this.fields.set(id, this.initialData[id]);
  212. }
  213. if (typeof props.setValue === 'function') {
  214. this.initialData[id] = props.setValue(this.initialData[id], props);
  215. this.fields.set(id, this.initialData[id]);
  216. }
  217. }
  218. /**
  219. * Remove a field from the descriptor map and errors.
  220. */
  221. removeField(id: string) {
  222. this.fieldDescriptor.delete(id);
  223. this.errors.delete(id);
  224. }
  225. /**
  226. * Creates a cloned Map of `this.fields` and returns a closure that when called
  227. * will save Map to `snapshots
  228. */
  229. createSnapshot() {
  230. const snapshot = new Map(this.fields.entries());
  231. return () => this.snapshots.unshift(snapshot);
  232. }
  233. getDescriptor(id: string, key: string) {
  234. // Needs to call `has` or else component will not be reactive if `id` doesn't exist in observable map
  235. const descriptor = this.fieldDescriptor.has(id) && this.fieldDescriptor.get(id);
  236. if (!descriptor) {
  237. return null;
  238. }
  239. return descriptor[key];
  240. }
  241. getFieldState(id: string, key: string) {
  242. // Needs to call `has` or else component will not be reactive if `id` doesn't exist in observable map
  243. const fieldState = this.fieldState.has(id) && this.fieldState.get(id);
  244. if (!fieldState) {
  245. return null;
  246. }
  247. return fieldState[key];
  248. }
  249. getValue(id: string) {
  250. return this.fields.has(id) ? this.fields.get(id) : '';
  251. }
  252. getTransformedValue(id: string) {
  253. const fieldDescriptor = this.fieldDescriptor.get(id);
  254. const transformer =
  255. fieldDescriptor && typeof fieldDescriptor.getValue === 'function'
  256. ? fieldDescriptor.getValue
  257. : null;
  258. const value = this.getValue(id);
  259. return transformer ? transformer(value) : value;
  260. }
  261. /**
  262. * Data represented in UI
  263. */
  264. getData() {
  265. return Object.fromEntries(this.fields.toJSON());
  266. }
  267. /**
  268. * Form data that will be sent to API endpoint (i.e. after transforms)
  269. */
  270. getTransformedData() {
  271. const form = this.getData();
  272. const data = Object.keys(form)
  273. .map(id => [id, this.getTransformedValue(id)])
  274. .reduce<Record<string, any>>((acc, [id, value]) => {
  275. acc[id] = value;
  276. return acc;
  277. }, {});
  278. return this.options.transformData ? this.options.transformData(data, this) : data;
  279. }
  280. getError(id: string) {
  281. return this.errors.has(id) && this.errors.get(id);
  282. }
  283. /**
  284. * Returns true if not required or is required and is not empty
  285. */
  286. isValidRequiredField(id: string) {
  287. // Check field descriptor to see if field is required
  288. const isRequired = this.getDescriptor(id, 'required');
  289. const value = this.getValue(id);
  290. return !isRequired || (value !== '' && defined(value));
  291. }
  292. isValidField(id: string) {
  293. return (this.getError(id) || []).length === 0;
  294. }
  295. doApiRequest({
  296. apiEndpoint,
  297. apiMethod,
  298. data,
  299. }: {
  300. data: object;
  301. apiEndpoint?: string;
  302. apiMethod?: APIRequestMethod;
  303. }) {
  304. const endpoint = apiEndpoint || this.options.apiEndpoint || '';
  305. const method = apiMethod || this.options.apiMethod;
  306. return new Promise((resolve, reject) =>
  307. this.api.request(endpoint, {
  308. method,
  309. data,
  310. success: response => resolve(response),
  311. error: error => reject(error),
  312. })
  313. );
  314. }
  315. /**
  316. * Set the value of the form field
  317. * if quiet is true, we skip callbacks, validations
  318. */
  319. setValue(id: string, value: FieldValue, {quiet}: {quiet?: boolean} = {}) {
  320. const fieldDescriptor = this.fieldDescriptor.get(id);
  321. let finalValue = value;
  322. if (fieldDescriptor && typeof fieldDescriptor.transformInput === 'function') {
  323. finalValue = fieldDescriptor.transformInput(value);
  324. }
  325. this.fields.set(id, finalValue);
  326. if (quiet) {
  327. return;
  328. }
  329. if (this.options.onFieldChange) {
  330. this.options.onFieldChange(id, finalValue);
  331. }
  332. this.validateField(id);
  333. this.updateShowSaveState(id, finalValue);
  334. this.updateShowReturnButtonState(id, finalValue);
  335. }
  336. validateField(id: string) {
  337. const validate = this.getDescriptor(id, 'validate');
  338. let errors: any[] = [];
  339. if (typeof validate === 'function') {
  340. // Returns "tuples" of [id, error string]
  341. errors = validate({model: this, id, form: this.getData()}) || [];
  342. }
  343. const fieldIsRequiredMessage = t('Field is required');
  344. if (!this.isValidRequiredField(id)) {
  345. errors.push([id, fieldIsRequiredMessage]);
  346. }
  347. // If we have no errors, ensure we clear the field
  348. errors = errors.length === 0 ? [[id, null]] : errors;
  349. errors.forEach(([field, errorMessage]) => this.setError(field, errorMessage));
  350. return undefined;
  351. }
  352. updateShowSaveState(id: string, value: FieldValue) {
  353. const isValueChanged = value !== this.initialData[id];
  354. // Update field state to "show save" if save on blur is disabled for this field
  355. // (only if contents of field differs from initial value)
  356. const saveOnBlurFieldOverride = this.getDescriptor(id, 'saveOnBlur');
  357. if (typeof saveOnBlurFieldOverride === 'undefined' || saveOnBlurFieldOverride) {
  358. return;
  359. }
  360. if (this.getFieldState(id, 'showSave') === isValueChanged) {
  361. return;
  362. }
  363. this.setFieldState(id, 'showSave', isValueChanged);
  364. }
  365. updateShowReturnButtonState(id: string, value: FieldValue) {
  366. const isValueChanged = value !== this.initialData[id];
  367. const shouldShowReturnButton = this.getDescriptor(id, 'showReturnButton');
  368. if (!shouldShowReturnButton) {
  369. return;
  370. }
  371. // Only update state if state has changed
  372. if (this.getFieldState(id, 'showReturnButton') === isValueChanged) {
  373. return;
  374. }
  375. this.setFieldState(id, 'showReturnButton', isValueChanged);
  376. }
  377. /**
  378. * Changes form values to previous saved state
  379. */
  380. undo() {
  381. // Always have initial data snapshot
  382. if (this.snapshots.length < 2) {
  383. return null;
  384. }
  385. this.snapshots.shift();
  386. this.fields.replace(this.snapshots[0]);
  387. return true;
  388. }
  389. /**
  390. * Attempts to save entire form to server and saves a snapshot for undos
  391. */
  392. saveForm() {
  393. if (!this.validateForm()) {
  394. return null;
  395. }
  396. let saveSnapshot: SaveSnapshot = this.createSnapshot();
  397. const request = this.doApiRequest({
  398. data: this.getTransformedData(),
  399. });
  400. this.setFormSaving();
  401. request
  402. .then(resp => {
  403. // save snapshot
  404. if (saveSnapshot) {
  405. saveSnapshot();
  406. saveSnapshot = null;
  407. }
  408. if (this.options.onSubmitSuccess) {
  409. this.options.onSubmitSuccess(resp, this);
  410. }
  411. })
  412. .catch(resp => {
  413. // should we revert field value to last known state?
  414. saveSnapshot = null;
  415. if (this.options.resetOnError) {
  416. this.setInitialData({});
  417. }
  418. this.submitError(resp);
  419. if (this.options.onSubmitError) {
  420. this.options.onSubmitError(resp, this);
  421. }
  422. });
  423. return request;
  424. }
  425. /**
  426. * Attempts to save field and show undo message if necessary.
  427. * Calls submit handlers.
  428. * TODO(billy): This should return a promise that resolves (instead of null)
  429. */
  430. saveField(id: string, currentValue: FieldValue) {
  431. const oldValue = this.initialData[id];
  432. const savePromise = this.saveFieldRequest(id, currentValue);
  433. if (!savePromise) {
  434. return null;
  435. }
  436. return savePromise
  437. .then(resp => {
  438. const newValue = this.getValue(id);
  439. const change = {old: oldValue, new: newValue};
  440. // Only use `allowUndo` option if explicitly defined
  441. if (typeof this.options.allowUndo === 'undefined' || this.options.allowUndo) {
  442. saveOnBlurUndoMessage(change, this, id);
  443. }
  444. if (this.options.onSubmitSuccess) {
  445. this.options.onSubmitSuccess(resp, this, id, change);
  446. }
  447. return resp;
  448. })
  449. .catch(error => {
  450. if (this.options.onSubmitError) {
  451. this.options.onSubmitError(error, this, id);
  452. }
  453. return {};
  454. });
  455. }
  456. /**
  457. * Saves a field with new value
  458. *
  459. * If field has changes, field does not have errors, then it will:
  460. * Save a snapshot, apply any data transforms, perform api request.
  461. *
  462. * If successful then: 1) reset save state, 2) update `initialData`, 3) save snapshot
  463. * If failed then: 1) reset save state, 2) add error state
  464. */
  465. saveFieldRequest(id: string, currentValue: FieldValue) {
  466. const initialValue = this.initialData[id];
  467. // Don't save if field hasn't changed
  468. // Don't need to check for error state since initialData wouldn't have updated since last error
  469. if (
  470. currentValue === initialValue ||
  471. (currentValue === '' && !defined(initialValue))
  472. ) {
  473. return null;
  474. }
  475. // Check for error first
  476. this.validateField(id);
  477. if (!this.isValidField(id)) {
  478. return null;
  479. }
  480. // shallow clone fields
  481. let saveSnapshot: SaveSnapshot = this.createSnapshot();
  482. // Save field + value
  483. this.setSaving(id, true);
  484. const fieldDescriptor = this.fieldDescriptor.get(id);
  485. // Check if field needs to handle transforming request object
  486. const getData =
  487. typeof fieldDescriptor.getData === 'function' ? fieldDescriptor.getData : a => a;
  488. const request = this.doApiRequest({
  489. data: getData(
  490. {[id]: this.getTransformedValue(id)},
  491. {model: this, id, form: this.getData()}
  492. ),
  493. });
  494. request
  495. .then(data => {
  496. this.setSaving(id, false);
  497. // save snapshot
  498. if (saveSnapshot) {
  499. saveSnapshot();
  500. saveSnapshot = null;
  501. }
  502. // Update initialData after successfully saving a field as it will now be the baseline value
  503. this.initialData[id] = this.getValue(id);
  504. return data;
  505. })
  506. .catch(resp => {
  507. // should we revert field value to last known state?
  508. saveSnapshot = null;
  509. // Field can be configured to reset on error
  510. // e.g. BooleanFields
  511. const shouldReset = this.getDescriptor(id, 'resetOnError');
  512. if (shouldReset) {
  513. this.setValue(id, initialValue);
  514. }
  515. // API can return a JSON object with either:
  516. // 1) map of {[fieldName] => Array<ErrorMessages>}
  517. // 2) {'non_field_errors' => Array<ErrorMessages>}
  518. if (resp && resp.responseJSON) {
  519. // non-field errors can be camelcase or snake case
  520. const nonFieldErrors =
  521. resp.responseJSON.non_field_errors || resp.responseJSON.nonFieldErrors;
  522. // find the first entry with an error
  523. const firstError = Object.entries(resp.responseJSON).find(
  524. ([_, v]) => Array.isArray(v) && v.length
  525. )?.[1] as string | boolean | undefined;
  526. // Show resp msg from API endpoint if possible
  527. if (Array.isArray(resp.responseJSON[id]) && resp.responseJSON[id].length) {
  528. // Just take first resp for now
  529. this.setError(id, resp.responseJSON[id][0]);
  530. } else if (Array.isArray(nonFieldErrors) && nonFieldErrors.length) {
  531. addErrorMessage(nonFieldErrors[0], {duration: 10000});
  532. // Reset saving state
  533. this.setError(id, '');
  534. } else if (firstError) {
  535. this.setError(id, firstError);
  536. } else {
  537. this.setError(id, 'Failed to save');
  538. }
  539. } else {
  540. // Default error behavior
  541. this.setError(id, 'Failed to save');
  542. }
  543. // eslint-disable-next-line no-console
  544. console.error('Error saving form field', resp && resp.responseJSON);
  545. });
  546. return request;
  547. }
  548. /**
  549. * This is called when a field is blurred
  550. *
  551. * If `saveOnBlur` is set then call `saveField` and handle form callbacks accordingly
  552. */
  553. handleBlurField(id: string, currentValue: FieldValue) {
  554. // Nothing to do if `saveOnBlur` is not on
  555. if (!this.options.saveOnBlur) {
  556. return null;
  557. }
  558. // Fields can individually set `saveOnBlur` to `false` (note this is ignored when `undefined`)
  559. const saveOnBlurFieldOverride = this.getDescriptor(id, 'saveOnBlur');
  560. if (typeof saveOnBlurFieldOverride !== 'undefined' && !saveOnBlurFieldOverride) {
  561. return null;
  562. }
  563. return this.saveField(id, currentValue);
  564. }
  565. setFormSaving() {
  566. this.formState = FormState.SAVING;
  567. }
  568. /**
  569. * This is called when a field does not saveOnBlur and has an individual "Save" button
  570. */
  571. handleSaveField(id: string, currentValue: FieldValue) {
  572. const savePromise = this.saveField(id, currentValue);
  573. if (!savePromise) {
  574. return null;
  575. }
  576. return savePromise.then(() => {
  577. this.setFieldState(id, 'showSave', false);
  578. });
  579. }
  580. /**
  581. * Cancel "Save Field" state and revert form value back to initial value
  582. */
  583. handleCancelSaveField(id: string) {
  584. this.setValue(id, this.initialData[id]);
  585. this.setFieldState(id, 'showSave', false);
  586. }
  587. setFieldState(id: string, key: string, value: FieldValue) {
  588. const state = {
  589. ...(this.fieldState.get(id) || {}),
  590. [key]: value,
  591. };
  592. this.fieldState.set(id, state);
  593. }
  594. /**
  595. * Set "saving" state for field
  596. */
  597. setSaving(id: string, value: FieldValue) {
  598. // When saving, reset error state
  599. this.setError(id, false);
  600. this.setFieldState(id, FormState.SAVING, value);
  601. this.setFieldState(id, FormState.READY, !value);
  602. }
  603. /**
  604. * Set "error" state for field
  605. */
  606. setError(id: string, error: boolean | string) {
  607. // Note we don't keep error in `this.fieldState` so that we can easily
  608. // See if the form is in an "error" state with the `isError` getter
  609. if (error) {
  610. this.formState = FormState.ERROR;
  611. this.errors.set(id, error);
  612. } else {
  613. this.formState = FormState.READY;
  614. this.errors.delete(id);
  615. }
  616. // Field should no longer to "saving", but is not necessarily "ready"
  617. this.setFieldState(id, FormState.SAVING, false);
  618. }
  619. /**
  620. * Returns true if there are no errors
  621. */
  622. validateForm(): boolean {
  623. Array.from(this.fieldDescriptor.keys()).forEach(id => !this.validateField(id));
  624. return !this.isError;
  625. }
  626. handleErrorResponse({responseJSON: resp}: {responseJSON?: any} = {}) {
  627. if (!resp) {
  628. return;
  629. }
  630. // Show resp msg from API endpoint if possible
  631. Object.keys(resp).forEach(id => {
  632. // non-field errors can be camelcase or snake case
  633. const nonFieldErrors = resp.non_field_errors || resp.nonFieldErrors;
  634. if (
  635. (id === 'non_field_errors' || id === 'nonFieldErrors') &&
  636. Array.isArray(nonFieldErrors) &&
  637. nonFieldErrors.length
  638. ) {
  639. addErrorMessage(nonFieldErrors[0], {duration: 10000});
  640. } else if (Array.isArray(resp[id]) && resp[id].length) {
  641. // Just take first resp for now
  642. this.setError(id, resp[id][0]);
  643. }
  644. });
  645. }
  646. submitSuccess(data: Record<string, FieldValue>) {
  647. // update initial data
  648. this.formState = FormState.READY;
  649. this.initialData = data;
  650. }
  651. submitError(err: {responseJSON?: any}) {
  652. this.formState = FormState.ERROR;
  653. this.formErrors = this.mapFormErrors(err.responseJSON);
  654. this.handleErrorResponse({responseJSON: this.formErrors});
  655. }
  656. mapFormErrors(responseJSON?: any) {
  657. return responseJSON;
  658. }
  659. }
  660. /**
  661. * The mock model mocks the model interface to simply return values from the props
  662. *
  663. * This is valuable for using form fields outside of a Form context. Disables a
  664. * lot of functionality however.
  665. */
  666. export class MockModel {
  667. // TODO(TS)
  668. props: any;
  669. initialData: Record<string, FieldValue>;
  670. constructor(props) {
  671. this.props = props;
  672. this.initialData = {
  673. [props.name]: props.value,
  674. };
  675. }
  676. setValue() {}
  677. setFieldDescriptor() {}
  678. removeField() {}
  679. handleBlurField() {}
  680. getValue() {
  681. return this.props.value;
  682. }
  683. getError() {
  684. return this.props.error;
  685. }
  686. getFieldState() {
  687. return false;
  688. }
  689. }
  690. export default FormModel;