aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/collections/CollectionCarouselView.tsx
blob: ba7c944a09585786e14c1f2dc6f394c63f3daaab (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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/* eslint-disable react/jsx-props-no-spreading */
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Tooltip } from '@mui/material';
import { action, computed, makeObservable, observable, trace } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { StopEvent, returnFalse, returnOne, returnTrue, returnZero } from '../../../ClientUtils';
import { emptyFunction } from '../../../Utils';
import { Doc, Opt } from '../../../fields/Doc';
import { DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
import { DocumentType } from '../../documents/DocumentTypes';
import { Docs } from '../../documents/Documents';
import { DragManager } from '../../util/DragManager';
import { StyleProp } from '../StyleProp';
import { DocumentView } from '../nodes/DocumentView';
import { FieldViewProps } from '../nodes/FieldView';
import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
import './CollectionCarouselView.scss';
import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';

enum cardMode {
    // PRACTICE = 'practice',
    STAR = 'star',
    // QUIZ = 'quiz',
    ALL = 'all',
}
enum practiceMode {
    PRACTICE = 'practice',
    QUIZ = 'quiz',
    NORMAL = 'normal',
}
enum practiceVal {
    MISSED = 'missed',
    CORRECT = 'correct',
}
@observer
export class CollectionCarouselView extends CollectionSubView() {
    private _dropDisposer?: DragManager.DragDropDisposer;
    @observable private _practiceMessage: string | undefined;
    @observable private _filterMessage: string | undefined;
    get practiceField() { return this.fieldKey + "_practice"; } // prettier-ignore
    get sideField() { return "_" + this.fieldKey + "_usePath"; } // prettier-ignore
    get starField()     { return "star"; } // prettier-ignore

    constructor(props: SubCollectionViewProps) {
        super(props);
        makeObservable(this);
        // this.setModes();
        this.layoutDoc.filterOp = cardMode.ALL;
        Doc.setDocFilter(this.Document, 'star', undefined, 'match');
        this.layoutDoc.practiceMode = practiceMode.NORMAL;
        this.layoutDoc._carousel_index = 0;
        this.carouselItems.forEach(item => { item.layout[this.practiceField] = undefined}); //prettier-ignore
        console.log(this.carouselItems.length);
    }

    componentWillUnmount() {
        this._dropDisposer?.();
    }

    protected createDashEventsTarget = (ele: HTMLDivElement | null) => {
        this._dropDisposer?.();
        if (ele) {
            this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc);
        }
    };

    @computed get carouselItems() {
        this.childLayoutPairs.map(pair => {
            pair.layout.embedContainer = this.Document;
        });
        return this.childLayoutPairs.filter(pair => pair.layout.type !== DocumentType.LINK);
    }
    @computed get marginX() {
        return NumCast(this.layoutDoc.caption_xMargin, 50);
    }

    @action setPracticeMessage = (mes: string | undefined) => {
        this._practiceMessage = mes;
    };
    @action setFilterMessage = (mes: string | undefined) => {
        this._filterMessage = mes;
    };

    setModes = () => {
        this.layoutDoc.filterOp = cardMode.ALL;
        Doc.setDocFilter(this.Document, 'data_star', undefined, 'match');
        this.layoutDoc.practiceMode = practiceMode.NORMAL;
        this.layoutDoc._carousel_index = 0;
    };

    move = (dir: number) => {
        const moveToCardWithField = (match: (doc: Doc) => boolean): boolean => {
            let startInd = (NumCast(this.layoutDoc._carousel_index) + dir) % this.carouselItems.length;
            while (!match(this.carouselItems?.[startInd].layout) && (startInd + this.carouselItems.length) % this.carouselItems.length !== this.layoutDoc._carousel_index) {
                startInd = (startInd + dir + this.carouselItems.length) % this.carouselItems.length;
            }
            if (match(this.carouselItems?.[startInd].layout)) {
                this.layoutDoc._carousel_index = startInd;
                return true;
            }
            return match(this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)].layout);
        };

        switch (this.layoutDoc.practiceMode && this.layoutDoc.filterOp) {
            case practiceMode.PRACTICE && cardMode.ALL:
                if (!moveToCardWithField((doc: Doc) => doc[this.practiceField] !== practiceVal.CORRECT)) {
                    this._practiceMessage = 'Finished! Unselect practice mode to view all flashcards.';
                    this.carouselItems.forEach(item => { item.layout[this.practiceField] = undefined}); //prettier-ignore
                }
                break;
            case !practiceMode.PRACTICE && cardMode.STAR:
                if (!moveToCardWithField((doc: Doc) => !!doc[this.starField])) {
                    this._filterMessage = 'No starred items. Unselect this view to see all flashcards and star them.';
                }
                break;
            case practiceMode.PRACTICE && cardMode.STAR:
                if (!moveToCardWithField((doc: Doc) => doc[this.practiceField] !== practiceVal.CORRECT && doc[this.starField] === true)) {
                    this._filterMessage = 'No flashcards to show! Unselect mode to view all flashcards.';
                    this._practiceMessage = undefined;
                }
                break;
            default:
                moveToCardWithField(returnTrue);
        }
    };

    /**
     * Goes to the next Doc in the stack subject to the currently selected filter option.
     */
    advance = (e: React.MouseEvent) => {
        e.stopPropagation();
        this.move(1);
    };

    /**
     * Goes to the previous Doc in the stack subject to the currently selected filter option.
     */
    goback = (e: React.MouseEvent) => {
        e.stopPropagation();
        this.move(-1);
    };

    /*
     * Stars the document when the star button is pressed.
     */
    star = (e: React.MouseEvent) => {
        e.stopPropagation();
        const curDoc = this.carouselItems[NumCast(this.layoutDoc._carousel_index)];
        curDoc.layout[this.starField] = curDoc.layout[this.starField] ? undefined : true;
        // if (!curDoc.layout[this.starField]) this.move(1);
        // this.layoutDoc._carousel_index = undefined;
    };

    /*
     * Sets a flashcard to either missed or correct depending on if they got the question right in practice mode.
     */
    setPracticeVal = (e: React.MouseEvent, val: string) => {
        e.stopPropagation();
        const curDoc = this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)];
        curDoc.layout[this.practiceField] = val;
        this.advance(e);
    };

    captionStyleProvider = (doc: Doc | undefined, captionProps: Opt<FieldViewProps>, property: string) => {
        // first look for properties on the document in the carousel, then fallback to properties on the container
        const childValue = doc?.['caption_' + property] ? this._props.styleProvider?.(doc, captionProps, property) : undefined;
        return childValue ?? this._props.styleProvider?.(this.layoutDoc, captionProps, property);
    };
    panelHeight = () => this._props.PanelHeight() - (StrCast(this.layoutDoc._layout_showCaption) ? 50 : 0);
    onContentDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick);
    onContentClick = () => ScriptCast(this.layoutDoc.onChildClick);
    captionWidth = () => this._props.PanelWidth() - 2 * this.marginX;

    setPracticeMode = (mode: practiceMode) => {
        this.layoutDoc.practiceMode = mode;
        this.carouselItems?.map(doc => (doc.layout[this.practiceField] = undefined));
        switch (mode) {
            case practiceMode.QUIZ:
                this.carouselItems?.map(doc => (doc.layout[this.sideField] = undefined));
                break;
            case practiceMode.NORMAL:
                this.setPracticeMessage(undefined);
                break;
        }
    };

    setFilterMode = (mode: cardMode) => {
        this.layoutDoc.filterOp = mode;
        switch (mode) {
            case cardMode.STAR:
                // Doc.setDocFilter(this.Document, 'data_star', true, 'match');
                this.move(1);
                break;
            default:
                this.setFilterMessage(undefined); // prettier-ignore
            // Doc.setDocFilter(this.Document, 'data_star', true, 'remove');
        }
    };

    @computed get content() {
        trace();
        if (this.layoutDoc._carousel_index === this.carouselItems.length && this.layoutDoc._carousel_index !== 0) {
            this.move(1);
        }
        const index = NumCast(this.layoutDoc._carousel_index);
        const curDoc = this.carouselItems?.[index];
        const captionProps = { ...this._props, NativeScaling: returnOne, PanelWidth: this.captionWidth, fieldKey: 'caption', setHeight: undefined, setContentView: undefined };
        const carouselShowsCaptions = StrCast(this.layoutDoc._layout_showCaption);

        return !(curDoc?.layout instanceof Doc) ? null : (
            <>
                <div className="collectionCarouselView-image" key="image">
                    <DocumentView
                        {...this._props}
                        NativeWidth={returnZero}
                        NativeHeight={returnZero}
                        fitWidth={undefined}
                        setContentViewBox={undefined}
                        childFilters={this.childDocFilters}
                        onDoubleClickScript={this.onContentDoubleClick}
                        onClickScript={this.onContentClick}
                        isDocumentActive={this._props.childDocumentsActive?.() ? this._props.isDocumentActive : this._props.isContentActive}
                        isContentActive={(this._props.childContentsActive ?? this._props.isContentActive() === false) ? returnFalse : emptyFunction}
                        addDocument={this._props.addDocument}
                        hideCaptions={!!carouselShowsCaptions} // hide captions if the carousel is configured to show the captions
                        renderDepth={this._props.renderDepth + 1}
                        LayoutTemplate={this._props.childLayoutTemplate}
                        LayoutTemplateString={this._props.childLayoutString}
                        Document={curDoc.layout}
                        TemplateDataDocument={DocCast(curDoc.layout.resolvedDataDoc)}
                        PanelHeight={this.panelHeight}
                    />
                </div>
                {!carouselShowsCaptions ? null : (
                    <div
                        className="collectionCarouselView-caption"
                        key="caption"
                        onWheel={StopEvent}
                        style={{
                            borderRadius: this._props.styleProvider?.(this.layoutDoc, captionProps, StyleProp.BorderRounding) as string,
                            marginRight: this.marginX,
                            marginLeft: this.marginX,
                            width: `calc(100% - ${this.marginX * 2}px)`,
                        }}>
                        <FormattedTextBox key={index} {...captionProps} fieldKey={carouselShowsCaptions} styleProvider={this.captionStyleProvider} Document={curDoc.layout} TemplateDataDocument={undefined} />
                    </div>
                )}
            </>
        );
    }

    containsDifTypes = (): boolean => {
        return this.carouselItems.filter(doc => !doc.layout._layout_isFlashcard).length !== 0;
    };

    addFlashcard() {
        const newDoc = Docs.Create.ComparisonDocument('', { _layout_isFlashcard: true, _width: 300, _height: 300 });
        this.addDocument?.(newDoc);
        // DocUtils.copyDragFactory(newDoc);
        // this._props.addDocument?.();
        // newDoc.layout = this.layoutDoc;
        // newDoc.data = this.dataDoc;
        // Doc.AddDocToList()
        // this._props.parent._props.addDocument();
        // this.childLayoutPairs.push({ newDoc.layout, newDoc.data});
        // this._props.addDocument?.(newDoc);
        // console.log('HERE');
    }

    @computed get buttons() {
        if (!this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)]) return null;
        return (
            <>
                <div key="back" className="carouselView-back" onClick={this.goback}>
                    <FontAwesomeIcon icon="chevron-left" size="2x" />
                </div>
                <div key="fwd" className="carouselView-fwd" onClick={this.advance}>
                    <FontAwesomeIcon icon="chevron-right" size="2x" />
                </div>
                {!this.containsDifTypes() ? (
                    <div>
                        <Tooltip title="star">
                            <div key="star" className="carouselView-star" onClick={this.star}>
                                <FontAwesomeIcon icon="star" color={this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)].layout[this.starField] ? 'yellow' : 'gray'} size="1x" />
                            </div>
                        </Tooltip>
                        {/* <Tooltip title="add new flashcard to pile">
                            <div key="add" className="carouselView-add" onClick={this.addFlashcard}>
                                <FontAwesomeIcon icon="plus" color={this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)].layout[this.starField] ? 'yellow' : 'gray'} size="1x" />
                            </div>
                        </Tooltip> */}
                    </div>
                ) : null}
                {this.layoutDoc.practiceMode === practiceMode.PRACTICE ? (
                    <div>
                        <Tooltip title="Incorrect. View again later.">
                            <div key="remove" className="carouselView-remove" onClick={e => this.setPracticeVal(e, practiceVal.MISSED)}>
                                <FontAwesomeIcon icon="xmark" color="red" size="1x" />
                            </div>
                        </Tooltip>
                        <Tooltip title="Correct">
                            <div key="check" className="carouselView-check" onClick={e => this.setPracticeVal(e, practiceVal.CORRECT)}>
                                <FontAwesomeIcon icon="check" color="green" size="1x" />
                            </div>
                        </Tooltip>
                    </div>
                ) : null}
            </>
        );
    }

    togglePracticeMode = (mode: practiceMode) => {
        if (mode === this.layoutDoc.practiceMode) {
            this.setPracticeMode(practiceMode.NORMAL);
            // this.setPracticeMessage("undefined");
        } else this.setPracticeMode(mode);
    };
    toggleFilterMode = () => { this.layoutDoc.filterOp === cardMode.STAR ? this.setFilterMode(cardMode.ALL) : this.setFilterMode(cardMode.STAR)}; //prettier-ignore
    setColor = (mode: practiceMode | cardMode, which: string) => { return which === mode ? 'white' : 'light gray'}; //prettier-ignore

    @computed get menu() {
        return (
            <div className="carouselView-menu">
                <Tooltip title="Practice flashcards using GPT">
                    <div key="back" className="carouselView-quiz" onClick={e => this.togglePracticeMode(practiceMode.QUIZ)}>
                        <FontAwesomeIcon icon="file-pen" color={this.setColor(practiceMode.QUIZ, StrCast(this.layoutDoc.practiceMode))} size="1x" />
                    </div>
                </Tooltip>
                <Tooltip title={this.layoutDoc.practiceMode === practiceMode.PRACTICE ? 'Exit practice mode' : 'Practice flashcards manually'}>
                    <div key="back" className="carouselView-practice" onClick={e => this.togglePracticeMode(practiceMode.PRACTICE)}>
                        <FontAwesomeIcon icon="check" color={this.setColor(practiceMode.PRACTICE, StrCast(this.layoutDoc.practiceMode))} size="1x" />
                    </div>
                </Tooltip>
                <Tooltip title={this.layoutDoc.filterOp === cardMode.STAR ? 'Show all cards' : 'Show only starred cards'}>
                    <div key="back" className="carouselView-starFilter" onClick={e => this.toggleFilterMode()}>
                        <FontAwesomeIcon icon="filter" color={this.setColor(cardMode.STAR, StrCast(this.layoutDoc.filterOp))} size="1x" />
                    </div>
                </Tooltip>
            </div>
        );
    }

    render() {
        return (
            <div
                className="collectionCarouselView-outer"
                ref={this.createDashEventsTarget}
                style={{
                    background: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BackgroundColor) as string,
                    color: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color) as string,
                }}>
                {!this._practiceMessage && !this._filterMessage ? (
                    this.content
                ) : (
                    <p className="message">
                        {this._filterMessage}
                        {'\n'}
                        {this._practiceMessage}
                    </p>
                )}
                {!this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)] && this.layoutDoc.practiceMode === practiceMode.PRACTICE ? <p className="message">Add flashcards </p> : null}
                <p
                    className="missed-message"
                    style={{
                        color: 'red',
                        fontWeight: 'bold',
                        zIndex: '999',
                        position: 'relative',
                        left: '10px',
                        top: '10px',
                        width: '10px',
                        display: this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)]
                            ? this.carouselItems?.[NumCast(this.layoutDoc._carousel_index)].layout[this.practiceField] === practiceVal.MISSED && this.layoutDoc.practiceMode === practiceMode.PRACTICE && !this._practiceMessage
                                ? 'block'
                                : 'none'
                            : 'none',
                    }}>
                    Recently missed!
                </p>
                {!this.containsDifTypes() && this.carouselItems.length !== 0 ? this.menu : null}
                {this.Document._chromeHidden || (!this._filterMessage && !this._practiceMessage) ? this.buttons : null}
            </div>
        );
    }
}