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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import { withStorageKey } from '@automattic/state-utils';
import {
	filter,
	orderBy,
	has,
	map,
	reject,
	isEqual,
	get,
	includes,
	omit,
	startsWith,
} from 'lodash';
import {
	COMMENT_COUNTS_UPDATE,
	COMMENTS_CHANGE_STATUS,
	COMMENTS_EDIT,
	COMMENTS_EMPTY_SUCCESS,
	COMMENTS_RECEIVE,
	COMMENTS_DELETE,
	COMMENTS_RECEIVE_ERROR,
	COMMENTS_COUNT_INCREMENT,
	COMMENTS_COUNT_RECEIVE,
	COMMENTS_LIKE,
	COMMENTS_UPDATES_RECEIVE,
	COMMENTS_TOGGLE_INLINE_EXPANDED,
	COMMENTS_UNLIKE,
	COMMENTS_WRITE_ERROR,
	COMMENTS_SET_ACTIVE_REPLY,
} from 'calypso/state/action-types';
import { READER_EXPAND_COMMENTS } from 'calypso/state/reader/action-types';
import { combineReducers } from 'calypso/state/utils';
import {
	PLACEHOLDER_STATE,
	NUMBER_OF_COMMENTS_PER_FETCH,
	POST_COMMENT_DISPLAY_TYPES,
} from './constants';
import ui from './ui/reducer';
import { getStateKey, getErrorKey, commentHasLink, getCommentDate } from './utils';

const unionById = ( a = [], b = [] ) => [
	...a,
	...b.filter( ( bc ) => ! a.some( ( ac ) => ac.ID === bc.ID ) ),
];

const isCommentManagementEdit = ( newProperties ) =>
	has( newProperties, 'commentContent' ) &&
	has( newProperties, 'authorDisplayName' ) &&
	has( newProperties, 'authorUrl' );

const updateComment = ( commentId, newProperties ) => ( comment ) => {
	if ( comment.ID !== commentId ) {
		return comment;
	}
	const updateLikeCount =
		has( newProperties, 'i_like' ) && typeof newProperties.like_count === 'undefined';

	// Comment Management allows for modifying nested fields, such as `author.name` and `author.url`.
	// Though, there is no direct match between the GET response (which feeds the state) and the POST request.
	// This ternary matches and formats the updated fields sent by Comment Management's Edit form,
	// in order to optimistically update the state without temporary loss of information.
	const newComment = isCommentManagementEdit( newProperties )
		? {
				...comment,
				author: {
					...comment.author,
					name: newProperties.authorDisplayName,
					url: newProperties.authorUrl,
				},
				content: newProperties.commentContent,
		  }
		: { ...comment, ...newProperties };

	return {
		...newComment,
		...( updateLikeCount && {
			like_count: newProperties.i_like ? comment.like_count + 1 : comment.like_count - 1,
		} ),
	};
};

/**
 * Comments items reducer, stores a comments items Immutable.List per siteId, postId
 * @param {Object} state redux state
 * @param {Object} action redux action
 * @returns {Object} new redux state
 */
