-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
493 lines (473 loc) · 14.3 KB
/
index.js
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import React, { useMemo, useEffect, useState } from "react"
import PropTypes from "prop-types"
import { graphql } from "gatsby"
import { useIntl } from "gatsby-plugin-intl"
import fromEntries from "object.fromentries"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import Fuse from "fuse.js"
import Layout from "../components/layout"
import SEO from "../components/seo"
import IntroBanner from "../components/intro-banner"
import FilterDescription from "../components/filter-description"
import ResourceRow from "../components/resource-row"
import CheckboxGroup from "../components/checkbox-group"
import DebouncedInput from "../components/debounced-input"
import ScrollTopButton from "../components/scroll-top-button"
import ToastMessage from "../components/toast-message"
import ReportErrorModal from "../components/report-error-modal"
import { objectFromSearchParams } from "../utils"
import { useDebounce } from "../hooks"
import { DEFAULT_DEBOUNCE } from "../constants"
// Array of ZIP codes for resources that should be checked for city-level resources
import CITY_ZIPS from "../data/city-zips.json"
// Mapping of ZIP codes to arrays of ZIP codes they overlap for proximity search
import ZIP_MAP from "../data/zip-map.json"
export const PAGE_SIZE = 10
const WHAT_OPTIONS = [
"Money",
"Food",
"Housing",
"Health",
"Mental Health",
"Utilities",
"Legal Help",
]
const WHO_OPTIONS = [
"Families",
"Immigrants",
"LGBTQI",
"Business Owners",
"Students",
]
const LANGUAGE_OPTIONS = [
"English",
"Spanish",
"Chinese",
"Arabic",
"Polish",
"Urdu",
"Tagalog",
"Vietnamese",
"Gujarati",
]
export const LEVEL_ENUM = {
State: 1,
County: 2,
City: 3,
Neighborhood: 4,
National: 5,
}
const ZIP_LEVEL_ENUM = {
Neighborhood: 1,
City: 2,
County: 3,
State: 4,
National: 5,
}
export const sortByLevel = levelEnum => (a, b) => {
// Sort first by level, but if that's equal prioritize resources without restrictions
const levelSort = (levelEnum[a.level] || 10) - (levelEnum[b.level] || 10)
return levelSort === 0
? (a.who || []).length - (b.who || []).length
: levelSort
}
export const getFiltersWithValues = filters =>
fromEntries(
Object.entries(filters).filter(
([key, value]) =>
!(Array.isArray(value) && value.length === 0) && value !== ``
)
)
export const applyFilters = (filters, data) => {
const filtered = data.filter(d =>
Object.entries(filters).every(([key, value]) => {
// Ignore search, apply afterwards to save time
if (key === `search`) {
return true
}
if (key === `zip` && value.replace(/\D/g, ``) in ZIP_MAP) {
const zipVal = value.replace(/\D/g, ``)
// Filter out Neighborhood resources if ZIP filtered
// Remove City resources if ZIP outside city
return (
!["City", "Neighborhood"].includes(d.level) ||
(d.level === "City" && CITY_ZIPS.includes(zipVal)) ||
(!!d[key] &&
d.level === "Neighborhood" &&
ZIP_MAP[zipVal].some(z => d[key].includes(z)))
)
} else if (Array.isArray(value)) {
// If data value is array, check for overlap
return Array.isArray(d[key])
? d[key].some(v => value.includes(v))
: value.includes(d[key])
} else if (typeof value === `string`) {
return (d[key] || ``).toLowerCase().includes(value.toLowerCase().trim())
}
return true
})
)
if (filters.search?.trim()) {
return new Fuse(filtered, {
minMatchCharLength: 3,
shouldSort: true,
threshold: 0.3,
distance: 500,
keys: [
`name`,
`description`,
`descriptiones`,
`who`,
`what`,
`languages`,
],
})
.search(filters.search.trim())
.map(({ item }) => item)
} else if (!!filters.zip) {
return filtered.sort(sortByLevel(ZIP_LEVEL_ENUM))
} else {
return filtered
}
}
export const loadQueryParamFilters = (location, filters) =>
fromEntries(
Object.entries(objectFromSearchParams(new URLSearchParams(location.search)))
.filter(([key, value]) => value !== "" && key in filters)
// Ignore non-numbers in initial ZIP query params
.filter(([key, value]) => key !== `zip` || !!value.replace(/\D/g, ""))
.map(([key, value]) =>
Array.isArray(filters[key]) ? [key, value.split(",")] : [key, value]
)
)
const updateQueryParams = (filters, removeKeys) => {
// Retain query params not included in the params we're updating
const initParams = fromEntries(
Object.entries(
objectFromSearchParams(new URLSearchParams(window.location.search))
).filter(([key, _]) => !removeKeys.includes(key))
)
// Merge the existing, unwatched params with the filter params
const params = new URLSearchParams({
...initParams,
...filters,
})
const suffix = params.toString() === `` ? `` : `?${params}`
window.history.replaceState(
{},
window.document.title,
`${window.location.protocol}//${window.location.host}${window.location.pathname}${suffix}`
)
// Fire a custom event so that other components can update params
const event = new CustomEvent("location-search-change")
document.dispatchEvent(event)
}
const sendGaQueryParams = ({ search, what, who, languages, zip }) => {
const filters = [what, who, languages, zip]
.reduce((acc, val) => acc.concat(val), [])
.filter(v => !!v)
if (
typeof window !== "undefined" &&
window.gtag &&
!window.location.host.includes("staging") &&
window.location.search
) {
if (search && search.trim()) {
window.gtag("event", "search", {
event_category: window.location.pathname,
event_label: search.trim(),
})
}
if (filters.length > 0) {
window.gtag("event", "filter", {
event_category: window.location.pathname,
event_label: filters.join(", "),
})
}
} else {
console.log(search, filters)
}
}
const sendGaNextPage = page => {
if (
page > 1 &&
typeof window !== "undefined" &&
window.gtag &&
!window.location.host.includes("staging")
) {
window.gtag("event", "page", {
event_category: window.location.pathname,
event_label: page,
})
} else if (page > 1) {
console.log(page)
}
}
const IndexPage = ({
location,
data: {
site: {
siteMetadata: { reportErrorPath },
},
allAirtable: { edges },
},
}) => {
const defaultFilters = {
search: ``,
zip: ``,
who: [],
what: [],
languages: [],
}
const allResults = useMemo(
() =>
edges
.map(({ node: { recordId, data } }) => ({
id: recordId,
...data,
}))
.sort(sortByLevel(LEVEL_ENUM)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
const [filters, setFilters] = useState(defaultFilters)
const debounceFilters = useDebounce(filters, DEFAULT_DEBOUNCE)
const results = useMemo(
() => applyFilters(getFiltersWithValues(debounceFilters), allResults),
// eslint-disable-next-line react-hooks/exhaustive-deps
[
debounceFilters.search,
debounceFilters.zip,
debounceFilters.what,
debounceFilters.who,
debounceFilters.languages,
]
)
const [expanded, setExpanded] = useState(false)
const [page, setPage] = useState(1)
const [flagId, setFlagId] = useState(``)
const [toast, setToast] = useState(``)
const intl = useIntl()
const translateOptions = options =>
options.map(value => ({ value, label: intl.formatMessage({ id: value }) }))
useEffect(() => {
// Set initial filters from URL params if present
// Moved out of initial state to avoid hydration bugs
// https://stackoverflow.com/a/59653180
const urlFilters = loadQueryParamFilters(location, defaultFilters)
if (Object.keys(getFiltersWithValues(urlFilters)).length) {
setFilters(urlFilters)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
updateQueryParams(getFiltersWithValues(debounceFilters), [
`search`,
`zip`,
`what`,
`who`,
`languages`,
])
sendGaQueryParams(debounceFilters)
if (page !== 1) setPage(1)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
debounceFilters.search,
debounceFilters.zip,
debounceFilters.what,
debounceFilters.who,
debounceFilters.languages,
])
useEffect(() => {
sendGaNextPage(page)
}, [page])
return (
<Layout location={location}>
<SEO
title={`${intl.formatMessage({
id: "meta-title",
})} | ${intl.formatMessage({ id: "city-bureau" })}`}
overrideTitle
lang={intl.locale}
/>
{flagId && (
<ReportErrorModal
reportErrorPath={reportErrorPath}
id={flagId}
onSuccess={() =>
setToast(intl.formatMessage({ id: "flag-resource-success" }))
}
onClose={() => setFlagId(``)}
/>
)}
<ToastMessage show={toast !== ``} onHide={() => setToast(``)}>
{toast}
</ToastMessage>
<main className="main filter-container">
<aside className="section filter-controls">
<div className="filter-header">
<h1 className="header">
{intl.formatMessage({ id: "filter-title" })}
</h1>
<button
type="button"
className="is-hidden-tablet is-primary button"
aria-haspopup="true"
aria-expanded={expanded.toString()}
aria-controls="filter-form"
onClick={() => setExpanded(!expanded)}
>
<FontAwesomeIcon icon="filter" />
{intl.formatMessage({
id: expanded ? "hide-filters" : "show-filters",
})}
</button>
</div>
<form
id="filter-form"
className={expanded ? `` : `is-hidden-mobile`}
method="GET"
name="filter"
role="search"
action=""
>
<div className="filter-group search">
<DebouncedInput
name="search"
id="search"
classNames="search"
inputType="search"
value={filters.search}
label={intl.formatMessage({ id: "search-label" })}
placeholder={intl.formatMessage({ id: "search-label" })}
onChange={search => setFilters({ ...filters, search })}
/>
<FontAwesomeIcon icon="search" />
</div>
<CheckboxGroup
name="what"
label={intl.formatMessage({ id: "what-label" })}
options={translateOptions(WHAT_OPTIONS)}
value={filters.what}
onChange={what => setFilters({ ...filters, what })}
classNames="filter-group"
/>
<div className="filter-group">
<label className="label" htmlFor="zip-search">
{intl.formatMessage({ id: "where-label" })}
</label>
<DebouncedInput
name="zip"
id="zip-search"
inputType="number"
value={filters.zip}
placeholder={intl.formatMessage({
id: "zip-placeholder",
})}
onChange={zip => setFilters({ ...filters, zip })}
/>
</div>
<CheckboxGroup
name="who"
label={intl.formatMessage({ id: "who-label" })}
help={intl.formatMessage({ id: "who-help" })}
options={translateOptions(WHO_OPTIONS)}
value={filters.who}
onChange={who => setFilters({ ...filters, who })}
classNames="filter-group"
/>
<CheckboxGroup
name="languages"
label={intl.formatMessage({ id: "languages-label" })}
options={translateOptions(LANGUAGE_OPTIONS)}
value={filters.languages}
onChange={languages => setFilters({ ...filters, languages })}
classNames="filter-group"
/>
<button
className={`button is-info clear-filters ${
Object.entries(getFiltersWithValues(debounceFilters)).length ===
0
? `is-hidden`
: ``
}`}
type="button"
onClick={() => setFilters(defaultFilters)}
>
{intl.formatMessage({ id: "clear-filters" })}
</button>
</form>
<ScrollTopButton />
</aside>
<div className="section filter-results-section">
<IntroBanner />
<FilterDescription
filters={getFiltersWithValues(debounceFilters)}
count={results.length}
/>
<div className="filter-results">
{results.slice(0, page * PAGE_SIZE).map(result => (
<ResourceRow
key={result.id}
onFlag={() => setFlagId(result.id)}
{...result}
/>
))}
</div>
<div className="filter-results-footer">
{results.length > PAGE_SIZE * page ? (
<button
type="button"
className="button is-primary"
onClick={() => setPage(page + 1)}
>
{intl.formatMessage({ id: "load-more-results" })}
</button>
) : (
``
)}
</div>
</div>
</main>
</Layout>
)
}
IndexPage.propTypes = {
location: PropTypes.object.isRequired,
data: PropTypes.object.isRequired,
}
export const query = graphql`
query {
site {
siteMetadata {
reportErrorPath
}
}
allAirtable {
edges {
node {
recordId
data {
name: Name
link: Link
phone: Phone
email: Email
hours: Hours
address: Address
zip: ZIP
description: Description
descriptiones: Description_ES
who: Who
what: Category
languages: Languages
qualifications: Qualifications
level: Level
lastUpdated: Last_Updated
}
}
}
}
}
`
export default IndexPage