File size: 26,227 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import { Button, Gridicon, SegmentedControl } from '@automattic/components';
import clsx from 'clsx';
import { translate } from 'i18n-calypso';
import { get, size, delay, pickBy } from 'lodash';
import PropTypes from 'prop-types';
import { Component, createRef } from 'react';
import { connect } from 'react-redux';
import ConversationFollowButton from 'calypso/blocks/conversation-follow-button';
import { shouldShowConversationFollowButton } from 'calypso/blocks/conversation-follow-button/helper';
import ReaderFollowConversationIcon from 'calypso/reader/components/icons/follow-conversation-icon';
import ReaderFollowingConversationIcon from 'calypso/reader/components/icons/following-conversation-icon';
import { recordAction, recordGaEvent, recordTrackForPost } from 'calypso/reader/stats';
import {
	requestPostComments,
	requestComment,
	setActiveReply,
	toggleInlineCommentsExpanded,
} from 'calypso/state/comments/actions';
import { NUMBER_OF_COMMENTS_PER_FETCH } from 'calypso/state/comments/constants';
import {
	commentsFetchingStatus,
	getActiveReplyCommentId,
	getCommentById,
	getPostCommentsTree,
	getInlineCommentsExpandedState,
} from 'calypso/state/comments/selectors';
import { getCurrentUserId } from 'calypso/state/current-user/selectors';
import { recordReaderTracksEvent } from 'calypso/state/reader/analytics/actions';
import { canCurrentUser } from 'calypso/state/selectors/can-current-user';
import CommentCount from './comment-count';
import PostCommentFormRoot from './form-root';
import PostComment from './post-comment';

import './post-comment-list.scss';

/**
 * PostCommentList displays a list of comments for a post.
 * It has the capability of either starting from the latest comment for a post,
 * or it may begin from any commentId within the post by specifying a commentId.
 *
 * Depending on where the list starts, there is slightly different behavior:
 * 1. from the last comments:
 *    this is the simplest case. Initially onMount we request the latest comments
 *    and only display a subset of them.  When the user clicks "Show More" we load more comments
 *
 * 2. from a specific commentId:
 *    this is activated by specifying the commentId prop. onMount we request the specific comment and then
 *    also a page before it / a page after it.  Then we scroll down to the specific comment.
 *    This also activates a "Show More" button at the end of the comment list instead of just at the top
 *
 */

class PostCommentList extends Component {
	static propTypes = {
		post: PropTypes.shape( {
			ID: PropTypes.number.isRequired,
			site_ID: PropTypes.number.isRequired,
		} ).isRequired,
		pageSize: PropTypes.number,
		initialSize: PropTypes.number,
		showCommentCount: PropTypes.bool,
		startingCommentId: PropTypes.number,
		commentCount: PropTypes.number,
		maxDepth: PropTypes.number,
		showNestingReplyArrow: PropTypes.bool,
		showConversationFollowButton: PropTypes.bool,
		commentsFilter: PropTypes.string,
		followSource: PropTypes.string,
		fixedHeaderHeight: PropTypes.number,
		streamKey: PropTypes.string,

		// To show only the most recent comment by default, and allow expanding to see the longer
		// list.
		expandableView: PropTypes.bool,
		openPostPageAtComments: PropTypes.func,

		// To display comments with a different status but not fetch them
		// e.g. Reader full post view showing unapproved comments made to a moderated site
		commentsFilterDisplay: PropTypes.string,

		// connect()ed props:
		commentsTree: PropTypes.object,
		requestPostComments: PropTypes.func.isRequired,
		requestComment: PropTypes.func.isRequired,
		shouldHighlightNew: PropTypes.bool,
	};

	static defaultProps = {
		shouldHighlightNew: false,
		pageSize: NUMBER_OF_COMMENTS_PER_FETCH,
		initialSize: NUMBER_OF_COMMENTS_PER_FETCH,
		showCommentCount: true,
		maxDepth: Infinity,
		showNestingReplyArrow: false,
		showConversationFollowButton: false,
		expandableView: false,
	};