export function items( state = {}, action ) {
	const { type, siteId, postId, commentId, like_count } = action;

	// cannot construct stateKey without both
	let stateKey = null;
	if ( siteId && postId ) {
		stateKey = getStateKey( siteId, postId );
	}

	// We need a stateKey unless we're emptying comments
	if ( ! stateKey && type !== 'COMMENTS_EMPTY_SUCCESS' ) {
		return state;
	}

	switch ( type ) {
		case COMMENTS_CHANGE_STATUS: {
			const { status } = action;
			return {
				...state,
				[ stateKey ]: map( state[ stateKey ], updateComment( commentId, { status } ) ),
			};
		}
		case COMMENTS_EDIT: {
			const { comment } = action;
			return {
				...state,
				[ stateKey ]: map( state[ stateKey ], updateComment( commentId, comment ) ),
			};
		}
		case COMMENTS_RECEIVE: {
			const { skipSort } = action;
			const comments = map( action.comments, ( _comment ) => ( {
				..._comment,
				contiguous: ! action.commentById,
				has_link: commentHasLink( _comment.content, _comment.has_link ),
			} ) );
			const allComments = unionById( state[ stateKey ], comments );
			return {
				...state,
				[ stateKey ]: ! skipSort ? orderBy( allComments, getCommentDate, [ 'desc' ] ) : allComments,
			};
		}
		case COMMENTS_DELETE:
			return {
				...state,
				[ stateKey ]: reject( state[ stateKey ], { ID: commentId } ),
			};
		case COMMENTS_LIKE:
			return {
				...state,
				[ stateKey ]: map(
					state[ stateKey ],
					updateComment( commentId, { i_like: true, like_count } )
				),
			};
		case COMMENTS_UNLIKE:
			return {
				...state,
				[ stateKey ]: map(
					state[ stateKey ],
					updateComment( commentId, { i_like: false, like_count } )
				),
			};
		case COMMENTS_RECEIVE_ERROR:
		case COMMENTS_WRITE_ERROR: {
			const { error, errorType } = action;
			return {
				...state,
				[ stateKey ]: map(
					state[ stateKey ],
					updateComment( commentId, {
						placeholderState: PLACEHOLDER_STATE.ERROR,
						placeholderError: error,
						placeholderErrorType: errorType,
					} )
				),
			};
		}
		// When we've emptied spam or trash, we don't know the post ID
		// - just the site ID and comment ID
		case COMMENTS_EMPTY_SUCCESS: {
			const { commentIds } = action;

			let newState = { ...state };
			Object.entries( state ).map( ( [ key, comments ] ) => {
				newState = {
					...newState,
					[ key ]: comments.filter( ( comment ) => ! commentIds.includes( comment.ID ) ),
				};
			} );

			return newState;
		}
	}

	return state;
}

/**
 * Comments pending items reducer, stores new comments per siteId and postId
 * @param {Object} state redux state
 * @param {Object} action redux action
 * @returns {Object} new redux state
 */
export function pendingItems( state = {}, action ) {
	const { type, siteId, postId } = action;

	// cannot construct stateKey without both
	if ( ! siteId || ! postId ) {
		return state;
	}

	const stateKey = getStateKey( siteId, postId );

	switch ( type ) {
		case COMMENTS_UPDATES_RECEIVE: {
			const comments = map( action.comments, ( _comment ) => ( {
				..._comment,
				contiguous: ! action.commentById,
				has_link: commentHasLink( _comment.content, _comment.has_link ),
			} ) );
			const allComments = unionById( state[ stateKey ], comments );
			return {
				...state,
				[ stateKey ]: orderBy( allComments, getCommentDate, [ 'desc' ] ),
			};
		}

		case COMMENTS_RECEIVE: {
			const receivedCommentIds = map( action.comments, 'ID' );
			return {
				...state,
				[ stateKey ]: filter(
					state[ stateKey ],
					( _comment ) => ! includes( receivedCommentIds, _comment.ID )
				),
			};
		}
	}

	return state;
}

export const fetchStatusInitialState = {
	before: true,
	after: true,
	hasReceivedBefore: false,
	hasReceivedAfter: false,
};

const isValidExpansionsAction = ( action ) => {
	const { siteId, postId, commentIds, displayType } = action.payload;
	return (
		siteId &&
		postId &&
		Array.isArray( commentIds ) &&
		includes( Object.values( POST_COMMENT_DISPLAY_TYPES ), displayType )
	);
};

const expansionValue = ( type ) => {
	const { full, excerpt, singleLine } = POST_COMMENT_DISPLAY_TYPES;
	switch ( type ) {
		case full:
			return 3;
		case excerpt:
			return 2;
		case singleLine:
			return 1;
	}
};

export const expansions = ( state = {}, action ) => {
	switch ( action.type ) {
		case READER_EXPAND_COMMENTS: {
			const { siteId, postId, commentIds, displayType } = action.payload;

			if ( ! isValidExpansionsAction( action ) ) {
				return state;
			}

			const stateKey = getStateKey( siteId, postId );
			const currentExpansions = state[ stateKey ] || {};

			// generate object of { [ commentId ]: displayType }
			const newVal = Object.fromEntries(
				commentIds.map( ( id ) => {
					if (
						! has( currentExpansions, id ) ||
						expansionValue( displayType ) > expansionValue( currentExpansions[ id ] )
					) {
						return [ id, displayType ];
					}
					return [ id, currentExpansions[ id ] ];
				} )
			);

			return {
				...state,
				[ stateKey ]: Object.assign( {}, state[ stateKey ], newVal ),
			};
		}
	}

	return state;
};

