@ukhomeoffice/cop-react-form-renderer 0.1.0-beta → 1.0.0-delta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/components/CheckYourAnswers/Answer.js +48 -0
  2. package/dist/components/CheckYourAnswers/Answer.test.js +94 -0
  3. package/dist/components/CheckYourAnswers/CheckYourAnswers.js +64 -19
  4. package/dist/components/CheckYourAnswers/CheckYourAnswers.scss +0 -7
  5. package/dist/components/CheckYourAnswers/CheckYourAnswers.stories.mdx +100 -0
  6. package/dist/components/CheckYourAnswers/CheckYourAnswers.test.js +317 -0
  7. package/dist/components/FormComponent/FormComponent.js +7 -7
  8. package/dist/components/FormComponent/FormComponent.stories.mdx +167 -0
  9. package/dist/components/FormComponent/FormComponent.test.js +137 -0
  10. package/dist/components/FormPage/FormPage.js +12 -11
  11. package/dist/components/FormPage/FormPage.stories.mdx +118 -0
  12. package/dist/components/FormPage/FormPage.test.js +255 -0
  13. package/dist/components/FormRenderer/FormRenderer.js +70 -58
  14. package/dist/components/FormRenderer/FormRenderer.stories.mdx +90 -0
  15. package/dist/components/FormRenderer/FormRenderer.test.js +469 -0
  16. package/dist/components/FormRenderer/handlers/cyaAction.js +28 -0
  17. package/dist/components/FormRenderer/handlers/getPageId.js +28 -0
  18. package/dist/components/FormRenderer/handlers/getPageId.test.js +61 -0
  19. package/dist/components/FormRenderer/handlers/handlers.test.js +97 -0
  20. package/dist/components/FormRenderer/handlers/index.js +23 -0
  21. package/dist/components/FormRenderer/handlers/navigate.js +28 -0
  22. package/dist/components/FormRenderer/handlers/submissionError.js +20 -0
  23. package/dist/components/FormRenderer/helpers/canActionProceed.js +35 -0
  24. package/dist/components/FormRenderer/helpers/canActionProceed.test.js +73 -0
  25. package/dist/components/FormRenderer/helpers/canCYASubmit.js +42 -0
  26. package/dist/components/FormRenderer/helpers/canCYASubmit.test.js +155 -0
  27. package/dist/components/FormRenderer/helpers/getCYA.js +31 -0
  28. package/dist/components/FormRenderer/helpers/getCYA.test.js +38 -0
  29. package/dist/components/FormRenderer/helpers/getFormState.js +32 -0
  30. package/dist/components/FormRenderer/helpers/getFormState.test.js +61 -0
  31. package/dist/components/FormRenderer/helpers/getNextPageId.js +65 -0
  32. package/dist/components/FormRenderer/helpers/getNextPageId.test.js +90 -0
  33. package/dist/components/FormRenderer/helpers/getPage.js +34 -0
  34. package/dist/components/FormRenderer/helpers/getPage.test.js +46 -0
  35. package/dist/components/FormRenderer/helpers/index.js +27 -0
  36. package/dist/components/PageActions/ActionButton.js +58 -0
  37. package/dist/components/PageActions/ActionButton.test.js +116 -0
  38. package/dist/components/PageActions/PageActions.js +18 -25
  39. package/dist/components/PageActions/PageActions.stories.mdx +74 -0
  40. package/dist/components/PageActions/PageActions.test.js +157 -0
  41. package/dist/components/SummaryList/RowAction.js +13 -22
  42. package/dist/components/SummaryList/RowAction.test.js +94 -0
  43. package/dist/components/SummaryList/SummaryList.js +6 -20
  44. package/dist/components/SummaryList/SummaryList.scss +7 -0
  45. package/dist/components/SummaryList/SummaryList.stories.mdx +36 -0
  46. package/dist/components/SummaryList/SummaryList.test.js +197 -0
  47. package/dist/components/SummaryList/helpers/getRowActionAttributes.js +27 -0
  48. package/dist/components/SummaryList/helpers/getRowActionAttributes.test.js +77 -0
  49. package/dist/components/SummaryList/helpers/index.js +15 -0
  50. package/dist/components/index.js +8 -0
  51. package/dist/hooks/useGetRequest.js +16 -1
  52. package/dist/hooks/useHooks.js +16 -5
  53. package/dist/index.js +3 -1
  54. package/dist/models/EventTypes.js +14 -0
  55. package/dist/models/FormPages.js +14 -0
  56. package/dist/models/PageAction.js +40 -0
  57. package/dist/models/index.js +24 -0
  58. package/dist/utils/CheckYourAnswers/getCYAAction.js +9 -0
  59. package/dist/utils/CheckYourAnswers/getCYARow.js +10 -0
  60. package/dist/utils/CheckYourAnswers/getCYARowsForPage.js +9 -0
  61. package/dist/utils/CheckYourAnswers/showComponentCYA.js +6 -5
  62. package/dist/utils/Component/getComponent.js +2 -2
  63. package/dist/utils/Component/getComponent.test.js +1 -1
  64. package/dist/utils/Data/setupFormData.js +3 -3
  65. package/dist/utils/Data/setupFormData.test.js +6 -6
  66. package/dist/utils/Data/setupRefDataUrlForComponent.test.js +4 -4
  67. package/dist/utils/FormPage/getFormPage.js +12 -1
  68. package/dist/utils/FormPage/getFormPage.test.js +178 -0
  69. package/dist/utils/FormPage/getFormPages.js +11 -6
  70. package/dist/utils/FormPage/getFormPages.test.js +95 -0
  71. package/dist/utils/FormPage/getParagraphFromText.js +6 -0
  72. package/dist/utils/FormPage/getParagraphFromText.test.js +29 -0
  73. package/dist/utils/FormPage/useComponent.js +9 -2
  74. package/dist/utils/FormPage/useComponent.test.js +82 -0
  75. package/dist/utils/Format/formatData.js +32 -0
  76. package/dist/utils/Format/formatData.test.js +46 -0
  77. package/dist/utils/Format/formatDataForComponent.js +41 -0
  78. package/dist/utils/Format/formatDataForComponent.test.js +161 -0
  79. package/dist/utils/Format/formatDataForForm.js +33 -0
  80. package/dist/utils/Format/formatDataForForm.test.js +78 -0
  81. package/dist/utils/Format/formatDataForPage.js +37 -0
  82. package/dist/utils/Format/formatDataForPage.test.js +96 -0
  83. package/dist/utils/Format/index.js +26 -0
  84. package/dist/utils/Hub/getFormHub.js +18 -4
  85. package/dist/utils/Hub/getFormHub.test.js +96 -0
  86. package/dist/utils/Hub/index.js +0 -3
  87. package/dist/utils/Validate/validatePage.test.js +1 -1
  88. package/dist/utils/index.js +3 -0
  89. package/package.json +13 -9
  90. package/dist/components/FormRenderer/helpers.js +0 -66
  91. package/dist/components/FormRenderer/helpers.test.js +0 -158