	constructor( props ) {
		super( props );
		this.listRef = createRef();
	}

	state = {
		amountOfCommentsToTake: this.props.initialSize,
		commentText: '',
		showExpandWhenOnlyComments: false,
	};

	shouldFetchInitialComment = () => {
		const { startingCommentId, initialComment } = this.props;
		return !! ( startingCommentId && ! initialComment );
	};

	shouldFetchInitialPages = () => {
		const { startingCommentId, commentsTree } = this.props;

		return (
			startingCommentId &&
			commentsTree[ startingCommentId ] &&
			this.props.commentsTree[ startingCommentId ] &&
			! this.alreadyLoadedInitialSet
		);
	};

	shouldNormalFetchAfterPropsChange = () => {
		// this next check essentially looks out for whether we've ever requested comments for the post
		if (
			this.props.commentsFetchingStatus.haveEarlierCommentsToFetch &&
			this.props.commentsFetchingStatus.haveLaterCommentsToFetch
		) {
			return true;
		}

		const currentSiteId = get( this.props, 'post.site_ID' );
		const currentPostId = get( this.props, 'post.ID' );
		const currentCommentsFilter = this.props.commentsFilter;
		const currentInitialComment = this.props.initialComment;

		const nextSiteId = get( this.props, 'post.site_ID' );
		const nextPostId = get( this.props, 'post.ID' );
		const nextCommentsFilter = this.props.commentsFilter;
		const nextInitialComment = this.props.initialComment;

		const propsExist = nextSiteId && nextPostId && nextCommentsFilter;
		const propChanged =
			currentSiteId !== nextSiteId ||
			currentPostId !== nextPostId ||
			currentCommentsFilter !== nextCommentsFilter;

		/**
		 * This covers two cases where fetching by commentId fails and we should fetch as if it werent specified:
		 *  1. the comment specified (commentId) exists for the site but is for a different postId
		 *  2. the commentId does not exist for the site
		 */
		const commentIdBail =
			currentInitialComment !== nextInitialComment &&
			nextInitialComment &&
			( nextInitialComment.error ||
				( nextInitialComment.post && nextInitialComment.post.ID !== nextPostId ) );

		return ( propsExist && propChanged ) || commentIdBail;
	};

	initialFetches = () => {
		const { postId, siteId, commentsFilter: status } = this.props;

		if ( this.shouldFetchInitialComment() ) {
			// there is an edgecase the initialComment can change while on the same post
			// in this case we can't just load the exact comment in question because
			// we could create a gap in the list.
			if ( this.props.commentsTree ) {
				// view earlier...
				this.viewEarlierCommentsHandler();
			} else {
				this.props.requestComment( { siteId, commentId: this.props.startingCommentId } );
			}
		} else if ( this.shouldFetchInitialPages() ) {
			this.viewEarlierCommentsHandler();
			this.viewLaterCommentsHandler();
			this.alreadyLoadedInitialSet = true;
		} else if ( this.shouldNormalFetchAfterPropsChange() ) {
			this.props.requestPostComments( { siteId, postId, status } );
		}
	};

	componentDidMount() {
		this.initialFetches();
		this.scrollWhenDOMReady();
		this.resetActiveReplyComment();
		this.checkForClampedComments();
	}

	componentDidUpdate( prevProps, prevState ) {
		// If only the state is changing, do nothing. (Avoids setState loops.)
		if ( prevState !== this.state && prevProps === this.props ) {
			return;
		}
		this.initialFetches();
		if (
			prevProps.siteId !== this.props.siteId ||
			prevProps.postId !== this.props.postId ||
			prevProps.startingCommentId !== this.props.startingCommentId
		) {
			this.hasScrolledToComment = false;
			this.scrollWhenDOMReady();
		}

		if (
			// The view is not expanded and has just been collapsed or the amount of comments have changed.
			// Note more safety conditions are contained generally in checkForClampedComments.
			! this.props.isExpanded &&
			( prevProps.isExpanded ||
				Object.keys( prevProps.commentsTree ).length !==
					Object.keys( this.props.commentsTree ).length )
		) {
			this.checkForClampedComments();
		}
	}

