html-reporter 9.8.3 → 9.9.1

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 (42) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/lib/common-utils.js +5 -0
  3. package/lib/constants/diff-modes.js +5 -0
  4. package/lib/gui/app.js +4 -0
  5. package/lib/gui/server.js +7 -1
  6. package/lib/gui/tool-runner/index.js +43 -3
  7. package/lib/gui/tool-runner/utils.js +0 -5
  8. package/lib/local-images-saver.js +1 -1
  9. package/lib/report-builder/gui.js +53 -2
  10. package/lib/report-builder/static.js +4 -0
  11. package/lib/reporter-helpers.js +26 -2
  12. package/lib/server-utils.js +16 -2
  13. package/lib/sqlite-adapter.js +40 -12
  14. package/lib/static/components/controls/selects/index.styl +1 -1
  15. package/lib/static/components/modals/screenshot-accepter/header.js +17 -0
  16. package/lib/static/components/modals/screenshot-accepter/index.js +67 -4
  17. package/lib/static/components/section/body/history/index.js +1 -1
  18. package/lib/static/components/state/index.js +33 -6
  19. package/lib/static/components/state/screenshot/diff-circle.js +3 -2
  20. package/lib/static/components/state/screenshot/resized.js +4 -3
  21. package/lib/static/components/state/state-fail/index.js +111 -92
  22. package/lib/static/components/state/state-fail/index.styl +1 -1
  23. package/lib/static/components/state/state-fail/useFitImages.js +63 -0
  24. package/lib/static/gui.min.css +1 -1
  25. package/lib/static/gui.min.js +29 -25
  26. package/lib/static/hooks/useElementSize.js +2 -2
  27. package/lib/static/hooks/useWindowSize.js +3 -3
  28. package/lib/static/modules/action-names.js +2 -0
  29. package/lib/static/modules/actions.js +25 -1
  30. package/lib/static/modules/middlewares/metrika.js +1 -0
  31. package/lib/static/modules/reducers/tree/index.js +49 -2
  32. package/lib/static/modules/reducers/tree/nodes/browsers.js +11 -0
  33. package/lib/static/modules/reducers/tree/nodes/images.js +9 -0
  34. package/lib/static/modules/reducers/tree/nodes/results.js +14 -0
  35. package/lib/static/modules/reducers/tree/nodes/suites.js +23 -1
  36. package/lib/static/modules/reducers/view.js +3 -0
  37. package/lib/static/modules/utils.js +11 -1
  38. package/lib/static/report.min.css +1 -1
  39. package/lib/static/report.min.js +29 -25
  40. package/lib/test-adapter.js +36 -10
  41. package/lib/tests-tree-builder/gui.js +68 -0
  42. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ <a name="9.9.1"></a>
