BrowsePage.tsx 11.9 KB
Newer Older
1
2
3
import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
4
import { withStyles } from 'material-ui/styles';
5
6
7
8

import {log} from 'utilities/debug';

import { listCrops } from 'actions/crop';
9
10
11
import { listAccessions, loadGenesysDescriptors } from 'actions/genesys';
import { Descriptor, DescriptorList, DescriptorListExtra } from 'model/descriptor.model';
import { VocabularyTerm } from 'model/vocabulary.model';
12
13
14
15
16
17
18
19
20

import { Page, Pagination } from 'model/common.model';

import Loading from 'ui/common/Loading';
import PaginationComponent from 'ui/common/pagination';
import GenesysBrowseFilters from './c/Filters';
import PrettyFilters from 'ui/common/filter/PrettyFilters';
import DOI from 'ui/common/DOI';

21
22
import { MultiGrid as VMultiGrid, AutoSizer } from 'react-virtualized';

23
24
import Grid from 'material-ui/Grid';

25
26
const styles = (theme) => ({
    filterSection: theme.leftPanel.root,
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
    BodyGrid: {
      width: '100%',
      border: '1px solid #e0e0e0',
    },
    tableCell: {
      padding: '.5rem 1rem',
      borderRight: 'dotted 1px White',
      borderBottom: 'solid 1px White',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
      display: 'inline-block',
      overflow: 'hidden' as 'hidden',
    },
    tableHeaderCell: {
      fontWeight: 'bold' as 'bold',
      color: 'White',
      borderRight: 'dotted 1px #a0d457',
    },
    evenRow: {
      backgroundColor: '#f3f2ee',
    },
    oddRow: {
      backgroundColor: '#f8f7f5',
    },
    noCells: {
      position: 'absolute' as 'absolute',
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
      display: 'flex',
      alignItems: 'center' as 'center',
      justifyContent: 'center' as 'center',
      fontSize: '1em',
      color: '#bdbdbd',
    },
63
64
65
66
67
68
69
70
71
});

interface IBrowsePageProps extends React.ClassAttributes<any> {
  classes: any;
  router: any;

  pagination?: Pagination<object>;
  listCrops: any;
  listAccessions: any;
72
  loadGenesysDescriptors: any;
73
74
75
76
77
78
79
80
81
82
}


const SORT_OPTIONS = null;

// Page to browse and filter descriptor lists
class BrowsePage extends React.Component<IBrowsePageProps, any> {

    protected static needs = [
      listCrops,
83
      loadGenesysDescriptors,
84
85
86
87
88
    ];


    public constructor(props: any) {
        super(props);
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
        this.state = {
          paged: null,
          filter: {},
          displayedColumns: [
            { path: 'acceNumb', width: 200, title: 'Accession number' },
            { path: 'seqNo', width: 100, className: 'text-right', title: 'Seq' },
            { path: 'taxonomy', width: 400, title: 'Scientific name', renderer: (data) => {
              // console.log('Rendering taxonomy', data.taxonomy.sciNameHtml);
              return <span dangerouslySetInnerHTML={ this.htmlTaxa(data.taxonomy.sciNameHtml) } />;
            } },
            { path: 'acceName', width: 400, title: 'Accession name' },
            { path: 'doi', width: 200, title: 'DOI', renderer: (data) => {
              // console.log('Rendering DOI', data.doi);
              return data.doi ? <DOI noPrefix value={ data.doi } /> : null;
            } },
            { path: 'institute.code', width: 100, title: 'Institute code', renderer: (data) => data.institute.code },
            { path: 'institute.name', width: 400, title: 'Institute name', renderer: (data) => data.institute.fullName },
            { path: 'cropName', width: 200, title: 'Crop' },
            { path: 'sampStat', width: 300, title: 'Biological status of sample', renderer: (data) => data.sampStat && this.decode(data.sampStat, 'sampStat') },
          ],
        };

        this._cellRenderer = this._cellRenderer.bind(this);
        this._getColumnWidth = this._getColumnWidth.bind(this);
        this._getRowClassName = this._getRowClassName.bind(this);
        // this._getRowHeight = this._getRowHeight.bind(this);
        this._noContentRenderer = this._noContentRenderer.bind(this);
116
117
118
119
    }