	checkForClampedComments = () => {
		if (
			// This check isnt necessary if we arent in expandableView or are expanded.
			! this.props.expandableView ||
			this.props.isExpanded ||
			// Bail early if there is no listRef to query.
			! this.listRef.current ||
			// Bail early if this state is already flagged, avoids setState loops in methods like
			// componentDidUpdate.
			this.state.showExpandWhenOnlyComments
		) {
			return;
		}

		// Query selector ALL since we might be showing the readers reply as well.
		const commentContentEles = this.listRef.current.querySelectorAll(
			'.comments__comment-content'
		);
		let isClampedComment = false;

		// Check if either the comment or reply that might be shown are line clamped.
		commentContentEles.forEach( ( comment ) => {
			if ( comment.scrollHeight > comment.clientHeight ) {
				isClampedComment = true;
			}
		} );

		// There is no need to set false, as it already is false if this is running.
		if ( isClampedComment ) {
			this.setState( { showExpandWhenOnlyComments: true } );
		}
	};

	commentIsOnDOM = ( commentId ) => !! window.document.getElementById( `comment-${ commentId }` );

	scrollWhenDOMReady = () => {
		if ( this.props.startingCommentId && ! this.hasScrolledToComment ) {
			if ( this.commentIsOnDOM( this.props.startingCommentId ) ) {
				delay( () => this.scrollToComment(), 50 );
			}
			delay( this.scrollWhenDOMReady, 100 );
		}
	};

	renderComment = ( commentId, commentsTree ) => {
		if ( ! commentId ) {
			return null;
		}

		return (
			<PostComment
				post={ this.props.post }
				commentsTree={ commentsTree }
				commentId={ commentId }
				key={ commentId }
				activeReplyCommentId={ this.props.activeReplyCommentId }
				onReplyClick={ this.onReplyClick }
				onReplyCancel={ this.onReplyCancel }
				commentText={ this.state.commentText }
				onUpdateCommentText={ this.onUpdateCommentText }
				onCommentSubmit={ this.resetActiveReplyComment }
				depth={ 0 }
				maxDepth={ this.props.maxDepth }
				showNestingReplyArrow={ this.props.showNestingReplyArrow }
				shouldHighlightNew={ this.props.shouldHighlightNew }
				isInlineComment={ this.props.expandableView }
			/>
		);
	};

	renderCommentManageLink = () => {
		const { siteId, postId } = this.props;

		if ( ! siteId || ! postId ) {
			return null;
		}

		return (
			<Button
				className="comments__manage-comments-button"
				href={ `/comments/all/${ siteId }/${ postId }` }
				borderless
			>
				<Gridicon icon="chat" />
				<span>{ translate( 'Manage comments' ) }</span>
			</Button>
		);
	};

	onReplyClick = ( commentId ) => {
		this.setActiveReplyComment( commentId );
		recordAction( 'comment_reply_click' );
		recordGaEvent( 'Clicked Reply to Comment' );
		this.props.recordReaderTracksEvent(
			'calypso_reader_comment_reply_click',
			{
				comment_id: commentId,
				is_inline_comment: this.props.expandableView,
			},
			{ post: this.props.post }
		);
	};

	onReplyCancel = () => {
		this.setState( { commentText: null } );
		recordAction( 'comment_reply_cancel_click' );
		recordGaEvent( 'Clicked Cancel Reply to Comment' );
		this.props.recordReaderTracksEvent(
			'calypso_reader_comment_reply_cancel_click',
			{
				comment_id: this.props.activeReplyCommentId,
				is_inline_comment: this.props.expandableView,
			},
			{ post: this.props.post }
		);
		this.resetActiveReplyComment();
	};

