summaryrefslogtreecommitdiffstats
path: root/devtools/client/debugger/src/components/ProjectSearch.js
blob: ac8dbd2ef7ecc3544c831e0e1db030ed876e7dba (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
/* 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/>. */

// @flow

import PropTypes from "prop-types";
import React, { Component } from "react";
import { connect } from "../utils/connect";
import classnames from "classnames";
import actions from "../actions";

import { getEditor } from "../utils/editor";
import { highlightMatches } from "../utils/project-search";

import { statusType } from "../reducers/project-text-search";
import { getRelativePath } from "../utils/sources-tree";
import {
  getActiveSearch,
  getTextSearchResults,
  getTextSearchStatus,
  getTextSearchQuery,
  getContext,
} from "../selectors";

import ManagedTree from "./shared/ManagedTree";
import SearchInput from "./shared/SearchInput";
import AccessibleImage from "./shared/AccessibleImage";

import type { List } from "immutable";
import type { ActiveSearchType } from "../reducers/types";
import type { StatusType } from "../reducers/project-text-search";
import type { Context, SourceId } from "../types";

// $FlowIgnore
const { PluralForm } = require("devtools/shared/plural-form");

import "./ProjectSearch.css";

export type Match = {
  type: "MATCH",
  sourceId: SourceId,
  line: number,
  column: number,
  matchIndex: number,
  match: string,
  value: string,
  text: string,
};

type Result = {
  type: "RESULT",
  filepath: string,
  matches: Array<Match>,
  sourceId: SourceId,
};

type Item = Result | Match;

type State = {
  inputValue: string,
  inputFocused: boolean,
  focusedItem: ?Item,
};

type OwnProps = {||};
type Props = {
  cx: Context,
  query: string,
  results: List<Result>,
  status: StatusType,
  activeSearch: ?ActiveSearchType,
  closeProjectSearch: typeof actions.closeProjectSearch,
  searchSources: typeof actions.searchSources,
  clearSearch: typeof actions.clearSearch,
  selectSpecificLocation: typeof actions.selectSpecificLocation,
  setActiveSearch: typeof actions.setActiveSearch,
  doSearchForHighlight: typeof actions.doSearchForHighlight,
};

function getFilePath(item: Item, index?: number) {
  return item.type === "RESULT"
    ? `${item.sourceId}-${index || "$"}`
    : `${item.sourceId}-${item.line}-${item.column}-${index || "$"}`;
}

function sanitizeQuery(query: string): string {
  // no '\' at end of query
  return query.replace(/\\$/, "");
}

export class ProjectSearch extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      inputValue: this.props.query || "",
      inputFocused: false,
      focusedItem: null,
    };
  }

  componentDidMount() {
    const { shortcuts } = this.context;

    shortcuts.on(
      L10N.getStr("projectTextSearch.key"),
      this.toggleProjectTextSearch
    );
    shortcuts.on("Enter", this.onEnterPress);
  }

  componentWillUnmount() {
    const { shortcuts } = this.context;
    shortcuts.off(
      L10N.getStr("projectTextSearch.key"),
      this.toggleProjectTextSearch
    );
    shortcuts.off("Enter", this.onEnterPress);
  }

  componentDidUpdate(prevProps: Props) {
    // If the query changes in redux, also change it in the UI
    if (prevProps.query !== this.props.query) {
      this.setState({ inputValue: this.props.query });
    }
  }

  doSearch(searchTerm: string) {
    this.props.searchSources(this.props.cx, searchTerm);
  }

  toggleProjectTextSearch = (e: KeyboardEvent) => {
    const { cx, closeProjectSearch, setActiveSearch } = this.props;
    if (e) {
      e.preventDefault();
    }

    if (this.isProjectSearchEnabled()) {
      return closeProjectSearch(cx);
    }

    return setActiveSearch("project");
  };

  isProjectSearchEnabled = () => this.props.activeSearch === "project";

  selectMatchItem = (matchItem: Match) => {
    this.props.selectSpecificLocation(this.props.cx, {
      sourceId: matchItem.sourceId,
      line: matchItem.line,
      column: matchItem.column,
    });
    this.props.doSearchForHighlight(
      this.state.inputValue,
      getEditor(),
      matchItem.line,
      matchItem.column
    );
  };

  getResultCount = () =>
    this.props.results.reduce((count, file) => count + file.matches.length, 0);

  onKeyDown = (e: SyntheticKeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Escape") {
      return;
    }

    e.stopPropagation();

    if (e.key !== "Enter") {
      return;
    }
    this.setState({ focusedItem: null });
    const query = sanitizeQuery(this.state.inputValue);
    if (query) {
      this.doSearch(query);
    }
  };

  onHistoryScroll = (query: string) => {
    this.setState({ inputValue: query });
  };

  onEnterPress = () => {
    if (
      !this.isProjectSearchEnabled() ||
      !this.state.focusedItem ||
      this.state.inputFocused
    ) {
      return;
    }
    if (this.state.focusedItem.type === "MATCH") {
      this.selectMatchItem(this.state.focusedItem);
    }
  };

  onFocus = (item: Item) => {
    if (this.state.focusedItem !== item) {
      this.setState({ focusedItem: item });
    }
  };

  inputOnChange = (e: SyntheticInputEvent<HTMLInputElement>) => {
    const inputValue = e.target.value;
    const { cx, clearSearch } = this.props;
    this.setState({ inputValue });
    if (inputValue === "") {
      clearSearch(cx);
    }
  };

  renderFile = (file: Result, focused: boolean, expanded: boolean) => {
    const matchesLength = file.matches.length;
    const matches = ` (${matchesLength} match${matchesLength > 1 ? "es" : ""})`;

    return (
      <div
        className={classnames("file-result", { focused })}
        key={file.sourceId}
      >
        <AccessibleImage className={classnames("arrow", { expanded })} />
        <AccessibleImage className="file" />
        <span className="file-path">{getRelativePath(file.filepath)}</span>
        <span className="matches-summary">{matches}</span>
      </div>
    );
  };

  renderMatch = (match: Match, focused: boolean) => {
    return (
      <div
        className={classnames("result", { focused })}
        onClick={() => setTimeout(() => this.selectMatchItem(match), 50)}
      >
        <span className="line-number" key={match.line}>
          {match.line}
        </span>
        {highlightMatches(match)}
      </div>
    );
  };

  renderItem = (
    item: Item,
    depth: number,
    focused: boolean,
    _: any,
    expanded: boolean
  ) => {
    if (item.type === "RESULT") {
      return this.renderFile(item, focused, expanded);
    }
    return this.renderMatch(item, focused);
  };

  renderResults = () => {
    const { status, results } = this.props;
    if (!this.props.query) {
      return;
    }
    if (results.length) {
      return (
        <ManagedTree
          getRoots={() => results}
          getChildren={file => file.matches || []}
          itemHeight={24}
          autoExpandAll={true}
          autoExpandDepth={1}
          autoExpandNodeChildrenLimit={100}
          getParent={item => null}
          getPath={getFilePath}
          renderItem={this.renderItem}
          focused={this.state.focusedItem}
          onFocus={this.onFocus}
        />
      );
    }
    const msg =
      status === statusType.fetching
        ? L10N.getStr("loadingText")
        : L10N.getStr("projectTextSearch.noResults");
    return <div className="no-result-msg absolute-center">{msg}</div>;
  };

  renderSummary = () => {
    if (this.props.query !== "") {
      const resultsSummaryString = L10N.getStr("sourceSearch.resultsSummary2");
      const count = this.getResultCount();
      return PluralForm.get(count, resultsSummaryString).replace("#1", count);
    }
    return "";
  };

  shouldShowErrorEmoji() {
    return !this.getResultCount() && this.props.status === statusType.done;
  }

  renderInput() {
    const { cx, closeProjectSearch, status } = this.props;
    return (
      <SearchInput
        query={this.state.inputValue}
        count={this.getResultCount()}
        placeholder={L10N.getStr("projectTextSearch.placeholder")}
        size="big"
        showErrorEmoji={this.shouldShowErrorEmoji()}
        summaryMsg={this.renderSummary()}
        isLoading={status === statusType.fetching}
        onChange={this.inputOnChange}
        onFocus={() => this.setState({ inputFocused: true })}
        onBlur={() => this.setState({ inputFocused: false })}
        onKeyDown={this.onKeyDown}
        onHistoryScroll={this.onHistoryScroll}
        handleClose={() => closeProjectSearch(cx)}
        ref="searchInput"
      />
    );
  }

  render() {
    if (!this.isProjectSearchEnabled()) {
      return null;
    }

    return (
      <div className="search-container">
        <div className="project-text-search">
          <div className="header">{this.renderInput()}</div>
          {this.renderResults()}
        </div>
      </div>
    );
  }
}
ProjectSearch.contextTypes = {
  shortcuts: PropTypes.object,
};

const mapStateToProps = state => ({
  cx: getContext(state),
  activeSearch: getActiveSearch(state),
  results: getTextSearchResults(state),
  query: getTextSearchQuery(state),
  status: getTextSearchStatus(state),
});

export default connect<Props, OwnProps, _, _, _, _>(mapStateToProps, {
  closeProjectSearch: actions.closeProjectSearch,
  searchSources: actions.searchSources,
  clearSearch: actions.clearSearch,
  selectSpecificLocation: actions.selectSpecificLocation,
  setActiveSearch: actions.setActiveSearch,
  doSearchForHighlight: actions.doSearchForHighlight,
})(ProjectSearch);