summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/content-src/components/Sections/Sections.jsx
blob: e72e9145adae0f607632e314fed305438cd94c57 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

import {
  actionCreators as ac,
  actionTypes as at,
} from "common/Actions.sys.mjs";
import { Card, PlaceholderCard } from "content-src/components/Card/Card";
import { CollapsibleSection } from "content-src/components/CollapsibleSection/CollapsibleSection";
import { ComponentPerfTimer } from "content-src/components/ComponentPerfTimer/ComponentPerfTimer";
import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
import { connect } from "react-redux";
import { MoreRecommendations } from "content-src/components/MoreRecommendations/MoreRecommendations";
import { PocketLoggedInCta } from "content-src/components/PocketLoggedInCta/PocketLoggedInCta";
import React from "react";
import { Topics } from "content-src/components/Topics/Topics";
import { TopSites } from "content-src/components/TopSites/TopSites";

const VISIBLE = "visible";
const VISIBILITY_CHANGE_EVENT = "visibilitychange";
const CARDS_PER_ROW_DEFAULT = 3;
const CARDS_PER_ROW_COMPACT_WIDE = 4;

export class Section extends React.PureComponent {
  get numRows() {
    const { rowsPref, maxRows, Prefs } = this.props;
    return rowsPref ? Prefs.values[rowsPref] : maxRows;
  }

  _dispatchImpressionStats() {
    const { props } = this;
    let cardsPerRow = CARDS_PER_ROW_DEFAULT;
    if (
      props.compactCards &&
      global.matchMedia(`(min-width: 1072px)`).matches
    ) {
      // If the section has compact cards and the viewport is wide enough, we show
      // 4 columns instead of 3.
      // $break-point-widest = 1072px (from _variables.scss)
      cardsPerRow = CARDS_PER_ROW_COMPACT_WIDE;
    }
    const maxCards = cardsPerRow * this.numRows;
    const cards = props.rows.slice(0, maxCards);

    if (this.needsImpressionStats(cards)) {
      props.dispatch(
        ac.ImpressionStats({
          source: props.eventSource,
          tiles: cards.map(link => ({ id: link.guid })),
        })
      );
      this.impressionCardGuids = cards.map(link => link.guid);
    }
  }

  // This sends an event when a user sees a set of new content. If content
  // changes while the page is hidden (i.e. preloaded or on a hidden tab),
  // only send the event if the page becomes visible again.
  sendImpressionStatsOrAddListener() {
    const { props } = this;

    if (!props.shouldSendImpressionStats || !props.dispatch) {
      return;
    }

    if (props.document.visibilityState === VISIBLE) {
      this._dispatchImpressionStats();
    } else {
      // We should only ever send the latest impression stats ping, so remove any
      // older listeners.
      if (this._onVisibilityChange) {
        props.document.removeEventListener(
          VISIBILITY_CHANGE_EVENT,
          this._onVisibilityChange
        );
      }

      // When the page becomes visible, send the impression stats ping if the section isn't collapsed.
      this._onVisibilityChange = () => {
        if (props.document.visibilityState === VISIBLE) {
          if (!this.props.pref.collapsed) {
            this._dispatchImpressionStats();
          }
          props.document.removeEventListener(
            VISIBILITY_CHANGE_EVENT,
            this._onVisibilityChange
          );
        }
      };
      props.document.addEventListener(
        VISIBILITY_CHANGE_EVENT,
        this._onVisibilityChange
      );
    }
  }

  componentWillMount() {
    this.sendNewTabRehydrated(this.props.initialized);
  }

  componentDidMount() {
    if (this.props.rows.length && !this.props.pref.collapsed) {
      this.sendImpressionStatsOrAddListener();
    }
  }

  componentDidUpdate(prevProps) {
    const { props } = this;
    const isCollapsed = props.pref.collapsed;
    const wasCollapsed = prevProps.pref.collapsed;
    if (
      // Don't send impression stats for the empty state
      props.rows.length &&
      // We only want to send impression stats if the content of the cards has changed
      // and the section is not collapsed...
      ((props.rows !== prevProps.rows && !isCollapsed) ||
        // or if we are expanding a section that was collapsed.
        (wasCollapsed && !isCollapsed))
    ) {
      this.sendImpressionStatsOrAddListener();
    }
  }

  componentWillUpdate(nextProps) {
    this.sendNewTabRehydrated(nextProps.initialized);
  }

  componentWillUnmount() {
    if (this._onVisibilityChange) {
      this.props.document.removeEventListener(
        VISIBILITY_CHANGE_EVENT,
        this._onVisibilityChange
      );
    }
  }

  needsImpressionStats(cards) {
    if (
      !this.impressionCardGuids ||
      this.impressionCardGuids.length !== cards.length
    ) {
      return true;
    }

    for (let i = 0; i < cards.length; i++) {
      if (cards[i].guid !== this.impressionCardGuids[i]) {
        return true;
      }
    }

    return false;
  }

  // The NEW_TAB_REHYDRATED event is used to inform feeds that their
  // data has been consumed e.g. for counting the number of tabs that
  // have rendered that data.
  sendNewTabRehydrated(initialized) {
    if (initialized && !this.renderNotified) {
      this.props.dispatch(
        ac.AlsoToMain({ type: at.NEW_TAB_REHYDRATED, data: {} })
      );
      this.renderNotified = true;
    }
  }