	onOpenPostPageAtComments = () => {
		if ( ! this.props.openPostPageAtComments ) {
			return;
		}
		return this.props.openPostPageAtComments();
	};

	onUpdateCommentText = ( commentText ) => {
		this.setState( { commentText: commentText } );
	};

	setActiveReplyComment = ( commentId ) => {
		const siteId = get( this.props, 'post.site_ID' );
		const postId = get( this.props, 'post.ID' );

		if ( ! siteId || ! postId ) {
			return;
		}

		this.props.setActiveReply( {
			siteId,
			postId,
			commentId,
		} );
	};

	resetActiveReplyComment = () => {
		this.setActiveReplyComment( null );
	};

	toggleExpanded = ( ev ) => {
		if ( this.props.expandableView ) {
			ev.stopPropagation();

			if ( ! this.props.isExpanded ) {
				recordAction( 'click_inline_comments_expand' );
				recordGaEvent( 'Clicked Inline Comments Expand' );
				recordTrackForPost( 'calypso_reader_inline_comments_expand_click', this.props.post );
			} else {
				this.maybeScrollToListTop();
			}

			this.props.toggleInlineCommentsExpanded( {
				streamKey: this.props.streamKey,
				siteId: this.props.siteId,
				postId: this.props.postId,
			} );
		}
	};

	maybeScrollToListTop = () => {
		if ( this.listRef.current ) {
			const listEle = this.listRef.current;
			const rect = listEle.getBoundingClientRect();
			const visualCutoff = this.props.fixedHeaderHeight || 0;
			if ( rect.top < visualCutoff ) {
				listEle.scrollIntoView( true );
				window.scrollBy( 0, -1 * visualCutoff );
			}
		}
	};

	renderCommentsList = (
		commentIds,
		displayedCommentsCount,
		actualCommentsCount,
		// In many cases commentsTreeToShow === commentsTreeAvailable. For inline comments in
		// collapsed view: commentsTreeToShow represents the tree shown in the collapsed view, while
		// commentsTreeAvailable represents the comments tree available for expanded view.
		commentsTreeToShow,
		commentsTreeAvailable
	) => {
		// Comments in trees may be less than actualCommentCount since we may filter pingbacks out of
		// the tree. We need to use commentsTreeAvailable to determine whether to show
		// expand/collapse toggle for inline comments, but actualCommentsCount to determine whether
		// to show the link to view all comments (including pingbacks) on the post page.
		const shouldShowViewMoreToggle =
			this.props.expandableView &&
			( displayedCommentsCount < this.getCommentsCount( commentsTreeAvailable.children ) ||
				this.props.isExpanded );
		const shouldShowLinkToFullPost =
			this.props.expandableView &&
			( this.props.isExpanded || ! shouldShowViewMoreToggle ) &&
			displayedCommentsCount < actualCommentsCount;

		const viewMoreText =
			! shouldShowViewMoreToggle && this.state.showExpandWhenOnlyComments
				? translate( 'Show more' )
				: translate( 'Show more comments' );

		let viewFewerText = translate( 'Show fewer comments' );
		if ( this.props.isExpanded ) {
			const { displayedCommentsCount: collapsedDisplayedCommentsCount } =
				this.getDisplayedCollapsedInlineComments( commentsTreeToShow );

			// If collapsing will not reduce the number of comments shown (only line-clamp them
			// visually), display 'View less' instead of 'View fewer comments'.
			if ( displayedCommentsCount === collapsedDisplayedCommentsCount ) {
				viewFewerText = translate( 'Show less' );
			}
		}

		return (
			<>
				<ol className="comments__list is-root">
					{ commentIds
						// Reverse comment list so that newest comments are rendered first.
						?.reverse()
						.map( ( commentId ) => this.renderComment( commentId, commentsTreeToShow ) ) }
				</ol>
				{ ( shouldShowViewMoreToggle || this.state.showExpandWhenOnlyComments ) && (
					<Button
						compact
						borderless
						className="comments__toggle-expand"
						onClick={ this.toggleExpanded }
					>
						{ this.props.isExpanded ? viewFewerText : viewMoreText }
					</Button>
				) }
				{ shouldShowLinkToFullPost && (
					<Button
						compact
						borderless
						className="comments__open-post"
						onClick={ this.onOpenPostPageAtComments }
					>
						{ shouldShowViewMoreToggle && '• ' }
						{ translate( 'View more comments on the full post' ) }
					</Button>
				) }
			</>
		);
	};

