UNPKG

1.41 kBJavaScriptView Raw
1import differ from 'deep-diff';
2
3// https://github.com/flitbit/diff#differences
4const dictionary = {
5 'E': {
6 color: `#2196F3`,
7 text: `CHANGED:`,
8 },
9 'N': {
10 color: `#4CAF50`,
11 text: `ADDED:`,
12 },
13 'D': {
14 color: `#F44336`,
15 text: `DELETED:`,
16 },
17 'A': {
18 color: `#2196F3`,
19 text: `ARRAY:`,
20 },
21};
22
23function style(kind) {
24 return `color: ${dictionary[kind].color}; font-weight: bold`;
25}
26
27function render(diff) {
28 const { kind, path, lhs, rhs, index, item } = diff;
29
30 switch (kind) {
31 case `E`:
32 return [path.join(`.`), lhs, `→`, rhs];
33 case `N`:
34 return [path.join(`.`), rhs];
35 case `D`:
36 return [path.join(`.`)];
37 case `A`:
38 return [`${path.join(`.`)}[${index}]`, item];
39 default:
40 return [];
41 }
42}
43
44export default function diffLogger(prevState, newState, logger, isCollapsed) {
45 const diff = differ(prevState, newState);
46
47 try {
48 if (isCollapsed) {
49 logger.groupCollapsed(`diff`);
50 } else {
51 logger.group(`diff`);
52 }
53 } catch (e) {
54 logger.log(`diff`);
55 }
56
57 if (diff) {
58 diff.forEach((elem) => {
59 const { kind } = elem;
60 const output = render(elem);
61
62 logger.log(`%c ${dictionary[kind].text}`, style(kind), ...output);
63 });
64 } else {
65 logger.log(`—— no diff ——`);
66 }
67
68 try {
69 logger.groupEnd();
70 } catch (e) {
71 logger.log(`—— diff end —— `);
72 }
73}