/**
 * Stores whether or not there are more comments, and in which directions, for a particular post.
 * Also includes whether or not a before/after has ever been queried
 * Example state:
 * {
 * [ siteId-postId ]: {
 * before: bool,
 * after: bool,
 * hasReceivedBefore: bool,
 * hasReceivedAfter: bool,
 * }
 * }
 * @param {Object} state redux state
 * @param {Object} action redux action
 * @returns {Object} new redux state
 */
export const fetchStatus = ( state = {}, action ) => {
	switch ( action.type ) {
		case COMMENTS_RECEIVE: {
			const { siteId, postId, direction, commentById } = action;
			const stateKey = getStateKey( siteId, postId );

			// we can't deduce anything from a commentById fetch.
			if ( commentById ) {
				return state;
			}

			const hasReceivedDirection =
				direction === 'before' ? 'hasReceivedBefore' : 'hasReceivedAfter';

			const nextState = {
				...get( state, stateKey, fetchStatusInitialState ),
				[ direction ]: action.comments.length === NUMBER_OF_COMMENTS_PER_FETCH,
				[ hasReceivedDirection ]: true,
			};

			return isEqual( state[ stateKey ], nextState )
				? state
				: { ...state, [ stateKey ]: nextState };
		}
	}

	return state;
};

/**
 * Stores latest comments count for post we've seen from the server
 * @param {Object} state redux state, prev totalCommentsCount
 * @param {Object} action redux action
 * @returns {Object} new redux state
 */
export const totalCommentsCount = ( state = {}, action ) => {
	switch ( action.type ) {
		case COMMENTS_COUNT_RECEIVE: {
			const key = getStateKey( action.siteId, action.postId );
			return { ...state, [ key ]: action.totalCommentsCount };
		}
		case COMMENTS_COUNT_INCREMENT: {
			const key = getStateKey( action.siteId, action.postId );
			return { ...state, [ key ]: state[ key ] + 1 };
		}
	}

	return state;
};

/**
 * Houses errors by `siteId-commentId`
 * @param {Object} state redux state
 * @param {Object} action redux action
 * @returns {Object} new redux state
 */
export const errors = ( state = {}, action ) => {
	switch ( action.type ) {
		case COMMENTS_RECEIVE_ERROR: {
			const { siteId, commentId } = action;
			const key = getErrorKey( siteId, commentId );

			if ( state[ key ] ) {
				return state;
			}

			return {
				...state,
				[ key ]: { error: true },
			};
		}
		case COMMENTS_WRITE_ERROR: {
			const { siteId, commentId } = action;
			const key = getErrorKey( siteId, commentId );

			if ( state[ key ] ) {
				return state;
			}

			return {
				...state,
				[ key ]: { error: true },
			};
		}
	}

	return state;
};

/**
 * Stores the active reply comment for a given siteId and postId
 * @param {Object} state redux state
 * @param {Object} action redux action
 * @returns {Object} new redux state
 */
export const activeReplies = ( state = {}, action ) => {
	switch ( action.type ) {
		case COMMENTS_SET_ACTIVE_REPLY: {
			const { siteId, postId, commentId } = action.payload;
			const stateKey = getStateKey( siteId, postId );

			// If commentId is null, remove the key from the state map entirely
			if ( commentId === null ) {
				return omit( state, stateKey );
			}

			return { ...state, [ stateKey ]: commentId };
		}
		case COMMENTS_WRITE_ERROR: {
			const { siteId, postId, parentCommentId } = action;
			const stateKey = getStateKey( siteId, postId );
			return { ...state, [ stateKey ]: parentCommentId };
		}
	}

	return state;
};

function updateCount( counts, rawStatus, value = 1 ) {
	const status = rawStatus === 'unapproved' ? 'pending' : rawStatus;
	if ( ! counts || ! Number.isInteger( counts[ status ] ) ) {
		return undefined;
	}
	const newCounts = {
		...counts,
		[ status ]: counts[ status ] + value,
	};
	const { pending, approved, spam } = newCounts;
	return {
		...newCounts,
		all: pending + approved,
		totalComments: pending + approved + spam,
	};
}