	scrollToComment = () => {
		const comment = window.document.getElementById( window.location.hash.substring( 1 ) );
		if ( ! comment ) {
			return;
		}
		comment.scrollIntoView();
		window.scrollBy( 0, -50 );
		this.hasScrolledToComment = true;
	};

	getCommentsCount = ( commentIds ) => {
		// we always count prevSum, children sum, and +1 for the current processed comment
		return commentIds.reduce(
			( prevSum, commentId ) =>
				prevSum +
				this.getCommentsCount( get( this.props.commentsTree, [ commentId, 'children' ] ) ) +
				1,
			0
		);
	};

	/**
	 * Gets comments for display
	 * @param {Array<number>} commentIds The top level commentIds to take from
	 * @param {number} numberToTake How many top level comments to take
	 * @returns {Object} that has the displayed comments + total displayed count including children
	 */
	getDisplayedComments = ( commentIds, numberToTake ) => {
		if ( ! commentIds ) {
			return null;
		}

		const displayedComments = numberToTake ? commentIds.slice( numberToTake * -1 ) : [];

		return {
			displayedComments,
			displayedCommentsCount: this.getCommentsCount( displayedComments ),
		};
	};

	viewEarlierCommentsHandler = () => {
		const direction = this.props.commentsFetchingStatus.haveEarlierCommentsToFetch
			? 'before'
			: 'after';
		this.loadMoreCommentsHandler( direction );
	};

	viewLaterCommentsHandler = () => {
		const direction = this.props.commentsFetchingStatus.haveLaterCommentsToFetch
			? 'after'
			: 'before';
		this.loadMoreCommentsHandler( direction );
	};

	loadMoreCommentsHandler = ( direction ) => {
		const {
			post: { ID: postId, site_ID: siteId },
			commentsFilter: status,
		} = this.props;
		const amountOfCommentsToTake = this.state.amountOfCommentsToTake + this.props.pageSize;

		this.setState( { amountOfCommentsToTake } );
		this.props.requestPostComments( { siteId, postId, status, direction } );
	};

	handleFilterClick = ( commentsFilter ) => () => this.props.onFilterChange( commentsFilter );

	getDisplayedCollapsedInlineComments = ( commentsTree ) => {
		// Only take the most recent comment.
		const lastCommentArr = commentsTree.children.slice( -1 );
		const lastComment = lastCommentArr[ 0 ];

		if ( ! lastComment ) {
			return {
				displayedComments: [],
				displayedCommentsCount: 0,
				commentsTreeToUse: commentsTree,
			};
		}

		// Setup a new comment tree to customize replies rendered.
		const newCommentTree = { children: lastCommentArr };
		newCommentTree[ lastComment ] = {
			data: commentsTree[ lastComment ]?.data,
			children: [],
		};

		// Go through the children of the last comment to find replies by the current user.
		const authorReplies = commentsTree[ lastComment ]?.children.filter( ( replyId ) => {
			return commentsTree[ replyId ]?.data.author?.ID === this.props.currentUserId;
		} );

		// Add the latest reply of the current user to the comments children array and comment tree.
		if ( authorReplies?.length ) {
			const lastReply = authorReplies.pop();
			newCommentTree[ lastComment ].children.push( lastReply );
			newCommentTree[ lastReply ] = {
				data: commentsTree[ lastReply ].data,
				// Ensure no children since this is the last reply we want rendered.
				children: [],
			};
		}

		return {
			displayedComments: lastCommentArr,
			// We will show all comments in the newCommentTree, subtract 1 for the children array.
			displayedCommentsCount: Object.keys( newCommentTree ).length - 1,
			commentsTreeToUse: newCommentTree,
		};
	};

