summaryrefslogtreecommitdiffstats
path: root/devtools/client/debugger/src/components/shared/Accordion.js
blob: 3b5d5ae516a84c114fb0f338aee30c298852d7bc (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
/* 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 { cloneElement, Component } from "devtools/client/shared/vendor/react";
import {
  aside,
  button,
  div,
  h2,
} from "devtools/client/shared/vendor/react-dom-factories";
import PropTypes from "devtools/client/shared/vendor/react-prop-types";

class Accordion extends Component {
  static get propTypes() {
    return {
      items: PropTypes.array.isRequired,
    };
  }

  handleHeaderClick(i) {
    const item = this.props.items[i];
    const opened = !item.opened;
    item.opened = opened;

    if (item.onToggle) {
      item.onToggle(opened);
    }

    // We force an update because otherwise the accordion
    // would not re-render
    this.forceUpdate();
  }

  renderContainer = (item, i) => {
    const { opened } = item;
    const contentElementId = `${item.id}-content`;

    return aside(
      {
        className: item.className,
        key: item.id,
        "aria-labelledby": item.id,
        role: item.role,
      },
      h2(
        {
          className: "_header",
        },
        button(
          {
            id: item.id,
            className: "header-label",
            "aria-expanded": `${opened ? "true" : "false"}`,
            "aria-controls": opened ? contentElementId : undefined,
            onClick: () => this.handleHeaderClick(i),
          },
          item.header
        ),
        item.buttons
          ? div(
              {
                className: "header-buttons",
              },
              item.buttons
            )
          : null
      ),
      opened &&
        div(
          {
            className: "_content",
            id: contentElementId,
          },
          cloneElement(item.component, item.componentProps || {})
        )
    );
  };
  render() {
    return div(
      {
        className: "accordion",
      },
      this.props.items.map(this.renderContainer)
    );
  }
}

export default Accordion;