-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrerank.js
227 lines (206 loc) · 9.32 KB
/
rerank.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
// https://github.com/EnCiv/civil-pursuit/issues/61
// https://github.com/EnCiv/civil-pursuit/issues/215
'use strict'
import React, { useState, useEffect, useRef, useContext } from 'react'
import { createUseStyles } from 'react-jss'
import ReviewPoint from '../review-point'
import DeliberationContext from '../deliberation-context'
import { isEqual } from 'lodash'
import ObjectId from 'bson-objectid'
export default function RerankStep(props) {
const { onDone } = props
const { data, upsert } = useContext(DeliberationContext)
const args = { ...derivePointMostsLeastsRankList(data) }
const handleOnDone = ({ valid, value, delta }) => {
if (delta) upsert({ postRankByParentId: { [delta.parentId]: delta } })
onDone({ valid, value })
}
return <Rerank {...props} {...args} onDone={handleOnDone} />
}
// table to map from data model properties, to the Rank Strings shown in the UI
const toRankString = {
undefined: '',
most: 'Most',
least: 'Least',
neutral: 'Neutral',
}
// table to map from UI's Rank Strings to the data model prpoerty names
const rankStringToCategory = Object.entries(toRankString).reduce((rS2C, [key, value]) => {
if (key === 'undefined') return rS2C // rankStringToCategory[''] will be undefined
rS2C[value] = key
return rS2C
}, {})
export function Rerank(props) {
const { reviewPoints, onDone = () => {}, className, round, discussionId, ...otherProps } = props
// this componet manages the rank doc so we keep a local copy
// if it's changed from above, we use the setter to cause a rerender
// if it's chagned from below (by the user) we mutate the state so we don't cause a rerender
const [rankByParentId, setRankByParentId] = useState(
(reviewPoints || []).reduce((rankByParentId, reviewPoint) => {
if (reviewPoint.rank) rankByParentId[reviewPoint.point._id] = reviewPoint.rank
return rankByParentId
}, {})
)
const classes = useStylesFromThemeFunction()
// if reviewPoints are changed from above, we need to set the state and cause rerendering
// if they haven't changed - don't set state - on initial render they won't have changed don't set state
useEffect(() => {
const newRankByParentId = (reviewPoints || []).reduce((rankByParentId, reviewPoint) => {
if (reviewPoint.rank) rankByParentId[reviewPoint.point._id] = reviewPoint.rank
return rankByParentId
}, {})
let updated = false
for (const rankDoc of Object.values(newRankByParentId)) {
if (isEqual(rankDoc, rankByParentId[rankDoc.parentId])) {
newRankByParentId[rankDoc.parentId] = rankByParentId[rankDoc.parentId]
}
// don't change the ref if it hasn't changed in conotent
else updated = true
}
if (updated) {
setRankByParentId(newRankByParentId)
}
// if an item in the updated reviewPoints does not have a rank doc where it previously did, the rank doc will remain.
// deleting a rank is not a use case
}, [reviewPoints])
// first time through should call onDone if there are reviewPoints to notify parent of valid status
useEffect(() => {
if (reviewPoints) {
const percentDone = Object.keys(rankByParentId).length / reviewPoints.length
onDone({ valid: percentDone >= 1, value: percentDone })
}
}, [])
// handle user input from below, keep track of the new values by mutating state - without calling set state and causing a rerender
// call onDone to notify parent of new values, and add the delta prop to pass what's changed to the parent
const handleReviewPoint = (point, result) => {
const rankString = result.value
// the above vars are needed when calling onDone which must be done outside the set function
setRankByParentId(rankByParentId => {
// doing this within the set function because handleReviewPoint could get called multiple time before the next rerender which updates the state value returned by useState
let rank
let percentDone
if (rankByParentId[point._id]) {
if (rankByParentId[point._id].category !== rankStringToCategory[rankString]) {
rank = { ...rankByParentId[point._id], category: rankStringToCategory[rankString] }
rankByParentId[point._id] = rank // mutate the state don't call the set function
percentDone = Object.keys(rankByParentId).length / reviewPoints.length
} else {
percentDone = Object.keys(rankByParentId).length / reviewPoints.length
rank = rankByParentId[point._id]
}
} else {
rank = {
_id: ObjectId().toString(),
stage: 'post',
category: rankStringToCategory[rankString],
parentId: point._id,
round,
discussionId,
}
rankByParentId[point._id] = rank
percentDone = Object.keys(rankByParentId).length / reviewPoints.length
}
if (rank) setTimeout(() => onDone({ valid: percentDone === 1, value: percentDone, delta: rank })) // don't call onDone from within a setter - because onDone's may call other react hooks and react causes errors
return rankByParentId // about the setter
})
}
if (!reviewPoints) return null // nothing ready yet
return (
<div className={classes.reviewPointsContainer} {...otherProps}>
{reviewPoints.map((reviewPoint, idx) => (
<div key={reviewPoint.point._id} className={classes.reviewPoint}>
<ReviewPoint
point={reviewPoint.point}
leftPointList={reviewPoint.mosts}
rightPointList={reviewPoint.leasts}
rank={toRankString[rankByParentId[reviewPoint.point._id]?.category]}
onDone={result => handleReviewPoint(reviewPoint.point, result)}
/>
</div>
))}
</div>
)
}
const useStylesFromThemeFunction = createUseStyles(theme => ({
reviewPointsContainer: {
display: 'flex',
flexDirection: 'column',
gap: '1rem',
},
}))
/*
derives the reviewPoints array from the context
is careful:
not to change the array reference when nothing has changed
to change the array refereance when something has changed, and to only chanage references to the things that have changed
relies on the context, and other functions to only change only the references of things that have changed
keeps a local state that is changed directly to keep track of previous values in order to figure out what's changed
and only change what is different
Input pointList, mosts, whyLeasts, rankDocs
Output: reviewPoints=[{point, mosts, leasts, rankDoc}]
usage
function ReviewStep(props) {
return <ReviewPointList reviewPoints={deriveReviewPoints()} {...props} />
}
*/
// to make is possible to test with jest, this is exported
export function derivePointMostsLeastsRankList(data) {
const local = useRef({ reviewPointsById: {} }).current
const { reducedPointList, postRankByParentId, topWhyById } = data
let updated = false
const { reviewPointsById } = local
if (local.reducedPointList !== reducedPointList) {
for (const { point } of reducedPointList) {
if (!reviewPointsById[point._id]) {
reviewPointsById[point._id] = { point }
updated = true
} else if (reviewPointsById[point._id]?.point !== point) {
reviewPointsById[point._id].point = point
updated = true
}
}
local.reducedPointList = reducedPointList
}
if (local.topWhyById !== topWhyById) {
local.topWhyById = topWhyById
let index
const categoiesToUpdateByParentId = {}
for (const whyPoint of Object.values(topWhyById)) {
if (!reviewPointsById[whyPoint.parentId]) continue // parent not in pointList
const category = whyPoint.category
if ((index = reviewPointsById[whyPoint.parentId][category + 's']?.findIndex(w => w._id === whyPoint._id)) >= 0) {
if (reviewPointsById[whyPoint.parentId][category + 's'][index] !== whyPoint) {
reviewPointsById[whyPoint.parentId][category + 's'][index] = whyPoint
if (!categoiesToUpdateByParentId[whyPoint.parentId]) categoiesToUpdateByParentId[whyPoint.parentId] = []
categoiesToUpdateByParentId[whyPoint.parentId].push(category)
updated = true
} // else no need to update
} else {
if (!reviewPointsById[whyPoint.parentId][category + 's'])
reviewPointsById[whyPoint.parentId][category + 's'] = []
reviewPointsById[whyPoint.parentId][category + 's'].push(whyPoint)
if (!categoiesToUpdateByParentId[whyPoint.parentId]) categoiesToUpdateByParentId[whyPoint.parentId] = []
categoiesToUpdateByParentId[whyPoint.parentId].push(category)
updated = true
}
}
Object.entries(categoiesToUpdateByParentId).forEach(([parentId, categories]) =>
categories.forEach(
category => (reviewPointsById[parentId][category + 's'] = [...reviewPointsById[parentId][category + 's']])
)
)
}
if (local.postRankByParentId !== postRankByParentId) {
for (const rank of Object.values(postRankByParentId)) {
if (reviewPointsById[rank.parentId]) {
if (reviewPointsById[rank.parentId].rank !== rank) {
reviewPointsById[rank.parentId].rank = rank
updated = true
}
} // else some rankDoc's could relate to a whyPoint so do nothing in that case
}
local.postRankByParentId = postRankByParentId
}
if (updated) local.reviewPoints = Object.values(local.reviewPointsById)
return { reviewPoints: local.reviewPoints }
}