	removePingAndTrackbacks = ( commentsTree ) => {
		const newTree = pickBy(
			commentsTree,
			( comment ) =>
				comment.data && comment.data.type !== 'pingback' && comment.data.type !== 'trackback'
		);
		// Ensure we add the new children array.
		newTree.children = commentsTree.children.filter( ( commentId ) => newTree[ commentId ] );
		return newTree;
	};

	render() {
		if ( ! this.props.commentsTree ) {
			return null;
		}

		const {
			post: { ID: postId, site_ID: siteId },
			commentsFilter,
			showFilters,
			commentCount,
			followSource,
			expandableView,
		} = this.props;

		const shouldShowFilters = showFilters && ! expandableView;

		const commentsTree = expandableView
			? this.removePingAndTrackbacks( this.props.commentsTree )
			: this.props.commentsTree;

		const { haveEarlierCommentsToFetch, haveLaterCommentsToFetch } =
			this.props.commentsFetchingStatus;

		const amountOfCommentsToTake = this.props.startingCommentId
			? Infinity
			: this.state.amountOfCommentsToTake;

		const isCollapsedInline = expandableView && ! this.props.isExpanded;

		const {
			displayedComments,
			displayedCommentsCount,
			commentsTreeToUse = commentsTree,
		} = isCollapsedInline
			? this.getDisplayedCollapsedInlineComments( commentsTree )
			: this.getDisplayedComments( commentsTree.children, amountOfCommentsToTake );

		// Note: we might show fewer comments than commentsCount because some comments might be
		// orphans (parent deleted/unapproved), that comment will become unreachable but still counted.
		const showViewMoreComments =
			! this.props.expandableView &&
			( size( commentsTree.children ) > amountOfCommentsToTake ||
				haveEarlierCommentsToFetch ||
				haveLaterCommentsToFetch ) &&
			displayedCommentsCount > 0;

		// If we're not yet fetched all comments from server, we can only rely on server's count.
		// once we got all the comments tree, we can calculate the count of reachable comments
		const actualCommentsCount =
			haveEarlierCommentsToFetch || haveLaterCommentsToFetch
				? commentCount
				: // Use commentsTree on props since 'commentsTree' var here may have pingbacks
				  // filtered out above.
				  this.getCommentsCount( this.props.commentsTree.children );

		const showConversationFollowButton =
			this.props.showConversationFollowButton &&
			shouldShowConversationFollowButton( this.props.post );

		const showManageCommentsButton =
			! expandableView && this.props.canUserModerateComments && commentCount > 0;

		return (
			<div
				className={ clsx( 'comments__comment-list', {
					'has-double-actions': showManageCommentsButton && showConversationFollowButton,
					'is-inline': expandableView,
					'is-collapsed': isCollapsedInline,
				} ) }
				ref={ this.listRef }
			>
				{ ( this.props.showCommentCount ||
					showManageCommentsButton ||
					showConversationFollowButton ) && (
					<div className="comments__info-bar">
						<div className="comments__info-bar-title-links">
							{ this.props.showCommentCount && <CommentCount count={ actualCommentsCount } /> }
							<div className="comments__actions-wrapper">
								{ showManageCommentsButton && this.renderCommentManageLink() }
								{ showConversationFollowButton && (
									<ConversationFollowButton
										className="comments__conversation-follow-button"
										siteId={ siteId }
										postId={ postId }
										post={ this.props.post }
										followSource={ followSource }
										followIcon={ ReaderFollowConversationIcon( { iconSize: 24 } ) }
										followingIcon={ ReaderFollowingConversationIcon( {
											iconSize: 24,
											className: 'reader-following-conversation',
										} ) }
									/>
								) }
							</div>
						</div>
					</div>
				) }
				<PostCommentFormRoot
					post={ this.props.post }
					commentsTree={ commentsTreeToUse }
					commentText={ this.state.commentText }
					onUpdateCommentText={ this.onUpdateCommentText }
					activeReplyCommentId={ this.props.activeReplyCommentId }
					isInlineComment={ this.props.expandableView }
				/>
				{ shouldShowFilters && (
					<SegmentedControl compact primary>
						<SegmentedControl.Item
							selected={ commentsFilter === 'all' }
							onClick={ this.handleFilterClick( 'all' ) }
						>
							{ translate( 'All' ) }
						</SegmentedControl.Item>
						<SegmentedControl.Item
							selected={ commentsFilter === 'approved' }
							onClick={ this.handleFilterClick( 'approved' ) }
						>
							{ translate( 'Approved', { context: 'comment status' } ) }
						</SegmentedControl.Item>
						<SegmentedControl.Item
							selected={ commentsFilter === 'unapproved' }
							onClick={ this.handleFilterClick( 'unapproved' ) }
						>
							{ translate( 'Pending', { context: 'comment status' } ) }
						</SegmentedControl.Item>
						<SegmentedControl.Item
							selected={ commentsFilter === 'spam' }
							onClick={ this.handleFilterClick( 'spam' ) }
						>
							{ translate( 'Spam', { context: 'comment status' } ) }
						</SegmentedControl.Item>
						<SegmentedControl.Item
							selected={ commentsFilter === 'trash' }
							onClick={ this.handleFilterClick( 'trash' ) }
						>
							{ translate( 'Trash', { context: 'comment status' } ) }
						</SegmentedControl.Item>
					</SegmentedControl>
				) }
				{ showViewMoreComments && this.props.startingCommentId && (
					<button className="comments__view-more" onClick={ this.viewLaterCommentsHandler }>
						{ translate( 'Load more comments (Showing %(shown)d of %(total)d)', {
							args: {
								shown: displayedCommentsCount,
								total: actualCommentsCount,
							},
						} ) }
					</button>
				) }
				{ this.renderCommentsList(
					displayedComments,
					displayedCommentsCount,
					actualCommentsCount,
					commentsTreeToUse,
					commentsTree
				) }
				{ showViewMoreComments && (
					<button
						className="comments__view-more comments__view-more-last"
						onClick={ this.viewEarlierCommentsHandler }
					>
						{ translate( 'Load more comments (Showing %(shown)d of %(total)d)', {
							args: {
								shown: displayedCommentsCount,
								total: actualCommentsCount,
							},
						} ) }
					</button>
				) }
			</div>
		);
	}
}

export default connect(
	( state, ownProps ) => {
		const authorId = getCurrentUserId( state );
		const siteId = ownProps.post.site_ID;
		const postId = ownProps.post.ID;

		return {
			siteId,
			postId,
			currentUserId: authorId,
			canUserModerateComments: canCurrentUser( state, siteId, 'moderate_comments' ),
			commentsTree: getPostCommentsTree(
				state,
				siteId,
				postId,
				ownProps.commentsFilterDisplay ? ownProps.commentsFilterDisplay : ownProps.commentsFilter,
				authorId
			),
			commentsFetchingStatus: commentsFetchingStatus(
				state,
				siteId,
				postId,
				ownProps.commentCount
			),
			initialComment: getCommentById( {
				state,
				siteId,
				commentId: ownProps.startingCommentId,
			} ),
			activeReplyCommentId: getActiveReplyCommentId( {
				state,
				siteId,
				postId,
			} ),
			isExpanded: getInlineCommentsExpandedState( state, ownProps.streamKey, siteId, postId ),
		};
	},
	{
		requestComment,
		requestPostComments,
		recordReaderTracksEvent,
		setActiveReply,
		toggleInlineCommentsExpanded,
	}
)( PostCommentList );