    public componentWillMount() {
120
      const {pagination, listCrops, loadGenesysDescriptors} = this.props;
121
122
123

      log(`BrowsePage.componentWillMount...`, this.props);
      listCrops();
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145

      // Descriptors
      loadGenesysDescriptors()
        .then((genesysMcpd: DescriptorList) => {
          // console.log('Genesys descriptors', g);
          const mapping: Map<string, Descriptor> = new Map<string, Descriptor>();
          const decoder: Map<string, Map<string, VocabularyTerm>> = new Map<string, Map<string, VocabularyTerm>>();
          if (genesysMcpd && genesysMcpd.extras) {
            console.log('Genesys PGR mapping', genesysMcpd.extras[DescriptorListExtra.JSON_MAPPING]);
            for (const m of genesysMcpd.extras[DescriptorListExtra.JSON_MAPPING]) {
              const d = genesysMcpd.descriptors.find((d) => d.uuid === m.uuid);
              mapping.set(m.jsonPath, d);
              if (d && d.terms) {
                decoder.set(m.jsonPath, d.terms.reduce((codes, term) => codes.set(term.code, term), new Map<string, VocabularyTerm>()));
              }
            }
          }
          console.log(mapping, decoder);
          this.setState({ ...this.state, mapping, decoder });
          return genesysMcpd;
        });

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
      // if (! paged) {
      log('Loading genesys accessions');
      this.fetchAccessions(this.state.filter, pagination.page, pagination.size);
      // }
    }

    public componentWillReceiveProps(nextProps) {
        const {pagination: oldPagination} = this.props;
        const {pagination} = nextProps;

        if (! oldPagination.equals(pagination)) {
            log('Paginations differ!', pagination);
            this.fetchAccessions(this.state.filter, pagination.page, pagination.size);
        }
    }

    protected onPaginationChange = (page, results, sortBy, dir) => {
        log('onPaginationChange', page, results, sortBy);
        const {router, router: { location }} = this.props;

        location.query.p = page;
        location.query.l = results;
        location.query.s = sortBy;
        location.query.d = dir;
        router.push(location);
    }

    protected applyFilters = (newFilters) => {
        const {pagination} = this.props;

        log('Applying new filter', newFilters);
        this.fetchAccessions(newFilters, pagination.page, pagination.size);
    }

    private fetchAccessions(filter, page, size) {
      const {listAccessions} = this.props;
      console.log(`Fetching p=${page} l=${size}`, filter);
      listAccessions(filter, page, size)
        .then((data: Page<object>) => {
          this.setState({...this.state, paged: data, filter });
        })
        .catch((error) => {
          console.log(error);
        });
    }

