aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/formattedText/DailyJournal.tsx
blob: 564609494063498597d4f8e9865d4baa541ca765 (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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import { makeObservable, action, observable } from 'mobx';
import * as React from 'react';
import { Docs } from '../../../documents/Documents';
import { DocumentType } from '../../../documents/DocumentTypes';
import { ViewBoxAnnotatableComponent } from '../../DocComponent';
import { FieldView, FieldViewProps } from '../FieldView';
import { FormattedTextBox, FormattedTextBoxProps } from './FormattedTextBox';
import { gptAPICall, GPTCallType } from '../../../apis/gpt/GPT';
import { RichTextField } from '../../../../fields/RichTextField';
import { Plugin } from 'prosemirror-state';
import { RTFCast } from '../../../../fields/Types';
import { Mark } from 'prosemirror-model';
import { observer } from 'mobx-react';

export class DailyJournal extends ViewBoxAnnotatableComponent<FieldViewProps>() {
    @observable journalDate: string;
    @observable typingTimeout: NodeJS.Timeout | null = null; // track typing delay
    @observable lastUserText: string = ''; // store last user-entered text
    @observable isLoadingPrompts: boolean = false; // track if prompts are loading
    @observable showPromptMenu = false;
    @observable inlinePromptsEnabled = true;
    @observable askPromptsEnabled = true;

    _ref = React.createRef<FormattedTextBox>(); // reference to the formatted textbox
    predictiveTextRange: { from: number; to: number } | null = null; // where predictive text starts and ends
    private predictiveText: string | null = ' ... why?';
    private prePredictiveMarks: Mark[] = [];

    public static LayoutString(fieldStr: string) {
        return FieldView.LayoutString(DailyJournal, fieldStr);
    }

    constructor(props: FormattedTextBoxProps) {
        super(props);
        makeObservable(this);
        this.journalDate = this.getFormattedDate();
    }

    /**
     * Method to get the current date in standard format
     * @returns - date in standard long format
     */

    getFormattedDate(): string {
        const date = new Date().toLocaleDateString(undefined, {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        });
        // console.log('getFormattedDate():', date);
        return date;
    }

    /**
     * Method to set the title of the node to the date
     */
    @action
    setDailyTitle() {
        // console.log('setDailyTitle() called...');
        // console.log('Current title before update:', this.dataDoc.title);

        if (!this.dataDoc.title || this.dataDoc.title !== this.journalDate) {
            // console.log('Updating title to:', this.journalDate);
            this.dataDoc.title = this.journalDate;
        }

        // console.log('New title after update:', this.dataDoc.title);
    }

    /**
     * Method to set the standard text of the node (to the current date)
     */
    @action
    setDailyText() {
        const placeholderText = 'Start writing here...';
        const dateText = `${this.journalDate}\n`;

        // console.log('Checking if dataDoc has text field...');

        this.dataDoc[this.fieldKey] = RichTextField.textToRtfFormat(
            [
                { text: 'Journal Entry:', styles: { bold: true, color: 'black', fontSize: 20 } },
                { text: dateText, styles: { italic: true, color: 'gray', fontSize: 15 } },
                { text: placeholderText, styles: { fontSize: 14, color: 'gray' } },
            ],
            undefined,
            placeholderText.length
        );

        // console.log('Current text field:', this.dataDoc[this.fieldKey]);
    }

    /**
     * Method to show/hide the prompts menu
     */
    @action.bound togglePromptMenu() {
        this.showPromptMenu = !this.showPromptMenu;
    }

    /**
     * Method to toggle on/off inline predictive prompts
     */
    @action.bound toggleInlinePrompts() {
        this.inlinePromptsEnabled = !this.inlinePromptsEnabled;
    }

    /**
     * Method to toggle on/off inline /ask prompts
     */
    @action.bound toggleAskPrompts() {
        this.askPromptsEnabled = !this.askPromptsEnabled;
    }

    /**
     * Method to handle click on document (to close prompt menu)
     * @param e - a click on the document
     */
    @action.bound
    handleDocumentClick(e: MouseEvent) {
        const menu = document.getElementById('prompts-menu');
        const button = document.getElementById('prompts-button');
        if (this.showPromptMenu && menu && !menu.contains(e.target as Node) && button && !button.contains(e.target as Node)) {
            this.showPromptMenu = false;
        }
    }

    /**
     * Method to set initial date of document in the calendar view
     */

    @action setInitialDateRange() {
        if (!this.dataDoc.$task_dateRange && this.journalDate) {
            const parsedDate = new Date(this.journalDate);
            if (!isNaN(parsedDate.getTime())) {
                const localStart = new Date(parsedDate.getFullYear(), parsedDate.getMonth(), parsedDate.getDate());
                const localEnd = new Date(localStart); // same day

                this.dataDoc.$task_dateRange = `${localStart.toISOString()}|${localEnd.toISOString()}`;
                this.dataDoc.$task_allDay = true;
                this.dataDoc.$task = ''; // needed only to make the keyvalue view look good.

                // console.log('Set task_dateRange and task_allDay on journal (from local date):', this.dataDoc.$task_dateRange);
            } else {
                // console.log('Could not parse journalDate:', this.journalDate);
            }
        }
    }

    /**
     * Tracks user typing text inout into the node, to call the insert predicted
     * text function when appropriate (i.e. when the user stops typing)
     */

    @action onTextInput = () => {
        const editorView = this._ref.current?.EditorView;
        if (!editorView) return;

        if (this.typingTimeout) clearTimeout(this.typingTimeout);

        const { state } = editorView;
        const cursorPos = state.selection.from;

        // characters before cursor
        const triggerText = state.doc.textBetween(Math.max(0, cursorPos - 4), cursorPos);

        if (triggerText === '/ask' && this.askPromptsEnabled) {
            // remove /ask text
            const tr = state.tr.delete(cursorPos - 4, cursorPos);
            editorView.dispatch(tr);

            // insert predicted question
            this.insertPredictiveQuestion();
            return;
        }

        this.typingTimeout = setTimeout(() => {
            if (this.inlinePromptsEnabled) {
                this.insertPredictiveQuestion();
            }
        }, 3500);
    };

    /**
     * Inserts predictive text at the end of what the user is typing
     */

    @action insertPredictiveQuestion = async () => {
        const editorView = this._ref.current?.EditorView;
        if (!editorView) return;

        const { state, dispatch } = editorView;
        const { schema } = state;
        const { to } = state.selection;
        const insertPos = to; // cursor position

        const resolvedPos = state.doc.resolve(insertPos);
        const parentNode = resolvedPos.parent;
        const indexInParent = resolvedPos.index();
        const isAtEndOfParent = indexInParent >= parentNode.childCount;

        // Check if there's a line break or paragraph node after the current position
        let hasNewlineAfter = false;
        try {
            const nextNode = parentNode.child(indexInParent);
            hasNewlineAfter = nextNode.type.name === schema.nodes.hard_break.name || nextNode.type.name === schema.nodes.paragraph.name;
        } catch {
            hasNewlineAfter = false;
        }

        // Only insert if we're at end of node, or there's a newline node after
        if (!isAtEndOfParent && !hasNewlineAfter) return;

        // Save current marks at cursor
        const currentMarks = state.storedMarks || resolvedPos.marks();
        this.prePredictiveMarks = [...currentMarks];

        // color and italics are preset for predictive question, font and size are adaptive
        const fontColorMark = schema.marks.pFontColor.create({ fontColor: 'lightgray' });
        const fontItalicsMark = schema.marks.em.create();
        const fontSizeMark = this.prePredictiveMarks.find(m => m.type.name === 'pFontSize');
        const fontFamilyMark = this.prePredictiveMarks.find(m => m.type.name === 'pFontFamily'); // if applicable

        this.predictiveText = ' ...'; // placeholder

        const fullTextUpToCursor = state.doc.textBetween(0, state.selection.to, '\n', '\n');
        const gptPrompt = `Given the following incomplete journal entry, generate a single 2-5 word reflective question that continues the user's thought:\n\n"${fullTextUpToCursor}"`;
        const res = await gptAPICall(gptPrompt, GPTCallType.COMPLETION);
        if (!res) return;

        // styled text node
        const text = ` ... ${res.trim()}`;
        const predictedText = schema.text(text, [fontColorMark, fontItalicsMark, ...(fontSizeMark ? [fontSizeMark] : []), ...(fontFamilyMark ? [fontFamilyMark] : [])]);

        // Insert styled text at cursor position
        const transaction = state.tr.insert(insertPos, predictedText).setStoredMarks(this.prePredictiveMarks);
        dispatch(transaction);

        this.predictiveText = text;
    };

    /**
     * Method to remove the predictive question upon type/click
     * @returns - once predictive text is found, or all text has been checked
     */
    createPredictiveCleanupPlugin = () => {
        return new Plugin({
            view: () => {
                return {
                    update: (view, prevState) => {
                        const { state, dispatch } = view;
                        if (!this.predictiveText) return;

                        // Check if doc or selection changed
                        if (!prevState.doc.eq(state.doc) || !prevState.selection.eq(state.selection)) {
                            const found = false;
                            const textToRemove = this.predictiveText;

                            state.doc.descendants((node, pos) => {
                                if (node.isText && node.text === textToRemove) {
                                    const tr = state.tr.delete(pos, pos + node.nodeSize);

                                    // default marks for input
                                    const fontSizeMark = state.schema.marks.pFontSize.create({ fontSize: '14px' });
                                    const fontColorMark = state.schema.marks.pFontColor.create({ fontColor: 'gray' });
                                    tr.setStoredMarks([]);
                                    if (this.prePredictiveMarks.length > 0) {
                                        tr.setStoredMarks(this.prePredictiveMarks);
                                    } else {
                                        tr.setStoredMarks([fontSizeMark, fontColorMark]);
                                    }

                                    dispatch(tr);

                                    this.predictiveText = null;
                                    this.prePredictiveMarks = [];
                                    return false;
                                }
                                return true;
                            });

                            if (!found) {
                                // fallback cleanup
                                this.predictiveText = null;
                            }
                        }
                    },
                };
            },
        });
    };

    componentDidMount(): void {
        // console.log('componentDidMount() triggered...');
        document.addEventListener('mousedown', this.handleDocumentClick);
        // console.log('Text: ' + RTFCast(this.Document.text)?.Text);

        const editorView = this._ref.current?.EditorView;
        if (editorView) {
            editorView.dom.addEventListener('input', this.onTextInput);

            // Add plugin to state if not already added
            const cleanupPlugin = this.createPredictiveCleanupPlugin();
            this._ref.current?.addPlugin(cleanupPlugin);
        }

        const rawText = RTFCast(this.Document.text)?.Text ?? '';
        const isTextEmpty = !rawText || rawText === '';

        const currentTitle = this.dataDoc.title || '';
        const isTitleString = typeof currentTitle === 'string';
        const isDefaultTitle = isTitleString && currentTitle.includes('Untitled DailyJournal');

        if (isTextEmpty && isDefaultTitle) {
            // console.log('Journal title and text are default. Initializing...');
            this.setDailyTitle();
            this.setDailyText();
            this.setInitialDateRange();
        } else {
            // console.log('Journal already has content. Skipping initialization.');
        }
    }

    componentWillUnmount(): void {
        document.removeEventListener('mousedown', this.handleDocumentClick);
        const editorView = this._ref.current?.EditorView;
        if (editorView) {
            editorView.dom.removeEventListener('input', this.onTextInput);
        }
        if (this.typingTimeout) clearTimeout(this.typingTimeout);
    }

    /**
     * Method to generate pormpts via GPT
     * @returns - if failed
     */
    @action handleGeneratePrompts = async () => {
        if (this.isLoadingPrompts) {
            return;
        }

        this.isLoadingPrompts = true;

        const rawText = RTFCast(this.Document.text)?.Text ?? '';
        // console.log('Extracted Journal Text:', rawText);
        // console.log('Before Update:', this.Document.text, 'Type:', typeof this.Document.text);

        if (!rawText.trim()) {
            alert('Journal is empty! Write something first.');
            return;
        }

        try {
            // Call GPT API to generate prompts
            const res = await gptAPICall('Generate 1-2 short journal prompts for the following journal entry: ' + rawText, GPTCallType.COMPLETION);

            if (!res) {
                console.error('GPT call failed.');
                return;
            }

            const editorView = this._ref.current?.EditorView;
            if (!editorView) {
                console.error('EditorView is not available.');
                return;
            } else {
                const { state, dispatch } = editorView;
                const { schema } = state;

                // Use available marks
                const boldMark = schema.marks.strong.create();
                const italicMark = schema.marks.em.create();
                const fontSizeMark = schema.marks.pFontSize.create({ fontSize: '14px' });
                const fontColorMark = schema.marks.pFontColor.create({ fontColor: 'gray' });

                // Create text nodes with formatting
                const headerText = schema.text('\n\n# Suggested Prompts:\n', [boldMark, italicMark, fontSizeMark, fontColorMark]);
                const responseText = schema.text(res, [fontSizeMark, fontColorMark]);

                // Insert formatted text
                const transaction = state.tr.insert(state.selection.from, headerText).insert(state.selection.from + headerText.nodeSize, responseText);
                dispatch(transaction);
            }
        } catch (err) {
            console.error('Error calling GPT:', err);
        } finally {
            this.isLoadingPrompts = false;
        }
    };

    /**
     * Method to render the styled DailyJournal
     * @returns - the HTML component for the journal
     */
    render() {
        return (
            <div
                style={{
                    // background: 'beige',
                    width: '100%',
                    height: '100%',
                    backgroundColor: 'beige',
                    backgroundImage: `
                    repeating-linear-gradient(
                        to bottom, 
                        rgba(255, 26, 26, 0.2) 0px, rgba(255, 26, 26, 0.2) 1px,  /* Thin red stripes */
                        transparent 1px, transparent 20px
                    )
                `,
                    backgroundSize: '100% 20px',
                    backgroundRepeat: 'repeat',
                }}>
                {/* GPT Button */}
                <button
                    id="prompts-button"
                    style={{
                        position: 'absolute',
                        bottom: '5px',
                        right: '5px',
                        padding: '5px 10px',
                        backgroundColor: '#9EAD7C',
                        color: 'white',
                        border: 'none',
                        borderRadius: '5px',
                        cursor: 'pointer',
                        zIndex: 10,
                    }}
                    onClick={this.togglePromptMenu}>
                    Prompts
                </button>
                {this.showPromptMenu && (
                    <div
                        id="prompts-menu"
                        style={{
                            position: 'absolute',
                            bottom: '45px',
                            right: '5px',
                            backgroundColor: 'white',
                            border: '1px solid #ccc',
                            borderRadius: '4px',
                            padding: '10px',
                            boxShadow: '0 2px 6px rgba(0,0,0,0.2)',
                            zIndex: 20,
                            minWidth: '170px',
                            maxWidth: 'fit-content',
                            overflow: 'auto',
                        }}>
                        <div
                            style={{
                                display: 'flex',
                                justifyContent: 'flex-end',
                                alignItems: 'center',
                                marginBottom: '10px',
                            }}>
                            <label
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '6px',
                                    fontSize: '14px',
                                    justifyContent: 'flex-end',
                                    width: '100%',
                                }}>
                                /ask
                                <input type="checkbox" checked={this.askPromptsEnabled} onChange={this.toggleAskPrompts} style={{ margin: 0 }} />
                            </label>
                        </div>

                        <div
                            style={{
                                display: 'flex',
                                justifyContent: 'flex-end',
                                alignItems: 'center',
                                marginBottom: '10px',
                            }}>
                            <label
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '6px',
                                    fontSize: '14px',
                                    justifyContent: 'flex-end',
                                    width: '100%',
                                }}>
                                Inline Prompting
                                <input type="checkbox" checked={this.inlinePromptsEnabled} onChange={this.toggleInlinePrompts} style={{ margin: 0 }} />
                            </label>
                        </div>

                        <button
                            onClick={() => {
                                this.showPromptMenu = false;
                                this.handleGeneratePrompts();
                            }}
                            disabled={this.isLoadingPrompts}
                            style={{
                                backgroundColor: '#9EAD7C',
                                color: 'white',
                                border: 'none',
                                borderRadius: '4px',
                                cursor: this.isLoadingPrompts ? 'not-allowed' : 'pointer',
                                opacity: this.isLoadingPrompts ? 0.6 : 1,
                                padding: '5px 10px',
                                float: 'right',
                            }}>
                            Generate Prompts
                        </button>
                    </div>
                )}

                <FormattedTextBox ref={this._ref} {...this._props} fieldKey={'text'} Document={this.Document} TemplateDataDocument={undefined} />
            </div>
        );
    }
}

const ObservedDailyJournal = observer(DailyJournal);

Docs.Prototypes.TemplateMap.set(DocumentType.JOURNAL, {
    layout: { view: ObservedDailyJournal, dataField: 'text' },
    options: {
        acl: '',
        _height: 35,
        _xMargin: 10,
        _yMargin: 10,
        _layout_autoHeight: true,
        _layout_nativeDimEditable: true,
        _layout_reflowVertical: true,
        _layout_reflowHorizontal: true,
        defaultDoubleClick: 'ignore',
        systemIcon: 'BsFileEarmarkTextFill',
    },
});