export const counts = ( state = {}, action ) => {
	switch ( action.type ) {
		case COMMENT_COUNTS_UPDATE: {
			const { siteId, postId, ...commentCounts } = omit( action, 'type' );
			if ( ! siteId ) {
				return state;
			}
			const keyName = siteId && postId ? postId : 'site';
			const siteCounts = {
				[ siteId ]: Object.assign( {}, state[ siteId ] || {}, {
					[ keyName ]: commentCounts,
				} ),
			};
			return Object.assign( {}, state, siteCounts );
		}
		case COMMENTS_CHANGE_STATUS: {
			const { siteId, postId = -1, status } = action;
			const previousStatus = get( action, 'meta.comment.previousStatus' );
			if ( ! siteId || ! status || ! state[ siteId ] || ! previousStatus ) {
				return state;
			}

			const { site: siteCounts, [ postId ]: postCounts } = state[ siteId ];

			//increase new status counts by one and decrement previous status counts by 1
			const newSiteCounts = updateCount( updateCount( siteCounts, status, 1 ), previousStatus, -1 );
			const newPostCounts = updateCount( updateCount( postCounts, status, 1 ), previousStatus, -1 );

			const newTotalSiteCounts = Object.assign(
				{},
				state[ siteId ],
				newSiteCounts && { site: newSiteCounts },
				newPostCounts && { [ postId ]: newPostCounts }
			);
			return Object.assign( {}, state, { [ siteId ]: newTotalSiteCounts } );
		}
		case COMMENTS_DELETE: {
			const { siteId, postId = -1, commentId } = action;
			if ( commentId && startsWith( commentId, 'placeholder' ) ) {
				return state;
			}
			const previousStatus = get( action, 'meta.comment.previousStatus' );

			if ( ! siteId || ! state[ siteId ] || ! previousStatus ) {
				return state;
			}
			const { site: siteCounts, [ postId ]: postCounts } = state[ siteId ];

			const newSiteCounts = updateCount( siteCounts, previousStatus, -1 );
			const newPostCounts = updateCount( postCounts, previousStatus, -1 );

			const newTotalSiteCounts = Object.assign(
				{},
				state[ siteId ],
				newSiteCounts && { site: newSiteCounts },
				newPostCounts && { [ postId ]: newPostCounts }
			);
			return Object.assign( {}, state, { [ siteId ]: newTotalSiteCounts } );
		}
		case COMMENTS_RECEIVE: {
			if ( get( action, 'meta.comment.context' ) !== 'add' ) {
				return state;
			}
			const { siteId, postId = -1 } = action;
			if ( ! siteId || ! state[ siteId ] ) {
				return state;
			}
			const { site: siteCounts, [ postId ]: postCounts } = state[ siteId ];
			const status = get( action, [ 'comments', 0, 'status' ] );

			const newSiteCounts = updateCount( siteCounts, status, 1 );
			const newPostCounts = updateCount( postCounts, status, 1 );

			const newTotalSiteCounts = Object.assign(
				{},
				state[ siteId ],
				newSiteCounts && { site: newSiteCounts },
				newPostCounts && { [ postId ]: newPostCounts }
			);
			return Object.assign( {}, state, { [ siteId ]: newTotalSiteCounts } );
		}
		case COMMENTS_EMPTY_SUCCESS: {
			const { siteId, status, commentIds } = action;

			if ( ! siteId || ! state[ siteId ] || ! status ) {
				return state;
			}
			const { site: siteCounts } = state[ siteId ];

			const emptiedCommentsCount = commentIds?.length || 0;
			const newSiteCounts = updateCount( siteCounts, status, -emptiedCommentsCount );

			// Post counts can't be updated here because we don't know the post ID.

			const newTotalSiteCounts = Object.assign(
				{},
				state[ siteId ],
				newSiteCounts && { site: newSiteCounts }
			);
			return { ...state, ...{ [ siteId ]: newTotalSiteCounts } };
		}
	}

	return state;
};

export const inlineExpansion = ( state = {}, action ) => {
	switch ( action.type ) {
		case COMMENTS_TOGGLE_INLINE_EXPANDED: {
			const { siteId, postId, streamKey } = action.payload;
			const currentValue = state[ streamKey ]?.[ siteId ]?.[ postId ];
			const siteLevelData = {
				...( state[ streamKey ]?.[ siteId ] || {} ),
				...{ [ postId ]: ! currentValue },
			};
			const streamLevelData = {
				...( state[ streamKey ] || {} ),
				...{ [ siteId ]: siteLevelData },
			};
			return { ...state, ...{ [ streamKey ]: streamLevelData } };
		}
	}
	return state;
};

const combinedReducer = combineReducers( {
	counts,
	items,
	pendingItems,
	fetchStatus,
	errors,
	expansions,
	totalCommentsCount,
	activeReplies,
	ui,
	inlineExpansion,
} );
const commentsReducer = withStorageKey( 'comments', combinedReducer );
export default commentsReducer;