aboutsummaryrefslogtreecommitdiff
path: root/src/pages/Questions.tsx
blob: 92b9505e562fc4bc16d567309e5fea198bad62f7 (plain)
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
import {
    BodySubmitProfilingQuestionsProductIdProfilingQuestionsPost,
    ProfilingQuestionsApiFactory,
    UpkQuestionChoice,
    UserQuestionAnswerIn,
} from "@/api";
import React from "react"
import {Card, CardContent, CardFooter, CardHeader, CardTitle} from "@/components/ui/card.tsx";
import {useAppDispatch, useAppSelector} from "@/hooks.ts";
import {addAnswer, Answer, saveAnswer, selectAnswerForQuestion, submitAnswer} from "@/models/answerSlice.ts";
import {useSelector} from "react-redux";
import {Button} from "@/components/ui/button"
import {
    Pagination,
    PaginationContent,
    PaginationItem,
    PaginationLink,
    PaginationNext,
} from "@/components/ui/pagination"
import {Input} from "@/components/ui/input"
import {Badge} from "@/components/ui/badge"
import clsx from "clsx"
import {
    ProfileQuestion,
    selectFirstAvailableQuestion,
    selectNextAvailableQuestion,
    selectQuestions,
    setNextQuestion,
    setQuestionActive
} from "@/models/questionSlice.ts";
import {assert} from "@/lib/utils.ts";
import {motion} from "framer-motion"
import {App} from "../models/app";

const TextEntry: React.FC<{ question: ProfileQuestion }> = ({question}) => {
    const dispatch = useAppDispatch()
    // const selectAnswer = useMemo(() => selectAnswerForQuestion(question), [question]);
    // const selectAnswer = useSelector(selectAnswerForQuestion(question));
    const answer: Answer | undefined = useSelector(selectAnswerForQuestion(question));
    const error: Boolean = answer?.error_msg.length > 0

    const handleInputChange = (event: React.KeyboardEvent<HTMLInputElement>) => {
        const target = event.target as HTMLInputElement;
        dispatch(addAnswer({question, val: target.value as string}))
    };

    return (
        <>
            <Input type="text"
                   id="text-entry-input"
                   aria-describedby=""
                   defaultValue={answer?.values.length ? answer?.values[0] : ""}
                   onKeyUp={handleInputChange}
                   title={error ? answer?.error_msg : ""}
                   className={error ? "border-red-500 focus-visible:ring-red-500" : ""}
            />

            {
                error && <p className="text-sm text-red-500 mt-1">{answer?.error_msg}</p>
            }
        </>

    )
}

const MultiChoiceItem: React.FC<{ question: ProfileQuestion, choice: UpkQuestionChoice }> = ({question, choice}) => {
    const dispatch = useAppDispatch()
    // const selectAnswer = useMemo(() => selectAnswerForQuestion(question), [question]);
    // const answer: Answer = useSelector(selectAnswer);
    const answer: Answer | undefined = useSelector(selectAnswerForQuestion(question));

    const selected: Boolean = (answer?.values || []).includes(choice.choice_id)

    return (
        <li key={choice.choice_id} style={{marginBottom: '0.5rem'}}>
            <Button
                onClick={() => dispatch(addAnswer({question: question, val: choice.choice_id}))}
                className="cursor-pointer"
                variant={selected ? "default" : "secondary"}
            >
                {choice.choice_text}
            </Button>
        </li>
    )
}

const MultipleChoice: React.FC<{ question: ProfileQuestion }> = ({question}) => {
    // const selectAnswer = useMemo(() => selectAnswerForQuestion(question), [question]);
    // const answer: Answer = useSelector(selectAnswer);

    const answer: Answer | undefined = useSelector(selectAnswerForQuestion(question));
    const error: Boolean = answer?.error_msg.length > 0

    return (
        <>
            {
                error && <p className="text-sm text-red-500 mt-1">{answer?.error_msg}</p>
            }

            <ol style={{listStyle: 'none', padding: 0, margin: 0}}>
                {
                    question.choices.map(c => {
                        return <MultiChoiceItem
                            key={`${question.question_id}-${c.choice_id}`}
                            question={question}
                            choice={c}/>
                    })
                }
            </ol>
        </>
    )
}


export const ProfileQuestionFull: React.FC<{
    question: ProfileQuestion, submitAnswerEvt: () => void
}> = ({question, submitAnswerEvt}) => {

    const dispatch = useAppDispatch()

    // const selectAnswer = useMemo(() => selectAnswerForQuestion(question), [question]);
    // const answer: Answer = useSelector(selectAnswer);
    const answer: Answer | undefined = useSelector(selectAnswerForQuestion(question));
    const app: App = useAppSelector(state => state.app)

    const provided_answer = answer?.values.length > 0
    const error: Boolean = answer?.error_msg.length > 0
    const can_submit = provided_answer && !error && !answer?.complete

    const renderContent = () => {
        switch (question.question_type) {
            case 'TE':
                return <TextEntry question={question}/>
            case 'MC':
                return <MultipleChoice question={question}/>
        }
    };


    return (
        <Card className="@container/card relative overflow-hidden my-4 p-5">
            {answer && answer.processing && (
                <motion.div
                    className="absolute top-0 left-0 h-0.5 bg-gray-300"
                    initial={{width: "0%"}}
                    animate={{width: "100%"}}
                    transition={{duration: 1, ease: "easeInOut"}}
                    // onAnimationComplete={() => setLoading(false)}
                />
            )}

            <Badge
                className="absolute top-2 right-2 h-5 min-w-5 rounded-full px-1 font-mono tabular-nums cursor-pointer"
                variant="outline"
                title={`Currently ${(question.importance.task_count ?? 0).toLocaleString()} surveys use this profiling question`}
            >
                {(question.importance?.task_count ?? 0).toLocaleString()}
            </Badge>

            <CardHeader>
                <CardTitle>{question.question_text}</CardTitle>
            </CardHeader>
            <CardContent>
                {renderContent()}
            </CardContent>
            <CardFooter className="flex justify-end">
                <Button
                    type="submit"
                    className="w-1/3 cursor-pointer"
                    disabled={!can_submit}
                    onClick={submitAnswerEvt}
                >
                    Submit
                </Button>
            </CardFooter>
        </Card>
    )
}

