forked from ReactTraining/hooks-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
286 lines (249 loc) · 6.41 KB
/
utils.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
import { db, auth, mode } from "app/db.real.js"
import {
differenceInDays,
startOfWeek,
subDays,
addDays,
format as formatDate
} from "date-fns"
// data model is:
//
// users = [{
// ...auth,
// posts,
// progress,
// expectedProgress,
// goal
// }]
//
// post = [{
// createdAt, // milliseconds
// date, // "YYYY-MM-DD"
// minutes, // int
// uid,
// message
// }]
//
export { auth, db, mode }
export const WORKOUT_DAYS_PER_YEAR = 260
export const DATE_FORMAT = "YYYY-MM-DD"
export function login(email, password) {
return auth().signInWithEmailAndPassword(email, password)
}
export function logout() {
return auth().signOut()
}
export function onAuthStateChanged(callback) {
return auth().onAuthStateChanged(callback)
}
export async function signup({
email,
password,
displayName = "No Name",
photoURL = "https://placekitten.com/200/200",
startDate
}) {
try {
const { user } = await auth().createUserWithEmailAndPassword(
email,
password
)
await user.updateProfile({ displayName, photoURL })
await db.doc(`users/${user.uid}`).set({
displayName: displayName,
uid: user.uid,
photoURL: photoURL,
goal: 8000,
started: formatDate(startDate, DATE_FORMAT)
})
} catch (e) {
throw e
}
}
export const fetchUser = limitCalls(async function fetchUser(uid) {
return fetchDoc(`users/${uid}`)
})
export const fetchDoc = limitCalls(function fetchDoc(path) {
return db
.doc(path)
.get()
.then(doc => doc.data())
})
export const subscribeToPosts = limitCalls(function subscribeToPosts(
uid,
callback
) {
let collection = db
.collection("posts")
.orderBy("createdAt")
.where("uid", "==", uid)
return collection.onSnapshot(snapshot =>
callback(getDocsFromSnapshot(snapshot))
)
})
export const fetchPosts = limitCalls(function fetchPosts(uid) {
return db
.collection("posts")
.orderBy("createdAt")
.where("uid", "==", uid)
.get()
.then(getDocsFromSnapshot)
})
export async function createPost(post) {
return db
.collection("posts")
.add({ createdAt: Date.now(), ...post })
.then(ref => ref.get())
.then(doc => ({ ...doc.data(), id: doc.id }))
}
export function deletePost(id) {
return db.doc(`posts/${id}`).delete()
}
export const getPosts = limitCalls(function getPosts(uid) {
return db
.collection("posts")
.orderBy("createdAt")
.where("uid", "==", uid)
.get()
.then(getDocsFromSnapshot)
})
export const loadFeedPosts = limitCalls(function loadFeedPosts(
createdAtMax,
limit
) {
return db
.collection("posts")
.orderBy("createdAt", "desc")
.where("createdAt", "<", createdAtMax)
.limit(limit)
.get()
.then(getDocsFromSnapshot)
})
export const subscribeToFeedPosts = limitCalls(function subscribeToFeedPosts(
createdAtMax,
limit,
callback
) {
return db
.collection("posts")
.orderBy("createdAt", "desc")
.where("createdAt", "<", createdAtMax)
.limit(limit)
.onSnapshot(snapshot => callback(getDocsFromSnapshot(snapshot)))
})
export const subscribeToNewFeedPosts = limitCalls(
function subscribeToNewFeedPosts(createdAtMin, callback) {
return db
.collection("posts")
.orderBy("createdAt", "desc")
.where("createdAt", ">=", createdAtMin)
.onSnapshot(snapshot => {
callback(getDocsFromSnapshot(snapshot))
})
}
)
export { formatDate }
// Thanks!
// https://stackoverflow.com/questions/1433030/validate-number-of-days-in-a-given-month/1433119#1433119
export function daysInMonth(m, y) {
switch (m) {
case 1:
return (y % 4 === 0 && y % 100) || y % 400 === 0 ? 29 : 28
case 8:
case 3:
case 5:
case 10:
return 30
default:
return 31
}
}
export function isValidDate(year, month, day) {
return month >= 0 && month < 12 && day > 0 && day <= daysInMonth(month, year)
}
export function calculateTotalMinutes(posts) {
return posts.reduce((total, post) => post.minutes + total, 0)
}
export function calculateMakeup(total, expected, goal) {
const minutesPerWorkout = goal / WORKOUT_DAYS_PER_YEAR
const deficit = expected - total
return Math.round(deficit / minutesPerWorkout)
}
export function calculateExpectedMinutes(user) {
const days = differenceInDays(new Date(), user.started)
const perDay = user.goal / WORKOUT_DAYS_PER_YEAR
return Math.round(days * perDay)
}
export function sortByCreatedAtDescending(a, b) {
return b.createdAt - a.createdAt
}
export function calculateWeeks(posts, startDate, numWeeks) {
// ends up like [[s, m, t, w, t, f, s], week, week]
const weeks = []
// ends up like: { "2019-03-19": [post, post] }
const postsByDay = {}
posts.forEach(post => {
if (!postsByDay[post.date]) postsByDay[post.date] = []
postsByDay[post.date].push(post)
})
const startDay = startOfWeek(subDays(startDate, (numWeeks - 1) * 7))
let weekCursor = -1
Array.from({ length: numWeeks * 7 }).forEach((_, index) => {
const date = addDays(startDay, index)
const dayKey = formatDate(date, DATE_FORMAT)
const posts = postsByDay[dayKey] || []
const dayta /*get it?!*/ = { date, posts }
if (index % 7) {
weeks[weekCursor].push(dayta)
} else {
weeks.push([dayta])
weekCursor++
}
})
return weeks
}
function getDataFromDoc(doc) {
return { ...doc.data(), id: doc.id }
}
function getDocsFromSnapshot(snapshot) {
const docs = []
snapshot.forEach(doc => {
docs.push(getDataFromDoc(doc))
})
return docs
}
const easeOut = progress => Math.pow(progress - 1, 5) + 1
export function tween(duration, callback) {
let start = performance.now()
let elapsed = 0
let frame
const tick = now => {
elapsed = now - start
const progress = Math.min(elapsed / duration, 1)
const value = easeOut(progress)
if (progress < 1) {
callback(value)
frame = requestAnimationFrame(tick)
} else {
callback(value, true)
}
}
frame = requestAnimationFrame(tick)
return () => cancelAnimationFrame(frame)
}
function limitCalls(fn, limit = 20) {
let calls = 0
return (...args) => {
calls++
if (calls > limit) {
throw new Error(
`EASY THERE: You've called "${
fn.name
}" too many times too quickly, did you forget the second argument to useEffect? Also, this is a message from Ryan and Michael, not React.`
)
} else {
setTimeout(() => (calls = 0), 3000)
}
return fn(...args)
}
}