@@ -5,28 +5,28 @@ function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "functi
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
- exports.default = void 0;
8
+ exports.default = exports.DEFAULT_CLASS = void 0;
9
9
 
10
- var _react = _interopRequireWildcard(require("react"));
10
+ var _copReactComponents = require("@ukhomeoffice/cop-react-components");
11
11
 
12
12
  var _propTypes = _interopRequireDefault(require("prop-types"));
13
13
 
14
- var _copReactComponents = require("@ukhomeoffice/cop-react-components");
14
+ var _react = _interopRequireWildcard(require("react"));
15
+
16
+ var _utils = _interopRequireDefault(require("../../utils"));
15
17
 
16
18
  var _FormComponent = _interopRequireDefault(require("../FormComponent"));
17
19
 
18
20
  var _PageActions = _interopRequireDefault(require("../PageActions"));
19
21
 
20
- var _utils = _interopRequireDefault(require("../../utils"));
21
-
22
22
  require("./FormPage.scss");
23
23
 
24
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25
-
26
24
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
27
25
 
28
26
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
29
27
 
28
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29
+
30
30
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
31
31
 
32
32
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
@@ -46,6 +46,7 @@ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Sy
46
46
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
47
47
 
48
48
  var DEFAULT_CLASS = 'hods-form';
49
+ exports.DEFAULT_CLASS = DEFAULT_CLASS;
49
50
 