const PaginationIcon: React.FC<{
    question: ProfileQuestion, idx: number,
}> = ({question, idx}) => {
    const dispatch = useAppDispatch()

    const answers = useAppSelector(state => state.answers)
    const completed: Boolean = Boolean(answers[question.question_id]?.complete)

    const setQuestion = (evt: React.MouseEvent<HTMLAnchorElement>) => {
        if (completed) {
            evt.preventDefault()
        } else {
            dispatch(setQuestionActive(question))
        }
    }

    return (
        <PaginationItem>
            <PaginationLink
                href="#"
                title={question.question_text}
                isActive={question.active}
                aria-disabled={!!completed}

                onClick={setQuestion}
                className={clsx("cursor-pointer border border-gray-100",
                    {
                        "pointer-events-none opacity-50 cursor-not-allowed": completed,
                        "opacity-100 border-gray-200": question.active,
                    })}
            >
                {idx + 1}
            </PaginationLink>
        </PaginationItem>
    )
}


const QuestionsPage = () => {
    const dispatch = useAppDispatch()

    const questions = useSelector(selectQuestions)
    // @ts-ignore
    const question: ProfileQuestion | null = useSelector(selectFirstAvailableQuestion)
    dispatch(setQuestionActive(question as ProfileQuestion))

    // This is saved now, so that if they click next it's ready. It
    // cannot be done within the click handler.
    // @ts-ignore
    const nextQuestion: ProfileQuestion | null = useSelector(selectNextAvailableQuestion)

    const answer: Answer | undefined = useSelector(selectAnswerForQuestion(question));
    const app: App = useAppSelector(state => state.app)

    const clickNext = () => {
        // TODO: if nextQuestion was already submitted, skip it!
        if (nextQuestion) {
            // TS is not smart enough to know that the if statement above
            // prevents this from ever being null
            dispatch(setQuestionActive(nextQuestion))
        } else {
            // What do we do now... no more questions left to do.
        }
    }

    // All the variables needed for a sliding window
    const q_idx = questions.findIndex(q => q.question_id === question.question_id)
    const questionsWindow = (
        items: ProfileQuestion[], currentIndex: number, windowSize: number = 7
    ): ProfileQuestion[] => {
        const half: number = Math.floor(windowSize / 2)
        const total: number = items.length
        let start: number = currentIndex - half
        let end: number = currentIndex + half + 1

        if (start < 0) {
            end += Math.abs(start)
            start = 0
        }

        // Adjust if window goes past the end
        if (end > total) {
            const overflow: number = end - total
            start = Math.max(0, start - overflow)
            end = total
        }

        return items.slice(start, end)
    }


    const submitAnswerEvt = () => {
        dispatch(submitAnswer({question: question}))

        assert(!answer?.complete, "Can't submit completed Answer")
        assert(!answer?.processing, "Can't submit processing Answer")
        assert(answer?.error_msg.length == 0, "Can't submit Answer with error message")

        let body: BodySubmitProfilingQuestionsProductIdProfilingQuestionsPost = {
            'answers': [{
                "question_id": question.question_id,
                "answer": answer.values
            } as UserQuestionAnswerIn
            ]
        }
        ProfilingQuestionsApiFactory().submitProfilingQuestionsProductIdProfilingQuestionsPost(app.bpid, app.bpuid, body)
            .then(res => {
                if (res.status == 200) {
                    dispatch(saveAnswer({question: question}))
                    dispatch(setNextQuestion())
                } else {
                    // let error_msg = res.data.msg
                }
            })
            .catch(err => console.log(err));
    }


    return (
        <>
            <Pagination className="mt-4 mb-4">
                <PaginationContent>
                    {
                        questionsWindow(questions, q_idx).map(q => {
                            return <PaginationIcon
                                key={q.question_id}
                                question={q}
                                idx={questions.findIndex(qq => qq.question_id === q.question_id)}
                            />
                        })
                    }

                    <PaginationItem>
                        <PaginationNext
                            onClick={clickNext}
                            href="#"
                        />
                    </PaginationItem>
                </PaginationContent>
            </Pagination>

            <ProfileQuestionFull
                key={question.question_id}
                question={question}
                submitAnswerEvt={submitAnswerEvt}
            />
        </>
    )
}

export {
    QuestionsPage
}