-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathindex.tsx
310 lines (268 loc) · 9.92 KB
/
index.tsx
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
import React, { useState, useRef, useEffect, useCallback, createContext, useContext } from 'react';
import styled from 'styled-components';
import Select, { MultiValue } from 'react-select';
import ScrollableAnchor, { goToAnchor } from '../../../vendored/react-scrollable-anchor/index';
import {Tooltip} from 'react-tooltip-v5';
import { createFilterOption, useFilterOptions } from './useFilterOptions';
import { useSortAndFilter } from "./useSortAndFilter";
import { useDataFetch } from "./useDataFetch";
import {Spinner} from '../Spinner/Spinner';
import { ResourceGroup } from './ResourceGroup';
import { ErrorContainer } from "../../pages/404";
import { TooltipWrapper } from "./IndividualResource";
import {ResourceModal, SetModalResourceContext} from "./Modal";
import { CardImgWrapper, CardOuter, Showcase } from "../Showcase";
import { Card } from '../Showcase/types';
import { FilterOption, Group, GroupDisplayNames, QuickLink, Resource } from './types';
import { CardInner, CardTitle } from '../Cards/styles';
interface ListResourcesProps extends ListResourcesResponsiveProps {
elWidth: number
}
const LIST_ANCHOR = "list";
const SetSelectedFilterOptions = createContext<React.Dispatch<React.SetStateAction<readonly FilterOption[]>> | null>(null);
/**
* A React component to fetch data and display the available resources,
* including past versions ("snapshots").
*
* Note that currently this only uses 'dataset' resources. In the future this
* will be expanded. Similarly, we define versioned: boolean here in the UI whereas
* this may be better expressed as a property of the API response.
*/
function ListResources({
sourceId,
versioned=true,
elWidth,
quickLinks,
defaultGroupLinks=false,
groupDisplayNames,
showcase,
}: ListResourcesProps) {
const {groups, dataFetchError} = useDataFetch(sourceId, versioned, defaultGroupLinks, groupDisplayNames);
const showcaseCards = useShowcaseCards(showcase, groups);
const [selectedFilterOptions, setSelectedFilterOptions] = useState<readonly FilterOption[]>([]);
const [sortMethod, changeSortMethod] = useState("alphabetical");
const [resourceGroups, setResourceGroups] = useState<Group[]>([]);
useSortAndFilter(sortMethod, selectedFilterOptions, groups, setResourceGroups)
const availableFilterOptions = useFilterOptions(resourceGroups);
const [modalResource, setModalResource ] = useState<Resource>();
if (dataFetchError) {
return (
<ErrorContainer>
{"Whoops - listing resources isn't working!"}
<br/>
{'Please '}<a href="/contact" style={{fontWeight: 300}}>get in touch</a>{" if this keeps happening"}
</ErrorContainer>
)
}
if (!resourceGroups?.length) {
return (
<div>
<Spinner/>
</div>
)
}
return (
<ListResourcesContainer>
<Byline>
Showcase resources: click to filter the resources to a pathogen
</Byline>
<SetSelectedFilterOptions.Provider value={setSelectedFilterOptions}>
<Showcase cards={showcaseCards} CardComponent={FilterShowcaseTile} />
</SetSelectedFilterOptions.Provider>
<Filter options={availableFilterOptions} selectedFilterOptions={selectedFilterOptions} setSelectedFilterOptions={setSelectedFilterOptions}/>
<SortOptions sortMethod={sortMethod} changeSortMethod={changeSortMethod}/>
<SetModalResourceContext.Provider value={setModalResource}>
<ScrollableAnchor id={LIST_ANCHOR}>
<div>
{resourceGroups.map((group) => (
<ResourceGroup key={group.groupName}
group={group} quickLinks={quickLinks}
elWidth={elWidth}
numGroups={resourceGroups.length}
sortMethod={sortMethod}
/>
))}
</div>
</ScrollableAnchor>
</SetModalResourceContext.Provider>
<Tooltip style={{fontSize: '1.6rem'}} id="listResourcesTooltip"/>
{ versioned && (
<ResourceModal resource={modalResource} dismissModal={() => setModalResource(undefined)}/>
)}
</ListResourcesContainer>
)
}
interface ListResourcesResponsiveProps {
sourceId: string
versioned: boolean
quickLinks: QuickLink[]
/** Should the group name itself be a url? (which we let the server redirect) */
defaultGroupLinks: boolean
groupDisplayNames: GroupDisplayNames
showcase: Card[]
}
/**
* A wrapper element which monitors for resize events affecting the dom element.
* Because of the responsive CSS design in parent components, most of the time
* this only fires as we cross the specified thresholds so there's no need to
* debounce. However when we are below the smallest threshold (currently 768px)
* the resizes happen frequently and debouncing would be better. From limited
* testing it's not too slow and these resizes should be infrequent.
*/
function ListResourcesResponsive(props: ListResourcesResponsiveProps) {
const ref = useRef(null);
const [elWidth, setElWidth] = useState<number>(0);
useEffect(() => {
const observer = new ResizeObserver(([entry]) => {
if (entry) {
// don't do anything if entry is undefined
setElWidth(entry.contentRect.width);
}
});
if (ref.current) {
// don't do anything if ref is undefined
observer.observe(ref.current);
}
return () => {
observer.disconnect();
};
}, []);
return (
<div ref={ref}>
<ListResources {...props} elWidth={elWidth}/>
</div>
)
}
export default ListResourcesResponsive
function SortOptions({sortMethod, changeSortMethod}) {
function onChangeValue(event) {
changeSortMethod(event.target.value);
}
return (
<SortContainer>
Sort pathogens by:
<input id="alphabetical" type="radio" onChange={onChangeValue} value="alphabetical"
checked={"alphabetical"===sortMethod} style={{cursor: "alphabetical"===sortMethod ? 'default' : 'pointer'}}/>
<TooltipWrapper description={'Pathogen groups ordered alphabetically. ' +
'<br/>' +
'Datasets within each group ordered alphabetically.'}>
<label htmlFor='alphabetical' style={{cursor: "alphabetical"===sortMethod ? 'default' : 'pointer'}}>
alphabetical
</label>
</TooltipWrapper>
<input id='lastUpdated' type="radio" onChange={onChangeValue} value="lastUpdated"
checked={"lastUpdated"===sortMethod} style={{cursor: "lastUpdated"===sortMethod ? 'default' : 'pointer'}}/>
<TooltipWrapper description={'Pathogen groups ordered by the most recently updated dataset within that group. ' +
'<br/>' +
'Datasets within each group ordered by their latest update date.'}>
<label htmlFor='lastUpdated' style={{cursor: "lastUpdated"===sortMethod ? 'default' : 'pointer'}}>
most recently updated
</label>
</TooltipWrapper>
</SortContainer>
)
}
interface FilterProps {
options: FilterOption[]
selectedFilterOptions: readonly FilterOption[]
setSelectedFilterOptions: React.Dispatch<React.SetStateAction<readonly FilterOption[]>>
}
function Filter({options, selectedFilterOptions, setSelectedFilterOptions}: FilterProps) {
const onChange = (options: MultiValue<FilterOption>) => {
if (options) {
setSelectedFilterOptions(options)
}
};
return (
<div className="filter">
<Select
placeholder={"Filter by keywords in dataset names"}
isMulti options={options}
value={selectedFilterOptions}
onChange={onChange}
styles={{
// https://react-select.com/styles#inner-components
placeholder: (baseStyles) => ({...baseStyles, fontSize: "1.6rem"}),
input: (baseStyles) => ({...baseStyles, fontSize: "1.6rem"}),
option: (baseStyles) => ({...baseStyles, fontSize: "1.4rem"}),
multiValue: (baseStyles) => ({...baseStyles, fontSize: "1.6rem", backgroundColor: '#f4d5b7'}), // TODO XXX
}}
/>
</div>
)
}
const ListResourcesContainer = styled.div`
font-size: 1.8rem;
color: #4F4B50;
`
const SortContainer = styled.div`
display: flex;
padding-top: 20px;
padding-bottom: 30px;
& input {
margin-left: 20px;
margin-right: 5px;
}
`
const Byline = styled.div`
font-size: 1.6rem;
border-top: 1px rgb(230, 230, 230) solid;
`
/*** SHOWCASE ***/
interface FilterShowcaseTileProps {
card: Card
}
const FilterShowcaseTile = ({ card }: FilterShowcaseTileProps) => {
const setSelectedFilterOptions = useContext(SetSelectedFilterOptions);
if (!setSelectedFilterOptions) {
throw new Error("Usage of this component requires the SetSelectedFilterOptions context to be set.")
}
const filter = useCallback(
() => {
if (!card.filters) {
throw new Error("Cards used in this component are required to have filters.");
}
setSelectedFilterOptions(card.filters.map(createFilterOption));
goToAnchor(LIST_ANCHOR);
},
[setSelectedFilterOptions, card]
)
return (
<CardOuter>
<CardInner>
<div onClick={filter}>
<CardTitle $squashed>
{card.name}
</CardTitle>
<CardImgWrapper filename={card.img}/>
</div>
</CardInner>
</CardOuter>
)
}
/**
* Given a set of user-defined cards, restrict them to the set of cards for
* which the filters are valid given the resources known to the resource listing
* UI
*/
const useShowcaseCards = (cards?: Card[], groups?: Group[]) => {
const [restrictedCards, setRestrictedCards] = useState<Card[]>([]);
useEffect(() => {
if (!cards || !groups) return;
const words = groups.reduce((words, group) => {
for (const resource of group.resources) {
for (const word of resource.nameParts) {
words.add(word);
}
}
return words;
}, new Set<string>());
setRestrictedCards(cards.filter((card) => {
if (!card.filters) {
throw new Error("Cards used in this function are required to have filters.");
}
return card.filters.every((word) => words.has(word))
}));
}, [cards, groups]);
return restrictedCards;
}