Guest User

Untitled

a guest
Feb 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.88 KB | None | 0 0
  1. import React, {Component, PropTypes} from 'react';
  2. export default class InputStateMachine extends Component {
  3. constructor(props) {
  4. super(props);
  5. this.handleSubmit = this.handleSubmit.bind(this);
  6. this.goToState = this.goToState.bind(this);
  7. this.save = this.save.bind(this);
  8. this.state = {
  9. name: 'display',
  10. machine: this.generateState('display', props.initialValue),
  11. };
  12. }
  13. generateState(stateName, stateParam) {
  14. const previousState = this.state ? {...this.state.machine} : {};
  15. switch (stateName) {
  16. case 'display':
  17. return {
  18. processing: false,
  19. error: null,
  20. value: stateParam || previousState.value,
  21. editing: false,
  22. editValue: null,
  23. };
  24. case 'saving':
  25. return {
  26. processing: true,
  27. error: null, // Сброс предыдущей ошибки сохранения
  28. value: previousState.value,
  29. editing: true, // Отображение окна редактирования в процессе сохранения
  30. editValue: previousState.editValue,
  31. };
  32. case 'edit':
  33. return {
  34. processing: false,
  35. error: null,
  36. value: previousState.value,
  37. editing: true,
  38. editValue: stateParam,
  39. };
  40. case 'save_error':
  41. return {
  42. processing: false,
  43. error: stateParam,
  44. value: previousState.value,
  45. editing: true, // Оставляем окно редактирования открытым
  46. editValue: previousState.editValue,
  47. };
  48. case 'loading': // Идентично состоянию по умолчанию
  49. default:
  50. return {
  51. processing: true,
  52. error: null,
  53. value: null,
  54. editing: false,
  55. editValue: null,
  56. };
  57. }
  58. }
  59. goToState(stateName, stateParam) {
  60. this.setState({
  61. name: stateName,
  62. machine: this.generateState(stateName, stateParam),
  63. });
  64. }
  65. handleSubmit(e) {
  66. this.goToState('edit', e.target.value);
  67. }
  68. save(valueToSave) {
  69. this.goToState('saving');
  70. // Имитируем сохранение данных...
  71. setTimeout(() => this.goToState('display', valueToSave), 2000);
  72. }
  73. render() {
  74. const {processing, error, value, editing, editValue} = this.state.machine;
  75. if (processing) {
  76. return <p>Processing ...</p>;
  77. } else if (editing) {
  78. return (
  79. <div>
  80. <input
  81. type="text"
  82. onChange={this.handleSubmit}
  83. value={editValue || value}
  84. />
  85. {error && <p>Error: {error}</p>}
  86. <button onClick={() => this.save(editValue)}>Save</button>
  87. </div>
  88. );
  89. } else {
  90. return (
  91. <div>
  92. <p>{value}</p>
  93. <button onClick={() => this.goToState('edit', value)}>Edit</button>
  94. </div>
  95. );
  96. }
  97. }
  98. }
Add Comment
Please, Sign In to add comment