6
+ ## [9.9.1](https://github.com/gemini-testing/html-reporter/compare/v9.9.0...v9.9.1) (2023-05-30)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * 3-up scaled to fit diff bubble ([58aefb8](https://github.com/gemini-testing/html-reporter/commit/58aefb8))
12
+
13
+
14
+
15
+ <a name="9.9.0"></a>
16
+ # [9.9.0](https://github.com/gemini-testing/html-reporter/compare/v9.8.3...v9.9.0) (2023-05-11)
17
+
18
+
19
+ ### Bug Fixes
20
+
21
+ * undo with remote images ([ba56a47](https://github.com/gemini-testing/html-reporter/commit/ba56a47))
22
+
23
+
24
+ ### Features
25
+
26
+ * add diff mode '3-up scaled to fit' ([75624cd](https://github.com/gemini-testing/html-reporter/commit/75624cd))
27
+ * undo screen accept ([312e0eb](https://github.com/gemini-testing/html-reporter/commit/312e0eb))
28
+
29
+
30
+ ### Performance Improvements
31
+
32
+ * preload images in screenshot-accepter mode ([126037d](https://github.com/gemini-testing/html-reporter/commit/126037d))
33
+
34
+
35
+
5
36
  <a name="9.8.3"></a>
6
37
  ## [9.8.3](https://github.com/gemini-testing/html-reporter/compare/v9.8.2...v9.8.3) (2023-04-13)
7
38
 
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('crypto');
3
4
  const {pick} = require('lodash');
4
5
  const url = require('url');
5
6
  const axios = require('axios');
@@ -15,6 +16,10 @@ const {
15
16
  QUEUED
16
17
  } = require('./constants/test-statuses');
17
18
 
19
+ exports.getShortMD5 = (str) => {
20
+ return crypto.createHash('md5').update(str, 'ascii').digest('hex').substr(0, 7);
21
+ };
22
+
18
23
  const statusPriority = [
19
24
  // non-final
20
25
  RUNNING, QUEUED,
@@ -9,6 +9,11 @@ module.exports = {
9
9
  title: '3-up scaled',
10
10
  description: 'scaled images in row'
11
11
  },
12
+ THREE_UP_SCALED_TO_FIT: {
13
+ id: '3-up-scaled-to-fit',
14
+ title: '3-up scaled to fit',
15
+ description: 'scaled to browser height images in row'
16
+ },
12
17
  ONLY_DIFF: {
13
18
  id: 'only-diff',
14
19
  title: 'Only diff',
package/lib/gui/app.js CHANGED
@@ -55,6 +55,10 @@ module.exports = class App {
55
55
  return this._toolRunner.updateReferenceImage(failedTests);
56
56
  }
57
57
 
58
+ undoAcceptImages(imageIds) {
59
+ return this._toolRunner.undoAcceptImages(imageIds);
60
+ }
61
+
58
62
  async findEqualDiffs(data) {
59
63
  return this._toolRunner.findEqualDiffs(data);
60
64
  }
package/lib/gui/server.js CHANGED
@@ -74,7 +74,7 @@ exports.start = async ({paths, hermione, guiApi, configs}) => {
74
74
  }
75
75
  });
76
76
 
77
- server.post('/get-update-reference-data', (req, res) => {
77
+ server.post('/reference-data-to-update', (req, res) => {
78
78
  try {
79
79
  const data = app.getTestsDataToUpdateRefs(req.body);
80
80
  res.json(data);
@@ -89,6 +89,12 @@ exports.start = async ({paths, hermione, guiApi, configs}) => {
89
89
  .catch(({message}) => res.status(INTERNAL_SERVER_ERROR).send({error: message}));
90
90
  });
91
91
 
92
+ server.post('/undo-accept-images', (req, res) => {
93
+ app.undoAcceptImages(req.body)
94
+ .then((updated) => res.json(updated))
95
+ .catch(({message}) => res.status(INTERNAL_SERVER_ERROR).send({error: message}));
96
+ });
97
+
92
98
  server.post('/get-find-equal-diffs-data', (req, res) => {
93
99
  try {
94
100
  const data = app.getImageDataToFindEqualDiffs(req.body);
@@ -15,7 +15,8 @@ const {logger} = require('../../common-utils');
15
15
  const reporterHelper = require('../../reporter-helpers');
16
16
  const {UPDATED} = require('../../constants/test-statuses');
17
17
  const {DATABASE_URLS_JSON_NAME, LOCAL_DATABASE_NAME} = require('../../constants/database');
18
- const {formatId, getShortMD5, mkFullTitle, mergeDatabasesForReuse, filterByEqualDiffSizes} = require('./utils');
18
+ const {getShortMD5} = require('../../common-utils');
19
+ const {formatId, mkFullTitle, mergeDatabasesForReuse, filterByEqualDiffSizes} = require('./utils');
19
20
  const {getTestsTreeFromDatabase} = require('../../db-utils/server');
20
21
 
21
22
  module.exports = class ToolRunner {
@@ -96,7 +97,7 @@ module.exports = class ToolRunner {
96
97
 
97
98
  updateReferenceImage(tests) {
98
99
  return Promise.map(tests, (test) => {
99
- const updateResult = this._prepareUpdateResult(test);
100
+ const updateResult = this._prepareTestResult(test);
100
101
  const formattedResult = this._reportBuilder.format(updateResult, UPDATED);
101
102
  const failResultId = formattedResult.id;
102
103
  const updateAttempt = this._reportBuilder.getUpdatedAttempt(formattedResult);
@@ -120,6 +121,45 @@ module.exports = class ToolRunner {
120
121
  });
121
122
  }
122
123
 
124
+ async undoAcceptImages(tests) {
125
+ const updatedImages = [], removedResults = [];
126
+
127
+ await Promise.map(tests, async (test) => {
128
+ const updateResult = this._prepareTestResult(test);
129
+ const formattedResult = this._reportBuilder.format(updateResult);
130
+
131
+ formattedResult.attempt = updateResult.attempt;
132
+
133
+ await Promise.map(updateResult.imagesInfo, async (imageInfo) => {
134
+ const {stateName} = imageInfo;
135
+ const {
136
+ updatedImage,
137
+ removedResult,
138
+ previousExpectedPath,
139
+ shouldRemoveReference,
140
+ shouldRevertReference
141
+ } = await this._reportBuilder.undoAcceptImage(formattedResult, stateName);
142
+
143
+ updatedImage && updatedImages.push(updatedImage);
144
+ removedResult && removedResults.push(removedResult);
145
+
146
+ if (shouldRemoveReference) {
147
+ await reporterHelper.removeReferenceImage(formattedResult, stateName);
148
+ }
149
+
150
+ if (shouldRevertReference) {
151
+ await reporterHelper.revertReferenceImage(formattedResult, stateName);
152
+ }
153
+
154
+ if (previousExpectedPath) {
155
+ formattedResult.updateCacheExpectedPath(stateName, previousExpectedPath);
156
+ }
157
+ });
158
+ });
159
+
160
+ return {updatedImages, removedResults};
161
+ }
162
+
123
163
  async findEqualDiffs(images) {
124
164
  const [selectedImage, ...comparedImages] = images;
125
165
  const {tolerance, antialiasingTolerance} = this.config;
@@ -190,7 +230,7 @@ module.exports = class ToolRunner {
190
230
  subscribeOnToolEvents(this._hermione, this._reportBuilder, this._eventSource, this._reportPath);
191
231
  }
192
232
 
193
- _prepareUpdateResult(test) {
233
+ _prepareTestResult(test) {
194
234
  const {browserId, attempt} = test;
195
235
  const fullTitle = mkFullTitle(test);
196
236
  const testId = formatId(getShortMD5(fullTitle), browserId);
@@ -4,7 +4,6 @@ const _ = require('lodash');
4
4
  const path = require('path');
5
5
  const fs = require('fs-extra');
6
6
  const chalk = require('chalk');
7
- const crypto = require('crypto');
8
7
  const Database = require('better-sqlite3');
9
8
 
10
9
  const {logger} = require('../../common-utils');
@@ -13,10 +12,6 @@ const {mergeTables} = require('../../db-utils/server');
13
12
 
14
13
  exports.formatId = (hash, browserId) => `${hash}/${browserId}`;
15
14
 
16
- exports.getShortMD5 = (str) => {
17
- return crypto.createHash('md5').update(str, 'ascii').digest('hex').substr(0, 7);
18
- };
19
-
20
15
  exports.mkFullTitle = ({suite, state}) => {
21
16
  return suite.path.length > 0
22
17
  ? `${suite.path.join(' ')} ${state.name}`
@@ -4,7 +4,7 @@ const utils = require('./server-utils');
4
4
 
5
5
  module.exports = {
6
6
  saveImg: async (srcCurrPath, {destPath, reportDir}) => {
7
- await utils.copyFileAsync(srcCurrPath, destPath, reportDir);
7
+ await utils.copyFileAsync(srcCurrPath, destPath, {reportDir});
8
8
 
9
9
  return destPath;
10
10
  }
@@ -1,12 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  const _ = require('lodash');
4
+ const path = require('path');
5
+
4
6
  const StaticReportBuilder = require('./static');
5
7
  const GuiTestsTreeBuilder = require('../tests-tree-builder/gui');
6
8
  const {IDLE, RUNNING, SKIPPED, FAIL, SUCCESS, UPDATED} = require('../constants/test-statuses');
7
9
  const {hasResultFails, hasNoRefImageErrors} = require('../static/modules/utils');
8
- const {isSkippedStatus} = require('../common-utils');
9
- const {getConfigForStaticFile} = require('../server-utils');
10
+ const {isSkippedStatus, isUpdatedStatus} = require('../common-utils');
11
+ const {getConfigForStaticFile, deleteFile} = require('../server-utils');
12
+ const {DB_COLUMNS} = require('../constants/database');
10
13
 
11
14
  module.exports = class GuiReportBuilder extends StaticReportBuilder {
12
15
  static create(...args) {
@@ -103,6 +106,48 @@ module.exports = class GuiReportBuilder extends StaticReportBuilder {
103
106
  return isUpdated ? attempt : attempt + 1;
104
107
  }
105
108
 
109
+ async undoAcceptImage(formattedResult, stateName) {
110
+ const resultId = formattedResult.id;
111
+ const suitePath = formattedResult.testPath;
112
+ const browserName = formattedResult.browserId;
113
+ const {
114
+ imageId,
115
+ status,
116
+ timestamp,
117
+ previousImage,
118
+ shouldRemoveResult
119
+ } = this._testsTree.getResultDataToUnacceptImage(resultId, stateName);
120
+
121
+ if (!isUpdatedStatus(status)) {
122
+ return {};
123
+ }
124
+
125
+ const previousExpectedPath = _.get(previousImage, 'expectedImg.path', null);
126
+ const shouldRemoveReference = _.isNull(previousImage.refImg.size);
127
+ const shouldRevertReference = !shouldRemoveReference;
128
+
129
+ let updatedImage, removedResult;
130
+
131
+ if (shouldRemoveResult) {
132
+ this._testsTree.removeTestResult(resultId);
133
+ formattedResult.decreaseAttemptNumber();
134
+
135
+ removedResult = resultId;
136
+ } else {
137
+ updatedImage = this._testsTree.updateImageInfo(imageId, previousImage);
138
+ }
139
+
140
+ this._deleteTestResultFromDb({where: [
141
+ `${DB_COLUMNS.SUITE_PATH} = ?`,
142
+ `${DB_COLUMNS.NAME} = ?`,
143
+ `${DB_COLUMNS.STATUS} = ?`,
144
+ `${DB_COLUMNS.TIMESTAMP} = ?`,
145
+ `json_extract(${DB_COLUMNS.IMAGES_INFO}, '$[0].stateName') = ?`
146
+ ].join(' AND ')}, JSON.stringify(suitePath), browserName, status, timestamp, stateName);
147
+
148
+ return {updatedImage, removedResult, previousExpectedPath, shouldRemoveReference, shouldRevertReference};
149
+ }
150
+
106
151
  _addTestResult(formattedResult, props, opts = {}) {
107
152
  super._addTestResult(formattedResult, props);
108
153
 
@@ -156,4 +201,10 @@ module.exports = class GuiReportBuilder extends StaticReportBuilder {
156
201
  });
157
202
  }
158
203
  }
204
+
205
+ async _removeImageFromReport(reportPath, imgPath) {
206
+ const imageAbsolutePath = path.resolve(process.cwd(), reportPath, imgPath);
207
+
208
+ await deleteFile(imageAbsolutePath);
209
+ }
159
210
  };
@@ -143,6 +143,10 @@ module.exports = class StaticReportBuilder {
143
143
  this._sqliteAdapter.write({testResult, suitePath, suiteName});
144
144
  }
145
145
 
146
+ _deleteTestResultFromDb({where, orderBy, orderDescending, limit}, ...args) {
147
+ this._sqliteAdapter.delete({where, orderBy, orderDescending, limit}, ...args);
148
+ }
149
+
146
150
  async finalize() {
147
151
  this._sqliteAdapter.close();
148
152
 
@@ -1,18 +1,42 @@
1
1
  'use strict';
2
2
 
3
3
  const path = require('path');
4
+ const tmp = require('tmp');
4
5
  const Promise = require('bluebird');
6
+ const {getShortMD5} = require('./common-utils');
5
7
  const utils = require('./server-utils');
6
8
 
7
- exports.updateReferenceImage = (testResult, reportPath, stateName) => {
9
+ const mkReferenceId = (testId, stateName) => getShortMD5(`${testId}#${stateName}`);
10
+
11
+ exports.updateReferenceImage = async (testResult, reportPath, stateName) => {
8
12
  const currImg = testResult.getCurrImg(stateName);
9
13
 
10
14
  const src = currImg.path
11
15
  ? path.resolve(reportPath, currImg.path)
12
16
  : utils.getCurrentAbsolutePath(testResult, reportPath, stateName);
13
17
 
18
+ const referencePath = testResult.getRefImg(stateName).path;
19
+
20
+ if (utils.fileExists(referencePath)) {
21
+ const referenceId = mkReferenceId(testResult.id, stateName);
22
+ const oldReferencePath = path.resolve(tmp.tmpdir, referenceId);
23
+ await utils.copyFileAsync(referencePath, oldReferencePath);
24
+ }
25
+
14
26
  return Promise.all([
15
- utils.copyFileAsync(src, testResult.getRefImg(stateName).path),
27
+ utils.copyFileAsync(src, referencePath),
16
28
  utils.copyFileAsync(src, utils.getReferenceAbsolutePath(testResult, reportPath, stateName))
17
29
  ]);
18
30
  };
31
+
32
+ exports.revertReferenceImage = (testResult, stateName) => {
33
+ const referenceId = mkReferenceId(testResult.id, stateName);
34
+ const oldReferencePath = path.resolve(tmp.tmpdir, referenceId);
35
+ const referencePath = testResult.getRefImg(stateName).path;
36
+
37
+ return utils.copyFileAsync(oldReferencePath, referencePath);
38
+ };
39
+
40
+ exports.removeReferenceImage = (testResult, stateName) => {
41
+ return utils.deleteFile(testResult.getRefImg(stateName).path);
42
+ };
@@ -47,9 +47,17 @@ function createPath(kind, result, stateName) {
47
47
  return path.join.apply(null, components);
48
48
  }
49
49
 
50
- function copyFileAsync(srcPath, destPath, reportDir = '') {
50
+ function copyFileAsync(srcPath, destPath, {reportDir = '', overwrite = true} = {}) {
51
51
  const resolvedDestPath = path.resolve(reportDir, destPath);
52
- return makeDirFor(resolvedDestPath).then(() => fs.copy(srcPath, resolvedDestPath));
52
+ return makeDirFor(resolvedDestPath).then(() => fs.copy(srcPath, resolvedDestPath, {overwrite}));
53
+ }
54
+
55
+ /**
56
+ * @param {String} filePath
57
+ * @returns {Promise}
58
+ */
59
+ function deleteFile(filePath) {
60
+ return fs.remove(filePath);
53
61
  }
54
62
 
55
63
  /**
@@ -59,6 +67,10 @@ function makeDirFor(destPath) {
59
67
  return fs.mkdirs(path.dirname(destPath));
60
68
  }
61
69
 
70
+ function fileExists(path) {
71
+ return fs.existsSync(path);
72
+ }
73
+
62
74
  function logPathToHtmlReport(pluginConfig) {
63
75
  const reportPath = `file://${path.resolve(pluginConfig.path, 'index.html')}`;
64
76
 
@@ -268,7 +280,9 @@ module.exports = {
268
280
  getDiffAbsolutePath,
269
281
 
270
282
  copyFileAsync,
283
+ deleteFile,
271
284
  makeDirFor,
285
+ fileExists,
272
286
 
273
287
  logPathToHtmlReport,
274
288
  logError,
@@ -6,7 +6,7 @@ const Database = require('better-sqlite3');
6
6
  const NestedError = require('nested-error-stacks');
7
7
  const debug = require('debug')('html-reporter:sqlite-adapter');
8
8
 
9
- const {getShortMD5} = require('./gui/tool-runner/utils.js');
9
+ const {getShortMD5} = require('./common-utils');
10
10
  const {createTablesQuery} = require('./db-utils/server');
11
11
  const {DB_SUITES_TABLE_NAME, SUITES_TABLE_COLUMNS, LOCAL_DATABASE_NAME, DATABASE_URLS_JSON_NAME} = require('./constants/database');
12
12
 
@@ -62,27 +62,21 @@ module.exports = class SqliteAdapter {
62
62
  * @param {string} queryParams.where - `WHERE ${where}`
63
63
  * @param {string} queryParams.orderBy - `ORDER BY ${orderBy}`
64
64
  * @param {boolean} queryParams.orderDescending - ASCending / DESCending
65
+ * @param {number} queryParams.limit - `LIMIT ${limit}`
65
66
  * @param {boolean} queryParams.noCache - disables caching for equal queries
66
67
  * @param {...string} queryArgs
67
68
  */
68
- query({select, where, orderBy, orderDescending, noCache = false} = {}, ...queryArgs) {
69
+ query({select, where, orderBy, orderDescending, limit, noCache = false} = {}, ...queryArgs) {
69
70
  const cacheKey = !noCache && getShortMD5(`${select}#${where}#${orderBy}${orderDescending}${queryArgs.join('#')}`);
70
71
 
71
72
  if (!noCache && this._queryCache.has(cacheKey)) {
72
73
  return this._queryCache.get(cacheKey);
73
74
  }
74
75
 
75
- let query = `SELECT ${select || '*'} FROM ${DB_SUITES_TABLE_NAME}`;
76
+ const sentence = `SELECT ${select || '*'} FROM ${DB_SUITES_TABLE_NAME}`
77
+ + this._createSentence({where, orderBy, orderDescending, limit});
76
78
 
77
- if (where) {
78
- query += ` WHERE ${where}`;
79
- }
80
-
81
- if (orderBy) {
82
- query += ` ORDER BY ${orderBy} ${orderDescending ? 'DESC' : 'ASC'}`;
83
- }
84
-
85
- const result = this._db.prepare(query).get(...queryArgs);
79
+ const result = this._db.prepare(sentence).get(...queryArgs);
86
80
 
87
81
  if (!noCache) {
88
82
  this._queryCache.set(cacheKey, result);
@@ -99,6 +93,40 @@ module.exports = class SqliteAdapter {
99
93
  this._db.prepare(`INSERT INTO ${DB_SUITES_TABLE_NAME} VALUES (${placeholders})`).run(...values);
100
94
  }
101
95
 
96
+ /**
97
+ * Delete records from database
98
+ * @param {Object} deleteParams
99
+ * @param {string} deleteParams.where - `WHERE ${where}`
100
+ * @param {string} deleteParams.orderBy - `ORDER BY ${orderBy}`
101
+ * @param {boolean} deleteParams.orderDescending - ASCending / DESCending
102
+ * @param {number} deleteParams.limit - `LIMIT ${limit}`
103
+ * @param {...string} deleteArgs
104
+ */
105
+ delete({where, orderBy, orderDescending, limit} = {}, ...deleteArgs) {
106
+ const sentence = `DELETE FROM ${DB_SUITES_TABLE_NAME}`
107
+ + this._createSentence({where, orderBy, orderDescending, limit});
108
+
109
+ this._db.prepare(sentence).run(...deleteArgs);
110
+ }
111
+
112
+ _createSentence({where, orderBy, orderDescending, limit}) {
113
+ let sentence = '';
114
+
115
+ if (where) {
116
+ sentence += ` WHERE ${where}`;
117
+ }
118
+
119
+ if (orderBy) {
120
+ sentence += ` ORDER BY ${orderBy} ${orderDescending ? 'DESC' : 'ASC'}`;
121
+ }
122
+
123
+ if (limit) {
124
+ sentence += ` LIMIT ${limit}`;
125
+ }
126
+
127
+ return sentence;
128
+ }
129
+
102
130
  _parseTestResult({suitePath, suiteName, testResult}) {
103
131
  const {
104
132
  name,
@@ -39,7 +39,7 @@
39
39
 
40
40
  &.diff-mode
41
41
  .select__dropdown.ui.dropdown
42
- min-width: 90px
42
+ min-width: 95px
43
43
 
44
44
  &.select_type_group
45
45
  .select__dropdown.ui.dropdown
@@ -25,6 +25,7 @@ export default class ScreenshotAccepterHeader extends Component {
25
25
  onRetryChange: PropTypes.func.isRequired,
26
26
  onActiveImageChange: PropTypes.func.isRequired,
27
27
  onScreenshotAccept: PropTypes.func.isRequired,
28
+ onScreenshotUndo: PropTypes.func.isRequired,
28
29
  onShowMeta: PropTypes.func.isRequired
29
30
  }
30
31
 
@@ -37,6 +38,7 @@ export default class ScreenshotAccepterHeader extends Component {
37
38
  PREV_RETRY: ['left', 'a'],
38
39
  NEXT_RETRY: ['right', 'd'],
39
40
  ACCEPT_SCREENSHOT: ['space', 'enter'],
41
+ UNDO_SCREEN: 'backspace',
40
42
  CLOSE_MODAL: 'escape',
41
43
  IGNORE_META_UP: 'meta+up',
42
44
  IGNORE_META_DOWN: 'meta+down',
@@ -48,6 +50,7 @@ export default class ScreenshotAccepterHeader extends Component {
48
50
  PREV_RETRY: this.handlePrevRetry,
49
51
  NEXT_RETRY: this.handleNextRetry,
50
52
  ACCEPT_SCREENSHOT: this.handleScreenshotAccept,
53
+ UNDO_SCREEN: this.handleScreenUndo,
51
54
  CLOSE_MODAL: this.props.onClose,
52
55
  IGNORE_META_UP: () => {},
53
56
  IGNORE_META_DOWN: () => {},
@@ -96,6 +99,12 @@ export default class ScreenshotAccepterHeader extends Component {
96
99
  onScreenshotAccept(imageId);
97
100
  }
98
101
 
102
+ handleScreenUndo = (event) => {
103
+ event.preventDefault();
104
+
105
+ this.props.onScreenshotUndo();
106
+ }
107
+
99
108
  render() {
100
109
  const {images, stateNameImageIds, retryIndex,
101
110
  showMeta, onClose, onRetryChange, onShowMeta,
@@ -158,6 +167,14 @@ export default class ScreenshotAccepterHeader extends Component {
158
167
  extendClassNames="screenshot-accepter__arrows-close-btn"
159
168
  handler={onClose}
160
169
  />
170
+ <ControlButton
171
+ label="⎌ Undo"
172
+ title="Revert last updated screenshot"
173
+ isDisabled={!acceptedImages}
174
+ isSuiteControl={true}
175
+ extendClassNames="screenshot-accepter__undo-btn"
176
+ handler={this.handleScreenUndo}
177
+ />
161
178
  <ProgressBar done={acceptedImages} total={totalImages}/>
162
179
  </div>
163
180
  </header>
@@ -3,16 +3,19 @@ import ReactDOM from 'react-dom';
3
3
  import {connect} from 'react-redux';
4
4
  import {bindActionCreators} from 'redux';
5
5
  import PropTypes from 'prop-types';
6
- import {isEmpty, isNumber, size, findIndex} from 'lodash';
6
+ import {isEmpty, isNumber, size, get, findIndex, last} from 'lodash';
7
7
 
8
8
  import * as actions from '../../../modules/actions';
9
9
  import ScreenshotAccepterHeader from './header';
10
10
  import ScreenshotAccepterMeta from './meta';
11
11
  import ScreenshotAccepterBody from './body';
12
12
  import {getAcceptableImagesByStateName} from '../../../modules/selectors/tree';
13
+ import {preloadImage} from '../../../modules/utils';
13
14
 
14
15
  import './style.css';
15
16
 
17
+ const PRELOAD_IMAGE_COUNT = 3;
18
+
16
19
  class ScreenshotAccepter extends Component {
17
20
  static propTypes = {
18
21
  image: PropTypes.shape({
@@ -35,6 +38,7 @@ class ScreenshotAccepter extends Component {
35
38
  const images = this._getActiveImages(activeImageIndex, stateNameImageIds);
36
39
  const retryIndex = findIndex(images, {id: image.id});
37
40
 
41
+ this.acceptedImages = [];
38
42
  this.delayedTestResults = [];
39
43
  this.state = {
40
44
  stateNameImageIds,
@@ -44,6 +48,10 @@ class ScreenshotAccepter extends Component {
44
48
  };
45
49
 
46
50
  this.totalImagesCount = size(imagesByStateName);
51
+
52
+ for (let i = 1; i <= PRELOAD_IMAGE_COUNT; i++) {
53
+ this._preloadAdjacentImages(i);
54
+ }
47
55
  }
48
56
 
49
57
  componentDidUpdate() {
@@ -58,9 +66,12 @@ class ScreenshotAccepter extends Component {
58
66
  const images = this._getActiveImages(activeImageIndex);
59
67
 
60
68
  this.setState({retryIndex: images.length - 1, activeImageIndex});
69
+ this._preloadAdjacentImages();
61
70
  }
62
71
 
63
72
  onScreenshotAccept = async (imageId) => {
73
+ const currentImages = this._getActiveImages();
74
+ const {stateName} = currentImages[0];
64
75
  const updatedData = await this.props.actions.screenshotAccepterAccept(imageId);
65
76
 
66
77
  if (updatedData === null) {
@@ -69,12 +80,22 @@ class ScreenshotAccepter extends Component {
69
80
 
70
81
  this.delayedTestResults = this.delayedTestResults.concat(updatedData);
71
82
 
72
- const stateNameIds = this.state.stateNameImageIds.filter(stateNameImageId => {
83
+ const updatedImagesData = get(updatedData, '[0].images', []);
84
+ const {id: updatedImageId} = updatedImagesData.find(img => img.stateName === stateName) || {};
85
+ const acceptedStateNameImageIdIndex = this.state.stateNameImageIds.findIndex((stateNameImageId) => {
73
86
  const currImages = this.props.imagesByStateName[stateNameImageId];
74
87
 
75
- return !currImages.some(img => img.id === imageId);
88
+ return currImages.some(img => img.id === imageId);
76
89
  });
77
90
 
91
+ this.acceptedImages.push({
92
+ stateNameImageId: this.state.stateNameImageIds[acceptedStateNameImageIdIndex],
93
+ ind: acceptedStateNameImageIdIndex,
94
+ imageId: updatedImageId
95
+ });
96
+
97
+ const stateNameIds = this.state.stateNameImageIds.filter((_, ind) => ind !== acceptedStateNameImageIdIndex);
98
+
78
99
  if (isEmpty(stateNameIds)) {
79
100
  return this.setState({
80
101
  activeImageIndex: null,
@@ -84,13 +105,41 @@ class ScreenshotAccepter extends Component {
84
105
  }
85
106
 
86
107
  const activeImageIndex = Math.min(this.state.activeImageIndex, stateNameIds.length - 1);
87
- const images = this._getActiveImages(activeImageIndex, stateNameIds);
108
+ const newImages = this._getActiveImages(activeImageIndex, stateNameIds);
88
109
 
89
110
  this.setState({
90
111
  activeImageIndex,
91
112
  stateNameImageIds: stateNameIds,
113
+ retryIndex: newImages.length - 1
114
+ });
115
+ this._preloadAdjacentImages();
116
+ }
117
+
118
+ onScreenshotUndo = async () => {
119
+ if (isEmpty(this.acceptedImages)) {
120
+ return;
121
+ }
122
+
123
+ const {stateNameImageIds} = this.state;
124
+ const {stateNameImageId, ind, imageId} = this.acceptedImages.pop();
125
+
126
+ const previousStateNameImageId = [
127
+ ...stateNameImageIds.slice(0, ind),
128
+ stateNameImageId,
129
+ ...stateNameImageIds.slice(ind)
130
+ ];
131
+ const images = this._getActiveImages(ind, previousStateNameImageId);
132
+
133
+ await this.props.actions.undoAcceptImage(imageId, {skipTreeUpdate: true});
134
+
135
+ this.delayedTestResults.pop();
136
+
137
+ this.setState({
138
+ activeImageIndex: ind,
139
+ stateNameImageIds: previousStateNameImageId,
92
140
  retryIndex: images.length - 1
93
141
  });
142
+ this._preloadAdjacentImages();
94
143
  }
95
144
 
96
145
  onShowMeta = () => {
@@ -114,6 +163,19 @@ class ScreenshotAccepter extends Component {
114
163
  : [];
115
164
  }
116
165
 
166
+ _preloadAdjacentImages(offset = PRELOAD_IMAGE_COUNT) {
167
+ const screensCount = size(this.state.stateNameImageIds);
168
+ const previosImagesIndex = (screensCount + this.state.activeImageIndex - offset) % screensCount;
169
+ const nextImagesIndex = (this.state.activeImageIndex + offset) % screensCount;
170
+
171
+ [previosImagesIndex, nextImagesIndex].filter(ind => ind >= 0).forEach(preloadingImagesIndex => {
172
+ const stateNameImageId = this.state.stateNameImageIds[preloadingImagesIndex];
173
+ const {expectedImg, actualImg, diffImg} = last(this.props.imagesByStateName[stateNameImageId]);
174
+
175
+ [expectedImg, actualImg, diffImg].filter(Boolean).forEach(({path}) => preloadImage(path));
176
+ });
177
+ }
178
+
117
179
  render() {
118
180
  const {retryIndex, stateNameImageIds, activeImageIndex, showMeta} = this.state;
119
181
  const images = this._getActiveImages();
@@ -134,6 +196,7 @@ class ScreenshotAccepter extends Component {
134
196
  onRetryChange={this.onRetryChange}
135
197
  onActiveImageChange={this.onActiveImageChange}
136
198
  onScreenshotAccept={this.onScreenshotAccept}
199
+ onScreenshotUndo={this.onScreenshotUndo}
137
200
  onShowMeta={this.onShowMeta}
138
201
  />
139
202
  <ScreenshotAccepterMeta