    private htmlTaxa(taxonomyHtml: string) {
      return { __html: taxonomyHtml };
    }

196
197
    private decode(val, path): string {
      if (! val) {
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        return null;
      }
      const { decoder } = this.state;
      if (! decoder) {
        return val;
      }

      const terms = decoder.get(path);
      // console.log(path, terms);
      if (terms) {
        const term = terms.get(`${val}`);
        // console.log(val, term);
        return term ? term.title : val;
      }
      return val;
    }

215
216
    public render() {
        const { classes } = this.props;
217
        const { paged, filter, displayedColumns } = this.state;
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240

        const stillLoading: boolean = (! paged || ! paged.content);

        return (
          <Grid container spacing={ 0 }>
              <Grid item xs={ 12 } md={ 3 } lg={ 2 } className={ classes.filterSection }>
                <GenesysBrowseFilters initialValues={ filter } onSubmit={ this.applyFilters } />
              </Grid>
              <Grid item xs={ 12 } md={ 9 } lg={ 10 } className="back-gray">
                  <Grid container spacing={ 0 }>
                      <Grid item xs={ 12 }>
                          <PaginationComponent pageObj={ paged }
                            onChange={ this.onPaginationChange } displayName="accessions"
                            sortOptions={ SORT_OPTIONS } />
                      </Grid>
                      <Grid item xs={ 12 }>
                          <PrettyFilters
                              filterObj={ filter }
                              onSubmit={ this.applyFilters }
                          />
                      </Grid>
                  </Grid>
                  { stillLoading ? <Loading /> :
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
                    <AutoSizer disableHeight>
                      { ({ width }) => (
                        <VMultiGrid
                          { ...paged.content }
                          fixedRowCount={ 1 }
                          fixedColumnCount={ 1 }
                          cellRenderer={ this._cellRenderer }
                          className={ classes.BodyGrid }
                          columnWidth={ this._getColumnWidth }
                          columnCount={ displayedColumns.length }
                          height={ 800 }
                          noContentRenderer={ this._noContentRenderer }
                          overscanColumnCount={ 1 }
                          overscanRowCount={ 3 }
                          rowHeight={ 36 }
                          rowCount={ paged.content.length }
                          width={ width }
                        />
                      ) }
                    </AutoSizer>
261
262
263
264
265
266
267
268
269
270
271
272
                  }
              </Grid>
              <Grid container spacing={ 0 }>
                  <Grid item xs={ 12 }>
                    <PaginationComponent pageObj={ paged }
                      onChange={ this.onPaginationChange } displayName="accessions"
                      sortOptions={ SORT_OPTIONS } />
                  </Grid>
              </Grid>
          </Grid>
        );
    }
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

    private _cellRenderer({columnIndex, key, rowIndex, style}) {
        if (rowIndex === 0) {
          return this._headerRenderer({columnIndex, key, style});
        }
        const { classes } = this.props;
        const { paged, displayedColumns } = this.state;
        const rowClass = this._getRowClassName(rowIndex);
        const cellClass = displayedColumns[columnIndex].className || '';

        // console.log(`c ${rowIndex},${columnIndex}`, paged.content[rowIndex]);
        return (
          <div key={ key } style={ style } className={ `${classes.tableCell} ${rowClass} ${cellClass}` }>
            { displayedColumns[columnIndex].renderer ?
              displayedColumns[columnIndex].renderer(paged.content[rowIndex - 1])
              :
              paged.content[rowIndex - 1][displayedColumns[columnIndex].path]
            }
          </div>
        );
    }

    private _headerRenderer({columnIndex, key, style}) {
      const { classes } = this.props;
      const { displayedColumns } = this.state;
      const cellClass = displayedColumns[columnIndex].className || '';

      // console.log(`c ${rowIndex},${columnIndex}`, paged.content[rowIndex]);
      return (
        <div key={ key } style={ style } className={ `${classes.tableCell} ${classes.tableHeaderCell} ${cellClass} back-green` }>
          { displayedColumns[columnIndex].title }
        </div>
      );
    }

    private _noContentRenderer() {
      const { classes } = this.props;
      return <div className={ classes.noCells }>No cells</div>;
    }

    private _getColumnWidth({index}) {
      const { displayedColumns } = this.state;
      return displayedColumns[index].width;
    }

    private _getRowClassName(row) {
      const { classes } = this.props;
      return row % 2 === 0 ? classes.evenRow : classes.oddRow;
    }
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
}

const mapStateToProps = (state, ownProps) => ({
  pagination: new Pagination<object>({
    page: +ownProps.location.query.p || 0, // current page
    size: +ownProps.location.query.l || 50, // page size
    sort: ownProps.location.query.s, // page sorts
    dir: ownProps.location.query.d, // page sort directions
    filter: null,
  }),
});

const mapDispatchToProps = (dispatch) => bindActionCreators({
  listCrops,
  listAccessions,
337
  loadGenesysDescriptors,
338
339
340
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(BrowsePage));