model.tsx 20 KB

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