summaryrefslogtreecommitdiffstats
path: root/devtools/client/webconsole/components/Output/ConsoleTable.js
blob: f41afce96d7d044be3afc86461ac2d0cf4789993 (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
/* 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 dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
const {
  getArrayTypeNames,
} = require("resource://devtools/shared/webconsole/messages.js");
const {
  l10n,
  getDescriptorValue,
} = require("resource://devtools/client/webconsole/utils/messages.js");
loader.lazyGetter(this, "MODE", function () {
  return require("resource://devtools/client/shared/components/reps/index.js")
    .MODE;
});

const GripMessageBody = createFactory(
  require("resource://devtools/client/webconsole/components/Output/GripMessageBody.js")
);

loader.lazyRequireGetter(
  this,
  "PropTypes",
  "resource://devtools/client/shared/vendor/react-prop-types.js"
);

const TABLE_ROW_MAX_ITEMS = 1000;
// Match Chrome max column number.
const TABLE_COLUMN_MAX_ITEMS = 21;

class ConsoleTable extends Component {
  static get propTypes() {
    return {
      dispatch: PropTypes.func.isRequired,
      parameters: PropTypes.array.isRequired,
      serviceContainer: PropTypes.object.isRequired,
      id: PropTypes.string.isRequired,
      setExpanded: PropTypes.func,
    };
  }

  constructor(props) {
    super(props);
    this.getHeaders = this.getHeaders.bind(this);
    this.getRows = this.getRows.bind(this);
  }

  getHeaders(columns) {
    const headerItems = [];
    columns.forEach((value, key) =>
      headerItems.push(
        dom.th(
          {
            key,
            title: value,
          },
          value
        )
      )
    );
    return dom.thead({}, dom.tr({}, headerItems));
  }

  getRows(columns, items) {
    const { dispatch, serviceContainer, setExpanded } = this.props;

    const rows = [];
    items.forEach((item, index) => {
      const cells = [];

      columns.forEach((value, key) => {
        const cellValue = item[key];
        const cellContent =
          typeof cellValue === "undefined"
            ? ""
            : GripMessageBody({
                grip: cellValue,
                mode: MODE.SHORT,
                useQuotes: false,
                serviceContainer,
                dispatch,
                setExpanded,
              });

        cells.push(
          dom.td(
            {
              key,
            },
            cellContent
          )
        );
      });
      rows.push(dom.tr({}, cells));
    });
    return dom.tbody({}, rows);
  }

  render() {
    const { parameters } = this.props;
    const { valueGrip, headersGrip } = getValueAndHeadersGrip(parameters);

    const headers = headersGrip?.preview ? headersGrip.preview.items : null;

    const data = valueGrip?.ownProperties;

    // if we don't have any data, don't show anything.
    if (!data) {
      return null;
    }

    const dataType = getParametersDataType(parameters);
    const { columns, items } = getTableItems(data, dataType, headers);

    // We need to wrap the <table> in a div so we can have the max-height set properly
    // without changing the table display.
    return dom.div(
      { className: "consoletable-wrapper" },
      dom.table(
        {
          className: "consoletable",
        },
        this.getHeaders(columns),
        this.getRows(columns, items)
      )
    );
  }
}

function getValueAndHeadersGrip(parameters) {
  const [valueFront, headersFront] = parameters;

  const headersGrip = headersFront?.getGrip
    ? headersFront.getGrip()
    : headersFront;

  const valueGrip = valueFront?.getGrip ? valueFront.getGrip() : valueFront;

  return { valueGrip, headersGrip };
}

function getParametersDataType(parameters = null) {
  if (!Array.isArray(parameters) || parameters.length === 0) {
    return null;
  }
  const [firstParam] = parameters;
  if (!firstParam || !firstParam.getGrip) {
    return null;
  }
  const grip = firstParam.getGrip();
  return grip.class;
}

const INDEX_NAME = "_index";
const VALUE_NAME = "_value";

function getNamedIndexes(type) {
  return {
    [INDEX_NAME]: getArrayTypeNames().concat("Object").includes(type)
      ? l10n.getStr("table.index")
      : l10n.getStr("table.iterationIndex"),
    [VALUE_NAME]: l10n.getStr("table.value"),
    key: l10n.getStr("table.key"),
  };
}

function hasValidCustomHeaders(headers) {
  return (
    Array.isArray(headers) &&
    headers.every(
      header => typeof header === "string" || Number.isInteger(Number(header))
    )
  );
}

function getTableItems(data = {}, type, headers = null) {
  const namedIndexes = getNamedIndexes(type);

  let columns = new Map();
  const items = [];

  const addItem = function (item) {
    items.push(item);
    Object.keys(item).forEach(key => addColumn(key));
  };

  const validCustomHeaders = hasValidCustomHeaders(headers);

  const addColumn = function (columnIndex) {
    const columnExists = columns.has(columnIndex);
    const hasMaxColumns = columns.size == TABLE_COLUMN_MAX_ITEMS;

    if (
      !columnExists &&
      !hasMaxColumns &&
      (!validCustomHeaders ||
        headers.includes(columnIndex) ||
        columnIndex === INDEX_NAME)
    ) {
      columns.set(columnIndex, namedIndexes[columnIndex] || columnIndex);
    }
  };

  for (let [index, property] of Object.entries(data)) {
    if (type !== "Object" && index == parseInt(index, 10)) {
      index = parseInt(index, 10);
    }

    const item = {
      [INDEX_NAME]: index,
    };

    const propertyValue = getDescriptorValue(property);
    const propertyValueGrip = propertyValue?.getGrip
      ? propertyValue.getGrip()
      : propertyValue;

    if (propertyValueGrip?.ownProperties) {
      const entries = propertyValueGrip.ownProperties;
      for (const [key, entry] of Object.entries(entries)) {
        item[key] = getDescriptorValue(entry);
      }
    } else if (
      propertyValueGrip?.preview &&
      (type === "Map" || type === "WeakMap")
    ) {
      item.key = propertyValueGrip.preview.key;
      item[VALUE_NAME] = propertyValueGrip.preview.value;
    } else {
      item[VALUE_NAME] = propertyValue;
    }

    addItem(item);

    if (items.length === TABLE_ROW_MAX_ITEMS) {
      break;
    }
  }

  // Some headers might not be present in the items, so we make sure to
  // return all the headers set by the user.
  if (validCustomHeaders) {
    headers.forEach(header => addColumn(header));
  }

  // We want to always have the index column first
  if (columns.has(INDEX_NAME)) {
    const index = columns.get(INDEX_NAME);
    columns.delete(INDEX_NAME);
    columns = new Map([[INDEX_NAME, index], ...columns.entries()]);
  }

  // We want to always have the values column last
  if (columns.has(VALUE_NAME)) {
    const index = columns.get(VALUE_NAME);
    columns.delete(VALUE_NAME);
    columns.set(VALUE_NAME, index);
  }

  return {
    columns,
    items,
  };
}

module.exports = ConsoleTable;