  render() {
    const {
      id,
      eventSource,
      title,
      rows,
      Pocket,
      topics,
      emptyState,
      dispatch,
      compactCards,
      read_more_endpoint,
      contextMenuOptions,
      initialized,
      learnMore,
      pref,
      privacyNoticeURL,
      isFirst,
      isLast,
    } = this.props;

    const waitingForSpoc =
      id === "topstories" && this.props.Pocket.waitingForSpoc;
    const maxCardsPerRow = compactCards
      ? CARDS_PER_ROW_COMPACT_WIDE
      : CARDS_PER_ROW_DEFAULT;
    const { numRows } = this;
    const maxCards = maxCardsPerRow * numRows;
    const maxCardsOnNarrow = CARDS_PER_ROW_DEFAULT * numRows;

    const { pocketCta, isUserLoggedIn } = Pocket || {};
    const { useCta } = pocketCta || {};

    // Don't display anything until we have a definitve result from Pocket,
    // to avoid a flash of logged out state while we render.
    const isPocketLoggedInDefined =
      isUserLoggedIn === true || isUserLoggedIn === false;

    const hasTopics = topics && !!topics.length;

    const shouldShowPocketCta =
      id === "topstories" && useCta && isUserLoggedIn === false;

    // Show topics only for top stories and if it has loaded with topics.
    // The classs .top-stories-bottom-container ensures content doesn't shift as things load.
    const shouldShowTopics =
      id === "topstories" &&
      hasTopics &&
      ((useCta && isUserLoggedIn === true) ||
        (!useCta && isPocketLoggedInDefined));

    // We use topics to determine language support for read more.
    const shouldShowReadMore = read_more_endpoint && hasTopics;

    const realRows = rows.slice(0, maxCards);

    // The empty state should only be shown after we have initialized and there is no content.
    // Otherwise, we should show placeholders.
    const shouldShowEmptyState = initialized && !rows.length;

    const cards = [];
    if (!shouldShowEmptyState) {
      for (let i = 0; i < maxCards; i++) {
        const link = realRows[i];
        // On narrow viewports, we only show 3 cards per row. We'll mark the rest as
        // .hide-for-narrow to hide in CSS via @media query.
        const className = i >= maxCardsOnNarrow ? "hide-for-narrow" : "";
        let usePlaceholder = !link;
        // If we are in the third card and waiting for spoc,
        // use the placeholder.
        if (!usePlaceholder && i === 2 && waitingForSpoc) {
          usePlaceholder = true;
        }
        cards.push(
          !usePlaceholder ? (
            <Card
              key={i}
              index={i}
              className={className}
              dispatch={dispatch}
              link={link}
              contextMenuOptions={contextMenuOptions}
              eventSource={eventSource}
              shouldSendImpressionStats={this.props.shouldSendImpressionStats}
              isWebExtension={this.props.isWebExtension}
            />
          ) : (
            <PlaceholderCard key={i} className={className} />
          )
        );
      }
    }

    const sectionClassName = [
      "section",
      compactCards ? "compact-cards" : "normal-cards",
    ].join(" ");

    // <Section> <-- React component
    // <section> <-- HTML5 element
    return (
      <ComponentPerfTimer {...this.props}>
        <CollapsibleSection
          className={sectionClassName}
          title={title}
          id={id}
          eventSource={eventSource}
          collapsed={this.props.pref.collapsed}
          showPrefName={(pref && pref.feed) || id}
          privacyNoticeURL={privacyNoticeURL}
          Prefs={this.props.Prefs}
          isFixed={this.props.isFixed}
          isFirst={isFirst}
          isLast={isLast}
          learnMore={learnMore}
          dispatch={this.props.dispatch}
          isWebExtension={this.props.isWebExtension}
        >
          {!shouldShowEmptyState && (
            <ul className="section-list" style={{ padding: 0 }}>
              {cards}
            </ul>
          )}
          {shouldShowEmptyState && (
            <div className="section-empty-state">
              <div className="empty-state">
                <FluentOrText message={emptyState.message}>
                  <p className="empty-state-message" />
                </FluentOrText>
              </div>
            </div>
          )}
          {id === "topstories" && (
            <div className="top-stories-bottom-container">
              {shouldShowTopics && (
                <div className="wrapper-topics">
                  <Topics topics={this.props.topics} />
                </div>
              )}

              {shouldShowPocketCta && (
                <div className="wrapper-cta">
                  <PocketLoggedInCta />
                </div>
              )}

              <div className="wrapper-more-recommendations">
                {shouldShowReadMore && (
                  <MoreRecommendations
                    read_more_endpoint={read_more_endpoint}
                  />
                )}
              </div>
            </div>
          )}
        </CollapsibleSection>
      </ComponentPerfTimer>
    );
  }
}

Section.defaultProps = {
  document: global.document,
  rows: [],
  emptyState: {},
  pref: {},
  title: "",
};

export const SectionIntl = connect(state => ({
  Prefs: state.Prefs,
  Pocket: state.Pocket,
}))(Section);

export class _Sections extends React.PureComponent {
  renderSections() {
    const sections = [];
    const enabledSections = this.props.Sections.filter(
      section => section.enabled
    );
    const { sectionOrder, "feeds.topsites": showTopSites } =
      this.props.Prefs.values;
    // Enabled sections doesn't include Top Sites, so we add it if enabled.
    const expectedCount = enabledSections.length + ~~showTopSites;

    for (const sectionId of sectionOrder.split(",")) {
      const commonProps = {
        key: sectionId,
        isFirst: sections.length === 0,
        isLast: sections.length === expectedCount - 1,
      };
      if (sectionId === "topsites" && showTopSites) {
        sections.push(<TopSites {...commonProps} />);
      } else {
        const section = enabledSections.find(s => s.id === sectionId);
        if (section) {
          sections.push(<SectionIntl {...section} {...commonProps} />);
        }
      }
    }
    return sections;
  }

  render() {
    return <div className="sections-list">{this.renderSections()}</div>;
  }
}

export const Sections = connect(state => ({
  Sections: state.Sections,
  Prefs: state.Prefs,
}))(_Sections);