CartPage.tsx 5.6 KB
Newer Older
Oleksii Savran's avatar
Oleksii Savran committed
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
import React from 'react';

import { AccessionService } from '@genesys/client/service';
import AccessionFilter from '@genesys/client/model/accession/AccessionFilter';
import Accession from '@genesys/client/model/accession/Accession';
import FilteredPage, { IPageRequest } from '@genesys/client/model/FilteredPage';
import { withTranslation, WithTranslation } from 'react-i18next';
import { LocalStorageCart } from 'utilities';
import { Link } from 'react-router-dom';

interface IAccessionListPageState {
  accessions: FilteredPage<Accession & Record<string, any>>;
  isEmpty: boolean;
  selected: number[];
  isAllSelected: boolean;
}

interface IAccessionListPageProps extends WithTranslation {
  filter?: AccessionFilter;
}

export class AccessionListPage extends React.Component<IAccessionListPageProps, IAccessionListPageState> {
  public constructor(props) {
    super(props);

    this.state = {
      accessions: null,
      isEmpty: false,
      selected: [],
      isAllSelected: false,
    }
  }

  public componentDidMount(): void {
    if (typeof document !== 'undefined') {
      window.addEventListener('storage', this.handleLocalStorageUpdate);
      this.receiveData();
    }
  }

  public componentWillUnmount() {
    if (typeof document !== 'undefined') {
      window.removeEventListener('storage', this.handleLocalStorageUpdate);
    }
  }

  private handleLocalStorageUpdate = (e: StorageEvent) => {
    if (e.key === LocalStorageCart.LS_KEY) {
      this.receiveData();
    }
  };

  private receiveData = () => {
    const accessionsIds = LocalStorageCart.getCartItemsIds();
    if (accessionsIds.length === 0) {
      this.setState({ isEmpty: true, accessions: null });
    } else {
      this.loadData({ id: accessionsIds }, {});
    }
  };

  private loadData = (filter: AccessionFilter, pageR: IPageRequest): Promise<void> => {
    const cartItems = LocalStorageCart.getCartItemsLS();
    const map = new Map();
    cartItems.forEach((item) => map.set(+item.id, item.distributionFormCode));

    return AccessionService
      .list(filter, pageR)
      .then((data: FilteredPage<Accession & any>) => {
        console.log('accessions: ', data);
        data.content.forEach((accession) => accession.distributionFormCode = map.get(accession.id));
        this.setState({ accessions: data, isEmpty: false });
      })
      .catch((e) => {
        console.log('Api call failed: ', e);
      });
  };

  private toggleRowSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { selected } = this.state;
    const { id } = (e.currentTarget as HTMLElement).dataset;
    const updated = selected.filter((selectedId) => selectedId !== +id);
    if (updated.length === selected.length) {
      updated.push(+id);
    }
    this.setState({ selected: updated });
  };

  private removeItems = () => {
    const { selected, accessions } = this.state;
    LocalStorageCart.removeFromCart(selected);
    const accessionsUpdated = { ...accessions, content: accessions.content.filter((acc) => !selected.some((id) => id === acc.id)) };
    const isEmpty = accessionsUpdated.content.length === 0;
    this.setState({ selected: [], accessions: isEmpty ? null : accessionsUpdated, isEmpty, isAllSelected: false });
  };

  private onToggleAll = () => {
    this.setState((prevState) => ({
      isAllSelected: !prevState.isAllSelected,
      selected: !prevState.isAllSelected ? prevState.accessions.content.map((acc) => acc.id) : [],
    }));
  };

  public render() {
    const { accessions, selected, isEmpty, isAllSelected } = this.state;
    const { t } = this.props;
    const selectedIds = new Set();
    selected.forEach((id) => selectedIds.add(id));

    return (
      <>
        <h1 className="d-flex justify-content-between align-items-center">
          { t('cart.title') }
          { selected.length !== 0 &&
            <button type="button" className="btn btn-primary" onClick={ this.removeItems }>
              { t('cart.removeFromCart') }
            </button>
          }
        </h1>
        { isEmpty && <div>{ t('cart.isEmpty') }</div> }
        { accessions && (
          <table className="table table-striped">
            <thead className="thead-dark">
              <tr>
                <th>
                  <input
                    type="checkbox"
                    name="select-all"
                    checked={ isAllSelected }
                    onChange={ this.onToggleAll }
                    className="align-middle"
                  />
                </th>
                <th>{ t('accession.model') }</th>
                <th>{ t('accession.accessionName') }</th>
                <th>{ t('accession.countryOfOrigin') }</th>
              </tr>
            </thead>
            <tbody>
              { accessions.content.map((a, i) => (
                <tr key={ a.id } className={ selectedIds.has(a.id) ? 'table-primary' : '' }>
                  <td>
                    <input
                      type="checkbox"
                      name={ `checkbox-${a.id}-${i}` }
                      data-id={ a.id }
                      checked={ selectedIds.has(a.id) }
                      onChange={ this.toggleRowSelect }
                      className="align-middle"
                    />
                  </td>
                  <td><Link to={ `/a/${a.id}` }>{ a.accessionNumber }</Link></td>
                  <td>{ a.accessionName }</td>
                  <td>{ a.countryOfOrigin && a.countryOfOrigin.name }</td>
                </tr>
              )) }
            </tbody>
          </table>
        ) }
        { !isEmpty && !accessions && <div>{t('common.loading')}...</div> }
      </>
    );
  };
}

export default withTranslation()(AccessionListPage)