50
51
  var FormPage = function FormPage(_ref) {
51
52
  var page = _ref.page,
@@ -89,10 +90,10 @@ var FormPage = function FormPage(_ref) {
89
90
  return /*#__PURE__*/_react.default.createElement(_FormComponent.default, {
90
91
  key: index,
91
92
  component: component,
92
- value: page.formData[component.fieldId] || '',
93
- onChange: onPageChange
93
+ onChange: onPageChange,
94
+ value: page.formData[component.fieldId] || ''
94
95
  });
95
- }), page.actions && /*#__PURE__*/_react.default.createElement(_PageActions.default, {
96
+ }), /*#__PURE__*/_react.default.createElement(_PageActions.default, {
96
97
  actions: page.actions,
97
98
  onAction: function onAction(action) {
98
99
  return _onAction(action, patch, setErrors);
@@ -106,7 +107,7 @@ FormPage.propTypes = {
106
107
  title: _propTypes.default.string,
107
108
  components: _propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.object])).isRequired,
108
109
  actions: _propTypes.default.array,
109
- formData: _propTypes.default.object
110
+ formData: _propTypes.default.object.isRequired
110
111
  }).isRequired,
111
112
  onAction: _propTypes.default.func.isRequired,
112
113
  classBlock: _propTypes.default.string,
