summaryrefslogtreecommitdiffstats
path: root/devtools/client/netmonitor/src/components/messages/MessageListContent.js
blob: f4377911af3e8f3a782ee096b9b769eeaf5718c2 (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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/* 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/. */

"use strict";

const {
  Component,
  createFactory,
} = require("resource://devtools/client/shared/vendor/react.js");
const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
const {
  connect,
} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
const { PluralForm } = require("resource://devtools/shared/plural-form.js");
const {
  getDisplayedMessages,
  isCurrentChannelClosed,
  getClosedConnectionDetails,
} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
const { table, tbody, tr, td, div, input, label, hr, p } = dom;
const {
  L10N,
} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
const MESSAGES_EMPTY_TEXT = L10N.getStr("messagesEmptyText");
const TOGGLE_MESSAGES_TRUNCATION = L10N.getStr("toggleMessagesTruncation");
const TOGGLE_MESSAGES_TRUNCATION_TITLE = L10N.getStr(
  "toggleMessagesTruncation.title"
);
const CONNECTION_CLOSED_TEXT = L10N.getStr("netmonitor.ws.connection.closed");
const {
  MESSAGE_HEADERS,
} = require("resource://devtools/client/netmonitor/src/constants.js");
const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");

const {
  getSelectedMessage,
} = require("resource://devtools/client/netmonitor/src/selectors/index.js");

// Components
const MessageListContextMenu = require("resource://devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js");
loader.lazyGetter(this, "MessageListHeader", function () {
  return createFactory(
    require("resource://devtools/client/netmonitor/src/components/messages/MessageListHeader.js")
  );
});
loader.lazyGetter(this, "MessageListItem", function () {
  return createFactory(
    require("resource://devtools/client/netmonitor/src/components/messages/MessageListItem.js")
  );
});

const LEFT_MOUSE_BUTTON = 0;

/**
 * Renders the actual contents of the message list.
 */
class MessageListContent extends Component {
  static get propTypes() {
    return {
      connector: PropTypes.object.isRequired,
      startPanelContainer: PropTypes.object,
      messages: PropTypes.array,
      selectedMessage: PropTypes.object,
      selectMessage: PropTypes.func.isRequired,
      columns: PropTypes.object.isRequired,
      isClosed: PropTypes.bool.isRequired,
      closedConnectionDetails: PropTypes.object,
      channelId: PropTypes.number,
      onSelectMessageDelta: PropTypes.func.isRequired,
    };
  }

  constructor(props) {
    super(props);

    this.onContextMenu = this.onContextMenu.bind(this);
    this.onKeyDown = this.onKeyDown.bind(this);
    this.messagesLimit = Services.prefs.getIntPref(
      "devtools.netmonitor.msg.displayed-messages.limit"
    );
    this.currentTruncatedNum = 0;
    this.state = {
      checked: false,
    };
    this.pinnedToBottom = false;
    this.initIntersectionObserver = false;
    this.intersectionObserver = null;
    this.toggleTruncationCheckBox = this.toggleTruncationCheckBox.bind(this);
  }

  componentDidMount() {
    const { startPanelContainer } = this.props;
    const { scrollAnchor } = this.refs;

    if (scrollAnchor) {
      // Always scroll to anchor when MessageListContent component first mounts.
      scrollAnchor.scrollIntoView();
    }
    this.setupScrollToBottom(startPanelContainer, scrollAnchor);
  }

  componentDidUpdate(prevProps) {
    const { startPanelContainer, channelId } = this.props;
    const { scrollAnchor } = this.refs;

    // When messages are cleared, the previous scrollAnchor would be destroyed, so we need to reset this boolean.
    if (!scrollAnchor) {
      this.initIntersectionObserver = false;
    }

    // In addition to that, we need to reset currentTruncatedNum
    if (prevProps.messages.length && this.props.messages.length === 0) {
      this.currentTruncatedNum = 0;
    }

    // If a new connection is selected, scroll to anchor.
    if (channelId !== prevProps.channelId && scrollAnchor) {
      scrollAnchor.scrollIntoView();
    }

    // Do not autoscroll if the selection changed. This would cause
    // the newly selected message to jump just after clicking in.
    // (not user friendly)
    //
    // If the selection changed, we need to ensure that the newly
    // selected message is properly scrolled into the visible area.
    if (prevProps.selectedMessage === this.props.selectedMessage) {
      this.setupScrollToBottom(startPanelContainer, scrollAnchor);
    } else {
      const head = document.querySelector("thead.message-list-headers-group");
      const selectedRow = document.querySelector(
        "tr.message-list-item.selected"
      );

      if (selectedRow) {
        const rowRect = selectedRow.getBoundingClientRect();
        const scrollableRect = startPanelContainer.getBoundingClientRect();
        const headRect = head.getBoundingClientRect();

        if (rowRect.top <= scrollableRect.top) {
          selectedRow.scrollIntoView(true);

          // We need to scroll a bit more to get the row out
          // of the header. The header is sticky and overlaps
          // part of the scrollable area.
          startPanelContainer.scrollTop -= headRect.height;
        } else if (rowRect.bottom > scrollableRect.bottom) {
          selectedRow.scrollIntoView(false);
        }
      }
    }
  }

  componentWillUnmount() {
    // Reset observables and boolean values.
    const { scrollAnchor } = this.refs;

    if (this.intersectionObserver) {
      if (scrollAnchor) {
        this.intersectionObserver.unobserve(scrollAnchor);
      }
      this.initIntersectionObserver = false;
      this.pinnedToBottom = false;
    }
  }

  setupScrollToBottom(startPanelContainer, scrollAnchor) {
    if (startPanelContainer && scrollAnchor) {
      // Initialize intersection observer.
      if (!this.initIntersectionObserver) {
        this.intersectionObserver = new IntersectionObserver(
          () => {
            // When scrollAnchor first comes into view, this.pinnedToBottom is set to true.
            // When the anchor goes out of view, this callback function triggers again and toggles this.pinnedToBottom.
            // Subsequent scroll into/out of view will toggle this.pinnedToBottom.
            this.pinnedToBottom = !this.pinnedToBottom;
          },
          {
            root: startPanelContainer,
            threshold: 0.1,
          }
        );
        if (this.intersectionObserver) {
          this.intersectionObserver.observe(scrollAnchor);
          this.initIntersectionObserver = true;
        }
      }

      if (this.pinnedToBottom) {
        scrollAnchor.scrollIntoView();
      }
    }
  }

  toggleTruncationCheckBox() {
    this.setState({
      checked: !this.state.checked,
    });
  }

  onMouseDown(evt, item) {
    if (evt.button === LEFT_MOUSE_BUTTON) {
      this.props.selectMessage(item);
    }
  }

  onContextMenu(evt, item) {
    evt.preventDefault();
    const { connector } = this.props;
    this.contextMenu = new MessageListContextMenu({
      connector,
    });
    this.contextMenu.open(evt, item);
  }

  /**
   * Handler for keyboard events. For arrow up/down, page up/down, home/end,
   * move the selection up or down.
   */
  onKeyDown(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    let delta;

    switch (evt.key) {
      case "ArrowUp":
        delta = -1;
        break;
      case "ArrowDown":
        delta = +1;
        break;
      case "PageUp":
        delta = "PAGE_UP";
        break;
      case "PageDown":
        delta = "PAGE_DOWN";
        break;
      case "Home":
        delta = -Infinity;
        break;
      case "End":
        delta = +Infinity;
        break;
    }

    if (delta) {
      this.props.onSelectMessageDelta(delta);
    }
  }

  render() {
    const {
      messages,
      selectedMessage,
      connector,
      columns,
      isClosed,
      closedConnectionDetails,
    } = this.props;

    if (messages.length === 0) {
      return div(
        { className: "empty-notice message-list-empty-notice" },
        MESSAGES_EMPTY_TEXT
      );
    }

    const visibleColumns = MESSAGE_HEADERS.filter(
      header => columns[header.name]
    ).map(col => col.name);

    let displayedMessages;
    let MESSAGES_TRUNCATED;
    const shouldTruncate = messages.length > this.messagesLimit;
    if (shouldTruncate) {
      // If the checkbox is checked, we display all messages after the currentTruncatedNum limit.
      // If the checkbox is unchecked, we display all messages after the messagesLimit.
      this.currentTruncatedNum = this.state.checked
        ? this.currentTruncatedNum
        : messages.length - this.messagesLimit;
      displayedMessages = messages.slice(this.currentTruncatedNum);

      MESSAGES_TRUNCATED = PluralForm.get(
        this.currentTruncatedNum,
        L10N.getStr("netmonitor.ws.truncated-messages.warning")
      ).replace("#1", this.currentTruncatedNum);
    } else {
      displayedMessages = messages;
    }

    let connectionClosedMsg = CONNECTION_CLOSED_TEXT;
    if (
      closedConnectionDetails &&
      closedConnectionDetails.code !== undefined &&
      closedConnectionDetails.reason !== undefined
    ) {
      connectionClosedMsg += `: ${closedConnectionDetails.code} ${closedConnectionDetails.reason}`;
    }
    return div(
      {},
      table(
        { className: "message-list-table" },
        MessageListHeader(),
        tbody(
          {
            className: "message-list-body",
            onKeyDown: this.onKeyDown,
          },
          tr(
            {
              tabIndex: 0,
            },
            td(
              {
                className: "truncated-messages-cell",
                colSpan: visibleColumns.length,
              },
              shouldTruncate &&
                div(
                  {
                    className: "truncated-messages-header",
                  },
                  div(
                    {
                      className: "truncated-messages-container",
                    },
                    div({
                      className: "truncated-messages-warning-icon",
                    }),
                    div(
                      {
                        className: "truncated-message",
                        title: MESSAGES_TRUNCATED,
                      },
                      MESSAGES_TRUNCATED
                    )
                  ),
                  label(
                    {
                      className: "truncated-messages-checkbox-label",
                      title: TOGGLE_MESSAGES_TRUNCATION_TITLE,
                    },
                    input({
                      type: "checkbox",
                      className: "truncation-checkbox",
                      title: TOGGLE_MESSAGES_TRUNCATION_TITLE,
                      checked: this.state.checked,
                      onChange: this.toggleTruncationCheckBox,
                    }),
                    TOGGLE_MESSAGES_TRUNCATION
                  )
                )
            )
          ),
          displayedMessages.map((item, index) =>
            MessageListItem({
              key: "message-list-item-" + index,
              item,
              index,
              isSelected: item === selectedMessage,
              onMouseDown: evt => this.onMouseDown(evt, item),
              onContextMenu: evt => this.onContextMenu(evt, item),
              connector,
              visibleColumns,
            })
          )
        )
      ),
      isClosed &&
        p(
          {
            className: "msg-connection-closed-message",
          },
          connectionClosedMsg
        ),
      hr({
        ref: "scrollAnchor",
        className: "message-list-scroll-anchor",
      })
    );
  }
}

module.exports = connect(
  state => ({
    selectedMessage: getSelectedMessage(state),
    messages: getDisplayedMessages(state),
    columns: state.messages.columns,
    isClosed: isCurrentChannelClosed(state),
    closedConnectionDetails: getClosedConnectionDetails(state),
  }),
  dispatch => ({
    selectMessage: item => dispatch(Actions.selectMessage(item)),
    onSelectMessageDelta: delta => dispatch(Actions.selectMessageDelta(delta)),
  })
)(MessageListContent);