summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/components/tabs/tabs.js
blob: eaa0738b320f8401936e350ca5eabc92bfe627ab (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* 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";

define(function (require, exports, module) {
  const React = require("devtools/client/shared/vendor/react");
  const { DOM } = React;
  const { findDOMNode } = require("devtools/client/shared/vendor/react-dom");

  /**
   * Renders simple 'tab' widget.
   *
   * Based on ReactSimpleTabs component
   * https://github.com/pedronauck/react-simpletabs
   *
   * Component markup (+CSS) example:
   *
   * <div class='tabs'>
   *  <nav class='tabs-navigation'>
   *    <ul class='tabs-menu'>
   *      <li class='tabs-menu-item is-active'>Tab #1</li>
   *      <li class='tabs-menu-item'>Tab #2</li>
   *    </ul>
   *  </nav>
   *  <div class='panels'>
   *    The content of active panel here
   *  </div>
   * <div>
   */
  let Tabs = React.createClass({
    displayName: "Tabs",

    propTypes: {
      className: React.PropTypes.oneOfType([
        React.PropTypes.array,
        React.PropTypes.string,
        React.PropTypes.object
      ]),
      tabActive: React.PropTypes.number,
      onMount: React.PropTypes.func,
      onBeforeChange: React.PropTypes.func,
      onAfterChange: React.PropTypes.func,
      children: React.PropTypes.oneOfType([
        React.PropTypes.array,
        React.PropTypes.element
      ]).isRequired,
      showAllTabsMenu: React.PropTypes.bool,
      onAllTabsMenuClick: React.PropTypes.func,
    },

    getDefaultProps: function () {
      return {
        tabActive: 0,
        showAllTabsMenu: false,
      };
    },

    getInitialState: function () {
      return {
        tabActive: this.props.tabActive,

        // This array is used to store an information whether a tab
        // at specific index has already been created (e.g. selected
        // at least once).
        // If yes, it's rendered even if not currently selected.
        // This is because in some cases we don't want to re-create
        // tab content when it's being unselected/selected.
        // E.g. in case of an iframe being used as a tab-content
        // we want the iframe to stay in the DOM.
        created: [],

        // True if tabs can't fit into available horizontal space.
        overflow: false,
      };
    },

    componentDidMount: function () {
      let node = findDOMNode(this);
      node.addEventListener("keydown", this.onKeyDown, false);

      // Register overflow listeners to manage visibility
      // of all-tabs-menu. This menu is displayed when there
      // is not enough h-space to render all tabs.
      // It allows the user to select a tab even if it's hidden.
      if (this.props.showAllTabsMenu) {
        node.addEventListener("overflow", this.onOverflow, false);
        node.addEventListener("underflow", this.onUnderflow, false);
      }

      let index = this.state.tabActive;
      if (this.props.onMount) {
        this.props.onMount(index);
      }
    },

    componentWillReceiveProps: function (newProps) {
      // Check type of 'tabActive' props to see if it's valid
      // (it's 0-based index).
      if (typeof newProps.tabActive == "number") {
        let created = [...this.state.created];
        created[newProps.tabActive] = true;

        this.setState(Object.assign({}, this.state, {
          tabActive: newProps.tabActive,
          created: created,
        }));
      }
    },

    componentWillUnmount: function () {
      let node = findDOMNode(this);
      node.removeEventListener("keydown", this.onKeyDown, false);

      if (this.props.showAllTabsMenu) {
        node.removeEventListener("overflow", this.onOverflow, false);
        node.removeEventListener("underflow", this.onUnderflow, false);
      }
    },

    // DOM Events

    onOverflow: function (event) {
      if (event.target.classList.contains("tabs-menu")) {
        this.setState({
          overflow: true
        });
      }
    },

    onUnderflow: function (event) {
      if (event.target.classList.contains("tabs-menu")) {
        this.setState({
          overflow: false
        });
      }
    },

    onKeyDown: function (event) {
      // Bail out if the focus isn't on a tab.
      if (!event.target.closest(".tabs-menu-item")) {
        return;
      }

      let tabActive = this.state.tabActive;
      let tabCount = this.props.children.length;

      switch (event.code) {
        case "ArrowRight":
          tabActive = Math.min(tabCount - 1, tabActive + 1);
          break;
        case "ArrowLeft":
          tabActive = Math.max(0, tabActive - 1);
          break;
      }

      if (this.state.tabActive != tabActive) {
        this.setActive(tabActive);
      }
    },

    onClickTab: function (index, event) {
      this.setActive(index);
      event.preventDefault();
    },

    onAllTabsMenuClick: function (event) {
      if (this.props.onAllTabsMenuClick) {
        this.props.onAllTabsMenuClick(event);
      }
    },

    // API

    setActive: function (index) {
      let onAfterChange = this.props.onAfterChange;
      let onBeforeChange = this.props.onBeforeChange;

      if (onBeforeChange) {
        let cancel = onBeforeChange(index);
        if (cancel) {
          return;
        }
      }

      let created = [...this.state.created];
      created[index] = true;

      let newState = Object.assign({}, this.state, {
        tabActive: index,
        created: created
      });

      this.setState(newState, () => {
        // Properly set focus on selected tab.
        let node = findDOMNode(this);
        let selectedTab = node.querySelector(".is-active > a");
        if (selectedTab) {
          selectedTab.focus();
        }

        if (onAfterChange) {
          onAfterChange(index);
        }
      });
    },

    // Rendering

    renderMenuItems: function () {
      if (!this.props.children) {
        throw new Error("There must be at least one Tab");
      }

      if (!Array.isArray(this.props.children)) {
        this.props.children = [this.props.children];
      }

      let tabs = this.props.children
        .map(tab => {
          return typeof tab === "function" ? tab() : tab;
        }).filter(tab => {
          return tab;
        }).map((tab, index) => {
          let ref = ("tab-menu-" + index);
          let title = tab.props.title;
          let tabClassName = tab.props.className;
          let isTabSelected = this.state.tabActive === index;

          let classes = [
            "tabs-menu-item",
            tabClassName,
            isTabSelected ? "is-active" : ""
          ].join(" ");

          // Set tabindex to -1 (except the selected tab) so, it's focusable,
          // but not reachable via sequential tab-key navigation.
          // Changing selected tab (and so, moving focus) is done through
          // left and right arrow keys.
          // See also `onKeyDown()` event handler.
          return (
            DOM.li({
              ref: ref,
              key: index,
              id: "tab-" + index,
              className: classes,
              role: "presentation",
            },
              DOM.a({
                tabIndex: this.state.tabActive === index ? 0 : -1,
                "aria-controls": "panel-" + index,
                "aria-selected": isTabSelected,
                role: "tab",
                onClick: this.onClickTab.bind(this, index),
              },
                title
              )
            )
          );
        });

      // Display the menu only if there is not enough horizontal
      // space for all tabs (and overflow happened).
      let allTabsMenu = this.state.overflow ? (
        DOM.div({
          className: "all-tabs-menu",
          onClick: this.props.onAllTabsMenuClick
        })
      ) : null;

      return (
        DOM.nav({className: "tabs-navigation"},
          DOM.ul({className: "tabs-menu", role: "tablist"},
            tabs
          ),
          allTabsMenu
        )
      );
    },

    renderPanels: function () {
      if (!this.props.children) {
        throw new Error("There must be at least one Tab");
      }

      if (!Array.isArray(this.props.children)) {
        this.props.children = [this.props.children];
      }

      let selectedIndex = this.state.tabActive;

      let panels = this.props.children
        .map(tab => {
          return typeof tab === "function" ? tab() : tab;
        }).filter(tab => {
          return tab;
        }).map((tab, index) => {
          let selected = selectedIndex == index;

          // Use 'visibility:hidden' + 'width/height:0' for hiding
          // content of non-selected tab. It's faster (not sure why)
          // than display:none and visibility:collapse.
          let style = {
            visibility: selected ? "visible" : "hidden",
            height: selected ? "100%" : "0",
            width: selected ? "100%" : "0",
          };

          return (
            DOM.div({
              key: index,
              id: "panel-" + index,
              style: style,
              className: "tab-panel-box",
              role: "tabpanel",
              "aria-labelledby": "tab-" + index,
            },
              (selected || this.state.created[index]) ? tab : null
            )
          );
        });

      return (
        DOM.div({className: "panels"},
          panels
        )
      );
    },

    render: function () {
      let classNames = ["tabs", this.props.className].join(" ");

      return (
        DOM.div({className: classNames},
          this.renderMenuItems(),
          this.renderPanels()
        )
      );
    },
  });

  /**
   * Renders simple tab 'panel'.
   */
  let Panel = React.createClass({
    displayName: "Panel",

    propTypes: {
      title: React.PropTypes.string.isRequired,
      children: React.PropTypes.oneOfType([
        React.PropTypes.array,
        React.PropTypes.element
      ]).isRequired
    },

    render: function () {
      return DOM.div({className: "tab-panel"},
        this.props.children
      );
    }
  });

  // Exports from this module
  exports.TabPanel = Panel;
  exports.Tabs = Tabs;
});