@@ -0,0 +1,118 @@
1
+ <!-- Global imports -->
2
+ import { ArgsTable, Canvas, Meta, Story } from '@storybook/addon-docs';
3
+ import { Details, Heading, Link } from '@ukhomeoffice/cop-react-components';
4
+ import withMock from 'storybook-addon-mock';
5
+
6
+ <!-- Local imports -->
7
+ import Utils from '../../utils';
8
+ import FormPage from './FormPage';
9
+
10
+ <!-- JSON documents -->
11
+ import CIVIL_SERVANT from '../../json/areYouACivilServant.json';
12
+ import GRADE from '../../json/grade.json';
13
+ import TEAMS from '../../json/team.json';
14
+ import USER_PROFILE_DATA from '../../json/userProfile.data.json';
15
+ import USER_PROFILE from '../../json/userProfile.json';
16
+
17
+ <Meta title="Components/Form page" id="D-FormPage" component={ FormPage } decorators={[withMock]} />
18
+
19
+ <Heading size="xl" caption="Components">Form page</Heading>
20
+
21
+ Renders a page on a form with <Link href="https://ukhomeoffice.github.io/cop-react-components/?path=/docs/d-alert--default-story">COP React components</Link>,
22
+ on the basis of a <Link href="/?path=/docs/f-json-page">JSON</Link> configuration.
23
+
24
+ <Canvas withToolbar>
25
+ <Story name="Default" parameters={{
26
+ mockData: [
27
+ {
28
+ url: `${USER_PROFILE_DATA.urls.refData}/areYouACivilServant`,
29
+ method: 'GET',
30
+ status: 200,
31
+ response: CIVIL_SERVANT
32
+ },
33
+ {
34
+ url: `${USER_PROFILE_DATA.urls.refData}/grade`,
35
+ method: 'GET',
36
+ status: 200,
37
+ response: GRADE
38
+ },
39
+ {
40
+ url: `${USER_PROFILE_DATA.urls.refData}/team`,
41
+ method: 'GET',
42
+ status: 200,
43
+ response: TEAMS
44
+ }
45
+ ]
46
+ }}>
47
+ {() => {
48
+ const PAGE_JSON = USER_PROFILE.pages.find(p => p.id === 'civil-servant-status');
49
+ const PAGE = Utils.FormPage.get(PAGE_JSON, USER_PROFILE.components, { ...USER_PROFILE_DATA });
50
+ const ON_ACTION = (action, patch, onError) => {
51
+ console.log('action invoked', action, patch);
52
+ };
53
+ return (
54
+ <FormPage page={PAGE} onAction={ON_ACTION} />
55
+ );
56
+ }}
57
+ </Story>
58
+ </Canvas>
59
+
60
+ <Details summary="Properties" className="no-indent">
61
+ <ArgsTable of={ FormPage } />
62
+ </Details>
63
+
64
+
65
+ ## Variants
66
+ ### With `autocomplete`
67
+ <Canvas>
68
+ <Story name="With autocomplete" parameters={{
69
+ mockData: [
70
+ {
71
+ url: `${USER_PROFILE_DATA.urls.refData}/areYouACivilServant`,
72
+ method: 'GET',
73
+ status: 200,
74
+ response: CIVIL_SERVANT
75
+ },
76
+ {
77
+ url: `${USER_PROFILE_DATA.urls.refData}/grade`,
78
+ method: 'GET',
79
+ status: 200,
80
+ response: GRADE
81
+ },
82
+ {
83
+ url: `${USER_PROFILE_DATA.urls.refData}/team`,
84
+ method: 'GET',
85
+ status: 200,
86
+ response: TEAMS
87
+ }
88
+ ]
89
+ }}>
90
+ {() => {
91
+ const PAGE_JSON = USER_PROFILE.pages.find(p => p.id === 'team-name');
92
+ const PAGE = Utils.FormPage.get(PAGE_JSON, USER_PROFILE.components, { ...USER_PROFILE_DATA });
93
+ const ON_ACTION = (action, patch, onError) => {
94
+ console.log('action invoked', action, patch);
95
+ };
96
+ return (
97
+ <FormPage page={PAGE} onAction={ON_ACTION} />
98
+ );
99
+ }}
100
+ </Story>
101
+ </Canvas>
102
+
103
+ ### Without editable controls
104
+
105
+ <Canvas>
106
+ <Story name="Without editable controls">
107
+ {() => {
108
+ const PAGE_JSON = USER_PROFILE.pages.find(p => p.id === 'add-or-change-line-manager');
109
+ const PAGE = Utils.FormPage.get(PAGE_JSON, USER_PROFILE.components, { ...USER_PROFILE_DATA });
110
+ const ON_ACTION = (action, patch, onError) => {
111
+ console.log('action invoked', action, patch);
112
+ };
113
+ return (
114
+ <FormPage page={PAGE} onAction={ON_ACTION} />
115
+ );
116
+ }}
117
+ </Story>
118
+ </Canvas>
@@ -0,0 +1,255 @@
1
+ "use strict";
2
+
3
+ function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
4
+
5
+ var _react = require("@testing-library/react");
6
+
7
+ var _react2 = _interopRequireDefault(require("react"));
8
+
9
+ var _models = require("../../models");
10
+
11
+ var _ActionButton = require("../PageActions/ActionButton");
12
+
13
+ var _FormPage = _interopRequireWildcard(require("./FormPage"));
14
+
15
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
16
+
17
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
18
+
19
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20
+
21
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
22
+
23
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
24
+
25
+ describe('components', function () {
26
+ describe('FormPage', function () {
27
+ var TEXT = {
28
+ id: 'text',
29
+ fieldId: 'text',
30
+ type: 'text',
31
+ label: 'Text component',
32
+ hint: 'Text hint'
33
+ };
34
+ var VALUE = 'Text value';
35
+ var PAGE = {
36
+ id: 'pageId',
37
+ title: 'Page 1',
38
+ components: [TEXT],
39
+ actions: ['submit'],
40
+ formData: {
41
+ text: VALUE
42
+ }
43
+ };
44
+ var ON_ACTION_CALLS = [];
45
+
46
+ var ON_ACTION = function ON_ACTION(action, patch, onError) {
47
+ ON_ACTION_CALLS.push({
48
+ action: action,
49
+ patch: patch,
50
+ onError: onError
51
+ });
52
+ };
53
+
54
+ beforeEach(function () {
55
+ PAGE.formData = {
56
+ text: VALUE
57
+ };
58
+ ON_ACTION_CALLS.length = 0;
59
+ });
60
+ it('should render a submit page correctly', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
61
+ var _render, container, page, heading, formGroup, label, hint, input, buttonGroup, button;
62
+
63
+ return regeneratorRuntime.wrap(function _callee$(_context) {
64
+ while (1) {
65
+ switch (_context.prev = _context.next) {
66
+ case 0:
67
+ _render = (0, _react.render)( /*#__PURE__*/_react2.default.createElement(_FormPage.default, {
68
+ page: PAGE,
69
+ onAction: ON_ACTION
70
+ })), container = _render.container;
71
+ page = container.childNodes[0];
72
+ expect(page.tagName).toEqual('DIV');
73
+ expect(page.classList).toContain("".concat(_FormPage.DEFAULT_CLASS, "__page"));
74
+ heading = page.childNodes[0];
75
+ expect(heading.classList).toContain('govuk-heading-l');
76
+ expect(heading.textContent).toEqual(PAGE.title);
77
+ formGroup = page.childNodes[1];
78
+ expect(formGroup.tagName).toEqual('DIV');
79
+ expect(formGroup.classList).toContain('govuk-form-group');
80
+ label = formGroup.childNodes[0];
81
+ expect(label.tagName).toEqual('LABEL');
82
+ expect(label.classList).toContain('govuk-label');
83
+ expect(label.textContent).toEqual("".concat(TEXT.label, " (optional)"));
84
+ expect(label.getAttribute('for')).toEqual(TEXT.fieldId);
85
+ hint = formGroup.childNodes[1];
86
+ expect(hint.tagName).toEqual('SPAN');
87
+ expect(hint.classList).toContain('govuk-hint');
88
+ expect(hint.textContent).toEqual(TEXT.hint);
89
+ input = formGroup.childNodes[2];
90
+ expect(input.tagName).toEqual('INPUT');
91
+ expect(input.classList).toContain('govuk-input');
92
+ expect(input.id).toEqual(TEXT.fieldId);
93
+ expect(input.value).toEqual(VALUE);
94
+ buttonGroup = page.childNodes[2];
95
+ expect(buttonGroup.tagName).toEqual('DIV');
96
+ expect(buttonGroup.classList).toContain('govuk-button-group');
97
+ button = buttonGroup.childNodes[0];
98
+ expect(button.tagName).toEqual('BUTTON');
99
+ expect(button.classList).toContain('govuk-button');
100
+ expect(button.textContent).toEqual(_ActionButton.DEFAULT_LABEL);
101
+
102
+ case 31:
103
+ case "end":
104
+ return _context.stop();
105
+ }
106
+ }
107
+ }, _callee);
108
+ })));
109
+ it('should handle a page change appropriately', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
110
+ var _render2, container, page, input, NEW_VALUE, EVENT;
111
+
112
+ return regeneratorRuntime.wrap(function _callee2$(_context2) {
113
+ while (1) {
114
+ switch (_context2.prev = _context2.next) {
115
+ case 0:
116
+ _render2 = (0, _react.render)( /*#__PURE__*/_react2.default.createElement(_FormPage.default, {
117
+ page: PAGE,
118
+ onAction: ON_ACTION
119
+ })), container = _render2.container;
120
+ page = container.childNodes[0];
121
+ expect(page.tagName).toEqual('DIV'); // Change the input.
122
+
123
+ input = page.childNodes[1].childNodes[2];
124
+ NEW_VALUE = "".concat(VALUE, ".");
125
+ EVENT = {
126
+ target: {
127
+ name: TEXT.fieldId,
128
+ value: NEW_VALUE
129
+ }
130
+ };
131
+
132
+ _react.fireEvent.change(input, EVENT); // And confirm the formData has been changed.
133
+
134
+
135
+ expect(PAGE.formData.text).toEqual(NEW_VALUE);
136
+
137
+ case 8:
138
+ case "end":
139
+ return _context2.stop();
140
+ }
141
+ }
142
+ }, _callee2);
143
+ })));
144
+ it('should handle a page action appropriately', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
145
+ var _render3, container, page, input, NEW_VALUE, CHANGE_EVENT, button;
146
+
147
+ return regeneratorRuntime.wrap(function _callee3$(_context3) {
148
+ while (1) {
149
+ switch (_context3.prev = _context3.next) {
150
+ case 0:
151
+ _render3 = (0, _react.render)( /*#__PURE__*/_react2.default.createElement(_FormPage.default, {
152
+ page: PAGE,
153
+ onAction: ON_ACTION
154
+ })), container = _render3.container;
155
+ page = container.childNodes[0]; // Change the input.
156
+
157
+ input = page.childNodes[1].childNodes[2];
158
+ NEW_VALUE = "".concat(VALUE, ".");
159
+ CHANGE_EVENT = {
160
+ target: {
161
+ name: TEXT.fieldId,
162
+ value: NEW_VALUE
163
+ }
164
+ };
165
+
166
+ _react.fireEvent.change(input, CHANGE_EVENT); // Then click the action button.
167
+
168
+
169
+ button = page.childNodes[2].childNodes[0];
170
+
171
+ _react.fireEvent.click(button, {}); // And confirm an appropriate action was received.
172
+
173
+
174
+ expect(ON_ACTION_CALLS.length).toEqual(1);
175
+ expect(PAGE.formData.text).toEqual(NEW_VALUE);
176
+ expect(ON_ACTION_CALLS[0].action).toEqual(_models.PageAction.DEFAULTS.submit);
177
+ expect(ON_ACTION_CALLS[0].patch).toEqual({
178
+ text: NEW_VALUE
179
+ });
180
+
181
+ case 12:
182
+ case "end":
183
+ return _context3.stop();
184
+ }
185
+ }
186
+ }, _callee3);
187
+ })));
188
+ it('should display errors appropriately', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
189
+ var ERRORS, THROW_ERROR_ON_ACTION, _render4, container, page, input, NEW_VALUE, CHANGE_EVENT, button, errorSummary, errorList, error, errorLink;
190
+
191
+ return regeneratorRuntime.wrap(function _callee4$(_context4) {
192
+ while (1) {
193
+ switch (_context4.prev = _context4.next) {
194
+ case 0:
195
+ ERRORS = [{
196
+ id: TEXT.id,
197
+ error: 'Invalid value'
198
+ }];
199
+
200
+ THROW_ERROR_ON_ACTION = function THROW_ERROR_ON_ACTION(action, patch, onError) {
201
+ ON_ACTION_CALLS.push({
202
+ action: action,
203
+ patch: patch,
204
+ onError: onError
205
+ });
206
+ onError(ERRORS);
207
+ };
208
+
209
+ _render4 = (0, _react.render)( /*#__PURE__*/_react2.default.createElement(_FormPage.default, {
210
+ page: PAGE,
211
+ onAction: THROW_ERROR_ON_ACTION
212
+ })), container = _render4.container;
213
+ page = container.childNodes[0]; // Change the input.
214
+
215
+ input = page.childNodes[1].childNodes[2];
216
+ NEW_VALUE = "".concat(VALUE, ".");
217
+ CHANGE_EVENT = {
218
+ target: {
219
+ name: TEXT.fieldId,
220
+ value: NEW_VALUE
221
+ }
222
+ };
223
+
224
+ _react.fireEvent.change(input, CHANGE_EVENT); // Then click the action button, which should call the onError callback method.
225
+
226
+
227
+ button = page.childNodes[2].childNodes[0];
228
+
229
+ _react.fireEvent.click(button, {}); // And confirm the page error is now displayed.
230
+
231
+
232
+ errorSummary = page.childNodes[1];
233
+ expect(errorSummary.tagName).toEqual('DIV');
234
+ expect(errorSummary.id).toEqual('error-summary');
235
+ expect(errorSummary.classList).toContain('govuk-error-summary');
236
+ errorList = errorSummary.childNodes[1].childNodes[0];
237
+ expect(errorList.tagName).toEqual('UL');
238
+ expect(errorList.classList).toContain('govuk-error-summary__list');
239
+ expect(errorList.childNodes.length).toEqual(ERRORS.length);
240
+ error = errorList.childNodes[0];
241
+ expect(error.tagName).toEqual('LI');
242
+ errorLink = error.childNodes[0];
243
+ expect(errorLink.tagName).toEqual('A');
244
+ expect(errorLink.textContent).toEqual(ERRORS[0].error);
245
+ expect(errorLink.getAttribute('href')).toEqual("#".concat(ERRORS[0].id));
246
+
247
+ case 24:
248
+ case "end":
249
+ return _context4.stop();
250
+ }
251
+ }
252
+ }, _callee4);
253
+ })));
254
+ });
255
+ });
@@ -5,7 +5,7 @@ function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "functi
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
- exports.default = void 0;
8
+ exports.default = exports.DEFAULT_CLASS = void 0;
9
9
 
