forked from SLoh4137/umcp-tase
-
Notifications
You must be signed in to change notification settings - Fork 2
/
useEvents.tsx
executable file
·101 lines (88 loc) · 3.21 KB
/
useEvents.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
import { useStaticQuery, graphql } from "gatsby"
import { mapImgToNode, NodeWithImage } from "utils/hookUtils"
import { EventsQuery, Maybe } from "graphql-types"
// Type Definitions
type EventEdge = EventsQuery["allMarkdownRemark"]["edges"][0]
type EventNode = EventEdge["node"]
export type EventHookOptions = Readonly<{
tags?: string[]
amount?: number
filterFunctions?: EventFilterFunction[]
}>
export type EventArrayType = ReturnType<typeof useEvents>
export type EventType = EventArrayType[0]
export type ImageType = EventType["image"]
export interface EventFilterFunction {
(edge: EventEdge): boolean
}
/**
* Returns the event and their associated images based on options provided to the hook
*
* @param options Takes a tags array, amount to return, and a filter function. Filter must take an event node and return bool
*/
export default function useEvents(options: EventHookOptions) {
const { tags, amount, filterFunctions } = options
// Because static queries can't have parameters, we have to query for everything
const data = useStaticQuery<EventsQuery>(graphql`
query Events {
allMarkdownRemark(
filter: { frontmatter: { category: { eq: "event" } } }
sort: { order: DESC, fields: frontmatter___date }
) {
edges {
node {
fields {
slug
}
frontmatter {
title
tags
date
category
imgsrc
pinned
link
}
html
excerpt(format: HTML, pruneLength: 300)
id
}
}
}
allFile(
sort: { fields: relativePath, order: ASC }
filter: { absolutePath: { regex: "static/assets/" } }
) {
edges {
node {
id
relativePath
...RaisedImage
}
}
}
}
`)
if (!data.allMarkdownRemark?.edges || !data.allFile?.edges) {
throw new Error("Error in formation of events query")
}
let events = data.allMarkdownRemark.edges
if (tags && tags.length > 0) {
const containsTag = (eventTag: Maybe<string>) => {
return eventTag ? tags?.includes(eventTag) : false
}
// Tags were passed in, so filter based on them
events = data.allMarkdownRemark.edges.filter(
(eventNode) =>
eventNode.node.frontmatter?.tags &&
eventNode.node.frontmatter.tags.some(containsTag)
)
}
if (filterFunctions) {
filterFunctions.forEach((filterFunction) => events = events.filter(filterFunction))
}
const eventsWithPhoto = mapImgToNode<EventNode>(events, data.allFile.edges)
return amount && amount < eventsWithPhoto.length
? eventsWithPhoto.slice(0, amount)
: eventsWithPhoto
}