aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/collections/FlashcardPracticeUI.tsx
blob: 17b65334cdb27e5c19fc2f15bfc089266a18012b (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
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Tooltip } from '@mui/material';
import { MultiToggle, Type } from '@dash/components';
import { computed, makeObservable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { returnFalse, returnZero, setupMoveUpEvents } from '../../../ClientUtils';
import { emptyFunction } from '../../../Utils';
import { Doc, DocListCast, Opt } from '../../../fields/Doc';
import { BoolCast, NumCast, StrCast } from '../../../fields/Types';
import { SnappingManager } from '../../util/SnappingManager';
import { Transform } from '../../util/Transform';
import { ObservableReactComponent } from '../ObservableReactComponent';
import { DocumentView } from '../nodes/DocumentView';
import './FlashcardPracticeUI.scss';
import { StyleProp } from '../StyleProp';
import { FieldViewProps } from '../nodes/FieldView';
import { DocumentViewProps } from '../nodes/DocumentContentsView';

export enum practiceMode {
    PRACTICE = 'practice',
    QUIZ = 'quiz',
}
enum practiceVal {
    MISSED = 'missed',
    CORRECT = 'correct',
}

export enum flashcardRevealOp {
    FLIP = 'flip',
    SLIDE = 'slide',
}

interface PracticeUIProps {
    fieldKey: string;
    layoutDoc: Doc;
    filteredChildDocs: () => Doc[];
    allChildDocs: () => Doc[];
    curDoc: () => Doc | undefined;
    advance?: (correct: boolean) => void;
    renderDepth: number;
    sideBtnWidth: number;
    uiBtnScaling: number;
    ScreenToLocalBoxXf: () => Transform;
    docViewProps: () => DocumentViewProps;
    setFilterFunc: (func?: (doc: Doc) => boolean) => void;
}
@observer
export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProps> {
    constructor(props: PracticeUIProps) {
        super(props);
        makeObservable(this);
        this._props.setFilterFunc(this.tryFilterOut);
    }

    componentWillUnmount(): void {
        this._props.setFilterFunc(undefined);
    }

    get practiceField() { return this._props.fieldKey + "_practice"; } // prettier-ignore

    @computed get filterDoc() { return DocListCast(Doc.MyContextMenuBtns?.data).find(doc => doc.title === 'Filter'); } // prettier-ignore
    @computed get hasFlashcards() { return this._props.allChildDocs().some(doc => doc._layout_flashcardType); } // prettier-ignore
    @computed get practiceMode() { return this.hasFlashcards ? StrCast(this._props.layoutDoc.practiceMode) : ''; } // prettier-ignore

    btnHeight = () => NumCast(this.filterDoc?.height);
    btnWidth = () => (!this.filterDoc ? 1 : NumCast(this.filterDoc._width));

    /**
     * Sets the practice mode answer style for flashcards
     * @param mode practiceMode or undefined for no practice
     */
    setPracticeMode = (mode: practiceMode | undefined) => {
        this._props.layoutDoc.practiceMode = mode;
        this._props.allChildDocs().map(doc => (doc[this.practiceField] = undefined));
    };

    @computed get emptyMessage() {
        const cardCount = this._props.filteredChildDocs().length;
        const practiceMessage = this.practiceMode && !Doc.hasDocFilter(this._props.layoutDoc, 'tags', Doc.FilterAny) && !cardCount ? 'Finished! Click here to view all flashcards.' : '';
        const filterMessage = practiceMessage
            ? ''
            : Doc.hasDocFilter(this._props.layoutDoc, 'tags', Doc.FilterAny) && !cardCount
              ? 'No tagged items. Click here to view all flash cards.'
              : this.practiceMode && !cardCount
                ? 'No flashcards to show! Click here to leave practice mode'
                : '';
        return !practiceMessage && !filterMessage ? null : (
            <p
                className="FlashcardPracticeUI-message"
                style={{ transform: `scale(${this._props.uiBtnScaling})` }}
                onClick={() => {
                    if (filterMessage || practiceMessage) {
                        this.setPracticeMode(undefined);
                        Doc.setDocFilter(this._props.layoutDoc, 'tags', Doc.FilterAny, 'remove');
                    }
                }}>
                {filterMessage || practiceMessage}
            </p>
        );
    }

    @computed get practiceButtons() {
        /*
         * Sets a flashcard to either missed or correct depending on if they got the question right in practice mode.
         */
        const setPracticeVal = (e: React.MouseEvent, val: string) => {
            e.stopPropagation();
            const curDoc = this._props.curDoc();
            this._props.advance?.(val === practiceVal.CORRECT);
            curDoc && (curDoc[this.practiceField] = val);
        };

        return this.practiceMode == practiceMode.PRACTICE && this._props.curDoc() ? (
            <div className="FlashcardPracticeUI-practice" style={{ transform: `scale(${this._props.uiBtnScaling})`, bottom: `${this._props.sideBtnWidth}px`, height: `${this._props.sideBtnWidth}px` }}>
                <Tooltip title="Incorrect. View again later.">
                    <div key="remove" className="FlashcardPracticeUI-remove" onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => setPracticeVal(e, practiceVal.MISSED))}>
                        <FontAwesomeIcon icon="xmark" color="red" size="1x" />
                    </div>
                </Tooltip>
                <Tooltip title="Correct">
                    <div key="check" className="FlashcardPracticeUI-check" onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => setPracticeVal(e, practiceVal.CORRECT))}>
                        <FontAwesomeIcon icon="check" color="green" size="1x" />
                    </div>
                </Tooltip>
            </div>
        ) : null;
    }
    @computed get practiceModesMenu() {
        const setColor = (mode: practiceMode) => (StrCast(this.practiceMode) === mode ? 'white' : 'lightgray');
        const togglePracticeMode = (mode: practiceMode) => this.setPracticeMode(mode === this.practiceMode ? undefined : mode);

        return !this.hasFlashcards ? null : (
            <div
                className="FlashcardPracticeUI-practiceModes"
                style={{
                    background: SnappingManager.userVariantColor,
                }}>
                <MultiToggle
                    tooltip="Practice flashcards one at a time"
                    type={Type.PRIM}
                    color={SnappingManager.userColor}
                    background={SnappingManager.userVariantColor}
                    showUntilToggle={false}
                    multiSelect={false}
                    label="Practice"
                    items={[
                        [practiceMode.QUIZ, 'file-pen', 'Practice flashcards using GPT'],
                        [practiceMode.PRACTICE, 'check', this.practiceMode === practiceMode.PRACTICE ? 'Exit practice mode' : 'Practice flashcards manually'],
                    ].map(([item, icon, tooltip]) => ({
                        icon: <FontAwesomeIcon className={`FlashcardPracticeUI-${item}`} color={setColor(item as practiceMode)} icon={icon as IconProp} size="sm" />,
                        tooltip: tooltip,
                        val: item,
                    }))}
                    selectedItems={this.practiceMode}
                    onSelectionChange={(val: (string | number) | (string | number)[]) => togglePracticeMode(val as practiceMode)}
                />
                <MultiToggle
                    tooltip="How to reveal flashcard answer"
                    type={Type.PRIM}
                    color={SnappingManager.userColor}
                    background={SnappingManager.userVariantColor}
                    showUntilToggle={false}
                    multiSelect={false}
                    label={StrCast(this._props.layoutDoc.revealOp, flashcardRevealOp.FLIP)}
                    items={[
                        ['reveal', StrCast(this._props.layoutDoc.revealOp) === flashcardRevealOp.SLIDE ? 'expand' : 'question', StrCast(this._props.layoutDoc.revealOp, flashcardRevealOp.FLIP)],
                        ['trigger', this._props.layoutDoc.revealOp_hover ? 'hand-point-up' : 'hand', this._props.layoutDoc.revealOp_hover ? 'show on hover' : 'show on click'],
                    ].map(([item, icon, tooltip]) => ({
                        icon: <FontAwesomeIcon className={`FlashcardPracticeUI-${item}`} color={setColor(item as practiceMode)} icon={icon as IconProp} size="sm" />,
                        tooltip: tooltip,
                        val: item,
                    }))}
                    selectedItems={this._props.layoutDoc.revealOp_hover ? ['reveal', 'trigger'] : 'reveal'}
                    onSelectionChange={(val: (string | number) | (string | number)[]) => {
                        if (val === 'reveal') this._props.layoutDoc.revealOp = this._props.layoutDoc.revealOp === flashcardRevealOp.SLIDE ? flashcardRevealOp.FLIP : flashcardRevealOp.SLIDE;
                        if (val === 'trigger') this._props.layoutDoc.revealOp_hover = !this._props.layoutDoc.revealOp_hover;
                    }}
                />
            </div>
        );
    }
    childStyleProvider = (doc: Doc | undefined, props: Opt<FieldViewProps>, property: string) => {
        if (doc instanceof Doc && property === StyleProp.BackgroundColor) {
            return SnappingManager.userVariantColor;
        }
        return this._props.docViewProps().styleProvider?.(doc, props, property);
    };
    tryFilterOut = (doc: Doc) => (this.practiceMode && doc?._layout_flashcardType && doc[this.practiceField] === practiceVal.CORRECT ? true : false); // show only cards that aren't marked as correct
    render() {
        return (
            <div className="FlashcardPracticeUI">
                {this.emptyMessage}
                {this.practiceButtons}
                {this._props.layoutDoc._chromeHidden ? null : (
                    <div className="FlashcardPracticeUI-menu" style={{ height: this.btnHeight(), width: this.btnWidth(), transform: `scale(${this._props.uiBtnScaling})` }}>
                        {!this.filterDoc ? null : (
                            <div style={{ background: SnappingManager.userVariantColor }}>
                                <DocumentView
                                    {...this._props.docViewProps()}
                                    Document={this.filterDoc}
                                    TemplateDataDocument={undefined}
                                    PanelWidth={this.btnWidth}
                                    PanelHeight={this.btnHeight}
                                    NativeWidth={returnZero}
                                    NativeHeight={returnZero}
                                    hideDecorations={BoolCast(this._props.layoutDoc.layout_hideDecorations)}
                                    hideCaptions={true}
                                    hideFilterStatus={true}
                                    renderDepth={this._props.renderDepth + 1}
                                    styleProvider={this.childStyleProvider}
                                    fitWidth={undefined}
                                    showTags={false}
                                    setContentViewBox={undefined}
                                />
                            </div>
                        )}
                        {this.practiceModesMenu}
                    </div>
                )}
            </div>
        );
    }
}