10
10
  var _copReactComponents = require("@ukhomeoffice/cop-react-components");
11
11
 
@@ -13,7 +13,7 @@ var _propTypes = _interopRequireDefault(require("prop-types"));
13
13
 
14
14
  var _react = _interopRequireWildcard(require("react"));
15
15
 
16
- var _hooks = require("../../hooks");
16
+ var _hooks2 = require("../../hooks");
17
17
 
18
18
  var _models = require("../../models");
19
19
 
@@ -23,7 +23,9 @@ var _CheckYourAnswers = _interopRequireDefault(require("../CheckYourAnswers"));
23
23
 
24
24
  var _FormPage = _interopRequireDefault(require("../FormPage"));
25
25
 
26
- var _helpers = require("./helpers");
26
+ var _handlers = _interopRequireDefault(require("./handlers"));
27
+
28
+ var _helpers = _interopRequireDefault(require("./helpers"));
27
29
 
28
30
  require("./FormRenderer.scss");
29
31
 
@@ -54,6 +56,7 @@ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Sy
54
56
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
55
57
 
56
58
  var DEFAULT_CLASS = 'hods-form';
59
+ exports.DEFAULT_CLASS = DEFAULT_CLASS;
57
60
 
58
61
  var FormRenderer = function FormRenderer(_ref) {
59
62
  var title = _ref.title,
@@ -61,9 +64,9 @@ var FormRenderer = function FormRenderer(_ref) {
61
64
  components = _ref.components,
62
65
  _pages = _ref.pages,
63
66
  _hub = _ref.hub,
64
- _cya = _ref.cya,
67
+ cya = _ref.cya,
65
68
  _data = _ref.data,
66
- hooks = _ref.hooks,
69
+ _hooks = _ref.hooks,
67
70
  classBlock = _ref.classBlock,
68
71
  classModifiers = _ref.classModifiers,
69
72
  className = _ref.className;
@@ -74,42 +77,38 @@ var FormRenderer = function FormRenderer(_ref) {
74
77
  data = _useState2[0],
75
78
  setData = _useState2[1];
76
79
 
77
- var _useState3 = (0, _react.useState)(0),
80
+ var _useState3 = (0, _react.useState)([]),
78
81
  _useState4 = _slicedToArray(_useState3, 2),
79
- redoPages = _useState4[0],
80
- setRedoPages = _useState4[1];
82
+ pages = _useState4[0],
83
+ setPages = _useState4[1];
81
84
 
82
- var _useState5 = (0, _react.useState)([]),
85
+ var _useState5 = (0, _react.useState)(undefined),
83
86
  _useState6 = _slicedToArray(_useState5, 2),
84
- pages = _useState6[0],
85
- setPages = _useState6[1];
87
+ hub = _useState6[0],
88
+ setHub = _useState6[1];
86
89
 
87
- var _useState7 = (0, _react.useState)(undefined),
90
+ var _useState7 = (0, _react.useState)(_helpers.default.getNextPageId(type, _pages)),
88
91
  _useState8 = _slicedToArray(_useState7, 2),
89
- hub = _useState8[0],
90
- setHub = _useState8[1];
92
+ pageId = _useState8[0],
93
+ setPageId = _useState8[1];
91
94
 
92
- var _useState9 = (0, _react.useState)('hub'),
95
+ var _useState9 = (0, _react.useState)(_helpers.default.getFormState(pageId, pages, hub)),
93
96
  _useState10 = _slicedToArray(_useState9, 2),
94
- pageId = _useState10[0],
95
- setPageId = _useState10[1];
96
-
97
- var _useState11 = (0, _react.useState)((0, _helpers.getFormState)(pageId, pages, hub)),
98
- _useState12 = _slicedToArray(_useState11, 2),
99
- formState = _useState12[0],
100
- setFormState = _useState12[1]; // Set up hooks.
97
+ formState = _useState10[0],
98
+ setFormState = _useState10[1]; // Set up hooks.
101
99
 
102
100
 
103
- var _useHooks = (0, _hooks.useHooks)(),
101
+ var _useHooks = (0, _hooks2.useHooks)(),
102
+ hooks = _useHooks.hooks,
104
103
  addHook = _useHooks.addHook;
105
104
 
106
105
  (0, _react.useEffect)(function () {
107
- if (hooks) {
108
- Object.keys(hooks).forEach(function (key) {
109
- addHook(key, hooks[key]);
106
+ if (_hooks) {
107
+ Object.keys(_hooks).forEach(function (key) {
108
+ addHook(key, _hooks[key]);
110
109
  });
111
110
  }
112
- }, [hooks, addHook]); // Setup data.
111
+ }, [_hooks, addHook]); // Setup data.
113
112
 
114
113
  (0, _react.useEffect)(function () {
115
114
  setData(_utils.default.Data.setupForm(_pages, components, _data));
@@ -117,61 +116,71 @@ var FormRenderer = function FormRenderer(_ref) {
117
116
 
118
117
  (0, _react.useEffect)(function () {
119
118
  setPages(_utils.default.FormPage.getAll(_pages, components, _objectSpread({}, data)));
120
- }, [components, _pages, data, redoPages, setPages]); // Setup hub.
119
+ }, [components, _pages, data, setPages]); // Setup hub.
121
120
 
122
121
  (0, _react.useEffect)(function () {
123
- setHub(_utils.default.Hub.get(type, _hub, components));
124
- }, [type, _hub, components, setHub]); // Form state.
122
+ setHub(_utils.default.Hub.get(type, _hub, components, _objectSpread({}, data)));
123
+ }, [type, _hub, data, components, setHub]); // Form state.
125
124
 
126
125
  (0, _react.useEffect)(function () {
127
- setFormState((0, _helpers.getFormState)(pageId, pages, hub));
128
- }, [pages, hub, pageId, setFormState]); // Handle actions from pages.
126
+ setFormState(_helpers.default.getFormState(pageId, pages, hub));
127
+ }, [pages, hub, pageId, setFormState]); // Call the onFormLoad hook just when this component first renders.
128
+
129
+ (0, _react.useEffect)(function () {
130
+ hooks.onFormLoad();
131
+ }, [hooks]);
132
+
133
+ var onPageChange = function onPageChange(newPageId) {
134
+ setPageId(newPageId);
135
+ hooks.onPageChange(newPageId);
136
+ }; // Handle actions from pages.
129
137
 
130
- var onAction = function onAction(action, patch, onError) {
131
- // First check the validity of the
132
- if ((0, _helpers.canActionProceed)(action, formState.page, onError)) {
138
+
139
+ var onPageAction = function onPageAction(action, patch, onError) {
140
+ // Check to see whether the action is able to proceed, which in
141
+ // in the case of a submission will validate the fields in the page.
142
+ if (_helpers.default.canActionProceed(action, formState.page, onError)) {
133
143
  if (action.type === 'navigate') {
134
- setPageId(action.url.replace('/', ''));
135
- } else if (action.type === 'cancel') {
136
- setRedoPages(Date.now);
137
- setPageId('hub');
144
+ _handlers.default.navigate(action, pageId, onPageChange);
138
145
  } else {
139
146
  // Submit.
147
+ var submissionData = _utils.default.Format.form({
148
+ pages: pages,
149
+ components: components
150
+ }, _objectSpread(_objectSpread({}, data), patch), _models.EventTypes.SUBMIT);
151
+
140
152
  if (patch) {
141
- setData(function (prev) {
142
- return _objectSpread(_objectSpread({}, prev), patch);
143
- });
144
- } // Now submit the data to the backend and, if that succeeds...
153
+ setData(submissionData);
154
+ } // Now submit the data to the backend...
155
+
145
156
 
157
+ hooks.onSubmit(action.type, submissionData, function () {
158
+ var nextPageId = _helpers.default.getNextPageId(type, pages, pageId, action);
146
159
 
147
- setPageId('hub');
160
+ onPageChange(nextPageId);
161
+ }, function (errors) {
162
+ _handlers.default.submissionError(errors, onError);
163
+ });
148
164
  }
149
165
  }
150
166
  }; // Handle navigation from "Check your answers".
151
167
 
152
168
 
153
- var onCheckYourAnswerChange = function onCheckYourAnswerChange(page) {
154
- var action = page.action;
155
-
156
- if (action && action.href) {
157
- setPageId(action.href.replace('/', ''));
158
- } else {
159
- setPageId(page.pageId);
160
- }
169
+ var onCYAAction = function onCYAAction(page) {
170
+ _handlers.default.cyaAction(page, pageId, onPageChange);
161
171
  };
162
172
 
163
173
  var classes = _utils.default.classBuilder(classBlock, classModifiers, className);
164
174
 
165
175
  return /*#__PURE__*/_react.default.createElement("div", {
166
176
  className: classes()
167
- }, title && pageId === 'hub' && /*#__PURE__*/_react.default.createElement(_copReactComponents.LargeHeading, null, title), formState.cya && /*#__PURE__*/_react.default.createElement(_CheckYourAnswers.default, _extends({
177
+ }, title && pageId === _models.FormPages.HUB && /*#__PURE__*/_react.default.createElement(_copReactComponents.LargeHeading, null, title), formState.cya && /*#__PURE__*/_react.default.createElement(_CheckYourAnswers.default, _extends({
168
178
  pages: pages
169
- }, _cya, formState.cya, {
170
- onAction: onCheckYourAnswerChange
179
+ }, cya, formState.cya, {
180
+ onAction: onCYAAction
171
181
  })), formState.page && /*#__PURE__*/_react.default.createElement(_FormPage.default, {
172
182
  page: formState.page,
173
- onAction: onAction,
174
- classes: classes
183
+ onAction: onPageAction
175
184
  }));
176
185
  };
177
186
 
@@ -186,7 +195,10 @@ FormRenderer.propTypes = {
186
195
  cya: _propTypes.default.object,
187
196
  data: _propTypes.default.object,
188
197
  hooks: _propTypes.default.shape({
189
- onRequest: _propTypes.default.func
198
+ onFormLoad: _propTypes.default.func,
199
+ onPageChange: _propTypes.default.func,
200
+ onRequest: _propTypes.default.func,
201
+ onSubmit: _propTypes.default.func
190
202
  }),
191
203
  classBlock: _propTypes.default.string,
192
204
  classModifiers: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.arrayOf(_propTypes.default.string)]),