aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/collections/CollectionNoteTakingViewColumn.tsx
blob: 624beca96fce29920ad543af4bd0a598d257b68a (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
import React = require('react');
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, computed, observable } from 'mobx';
import { observer } from 'mobx-react';
import { Doc, DocListCast, Opt } from '../../../fields/Doc';
import { Id } from '../../../fields/FieldSymbols';
import { RichTextField } from '../../../fields/RichTextField';
import { SchemaHeaderField } from '../../../fields/SchemaHeaderField';
import { ScriptField } from '../../../fields/ScriptField';
import { ImageField } from '../../../fields/URLField';
import { TraceMobx } from '../../../fields/util';
import { emptyFunction, returnEmptyString, setupMoveUpEvents } from '../../../Utils';
import { Docs, DocUtils } from '../../documents/Documents';
import { DocumentType } from '../../documents/DocumentTypes';
import { DragManager } from '../../util/DragManager';
import { SnappingManager } from '../../util/SnappingManager';
import { Transform } from '../../util/Transform';
import { undoBatch } from '../../util/UndoManager';
import { ContextMenu } from '../ContextMenu';
import { ContextMenuProps } from '../ContextMenuItem';
import { EditableView } from '../EditableView';
import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
import './CollectionNoteTakingView.scss';
import { listSpec } from '../../../fields/Schema';
import { Cast } from '../../../fields/Types';
const higflyout = require('@hig/flyout');
export const { anchorPoints } = higflyout;
export const Flyout = higflyout.default;

// So this is how we are storing a column
interface CSVFieldColumnProps {
    Document: Doc;
    DataDoc: Opt<Doc>;
    docList: Doc[];
    heading: string;
    pivotField: string;
    chromeHidden?: boolean;
    columnHeaders: SchemaHeaderField[] | undefined;
    headingObject: SchemaHeaderField | undefined;
    yMargin: number;
    // columnWidth: number;
    numGroupColumns: number;
    gridGap: number;
    type: 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | undefined;
    headings: () => object[];
    renderChildren: (docs: Doc[]) => JSX.Element[];
    addDocument: (doc: Doc | Doc[]) => boolean;
    createDropTarget: (ele: HTMLDivElement) => void;
    screenToLocalTransform: () => Transform;
    observeHeight: (myref: any) => void;
    unobserveHeight: (myref: any) => void;
    //setDraggedCol:(clonedDiv:any, header:SchemaHeaderField, xycoors: )
    editableViewProps: () => any;
    resizeColumns: (n: number) => void;
    columnStartXCoords: number[];
    PanelWidth: number;
    maxColWidth: number;
    // docsByColumnHeader: Map<string, Doc[]>
    // setDocsForColHeader: (key: string, docs: Doc[]) => void
}

@observer
export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColumnProps> {
    @observable private _background = 'inherit';

    @computed get columnWidth() {
        // base cases
        if (!this.props.columnHeaders || !this.props.headingObject || this.props.columnHeaders.length == 1) {
            return this.props.maxColWidth;
        }
        const i = this.props.columnHeaders.indexOf(this.props.headingObject);
        if (i < 0 || i > this.props.columnStartXCoords.length - 1) {
            return this.props.maxColWidth;
        }
        const endColValue = i == this.props.numGroupColumns - 1 ? this.props.PanelWidth : this.props.columnStartXCoords[i + 1];
        // TODO make the math work here. 35 is half of 70, which is the current width of the divider
        return endColValue - this.props.columnStartXCoords[i] - 30;
    }

    private dropDisposer?: DragManager.DragDropDisposer;
    private _headerRef: React.RefObject<HTMLDivElement> = React.createRef();

    @observable _heading = this.props.headingObject ? this.props.headingObject.heading : this.props.heading;
    @observable _color = this.props.headingObject ? this.props.headingObject.color : '#f1efeb';
    _ele: HTMLElement | null = null;

    // This is likely similar to what we will be doing. Why do we need to make these refs?
    // is that the only way to have drop targets?
    createColumnDropRef = (ele: HTMLDivElement | null) => {
        this.dropDisposer?.();
        if (ele) {
            this._ele = ele;
            this.props.observeHeight(ele);
            this.dropDisposer = DragManager.MakeDropTarget(ele, this.columnDrop.bind(this));
        }
    };

    componentWillUnmount() {
        this.props.unobserveHeight(this._ele);
    }

    @undoBatch
    columnDrop = action((e: Event, de: DragManager.DropEvent) => {
        const drop = { docs: de.complete.docDragData?.droppedDocuments, val: this.getValue(this._heading) };
        drop.docs?.forEach(d => Doc.SetInPlace(d, this.props.pivotField, drop.val, false));
    });

    getValue = (value: string): any => {
        const parsed = parseInt(value);
        if (!isNaN(parsed)) return parsed;
        if (value.toLowerCase().indexOf('true') > -1) return true;
        if (value.toLowerCase().indexOf('false') > -1) return false;
        return value;
    };

    @action
    headingChanged = (value: string, shiftDown?: boolean) => {
        const castedValue = this.getValue(value);
        if (castedValue) {
            if (this.props.columnHeaders?.map(i => i.heading).indexOf(castedValue.toString()) !== -1) {
                return false;
            }
            this.props.docList.forEach(d => (d[this.props.pivotField] = castedValue));
            if (this.props.headingObject) {
                this.props.headingObject.setHeading(castedValue.toString());
                this._heading = this.props.headingObject.heading;
            }
            return true;
        }
        return false;
    };

    @action pointerEntered = () => SnappingManager.GetIsDragging() && (this._background = '#b4b4b4');
    @action pointerLeave = () => (this._background = 'inherit');
    textCallback = (char: string) => this.addNewTextDoc('-typed text-', false, true);

    @action
    addNewTextDoc = (value: string, shiftDown?: boolean, forceEmptyNote?: boolean) => {
        if (!value && !forceEmptyNote) return false;
        const key = this.props.pivotField;
        const newDoc = Docs.Create.TextDocument(value, { _height: 18, _width: 200, _fitWidth: true, title: value, _autoHeight: true });
        const colValue = this.getValue(this.props.heading);
        newDoc[key] = colValue;
        FormattedTextBox.SelectOnLoad = newDoc[Id];
        FormattedTextBox.SelectOnLoadChar = forceEmptyNote ? '' : ' ';
        return this.props.addDocument?.(newDoc) || false;
    };

    @undoBatch
    @action
    deleteColumn = () => {
        const columnHeaders = Cast(this.props.Document.columnHeaders, listSpec(SchemaHeaderField), null);
        if (columnHeaders && this.props.headingObject) {
            const index = columnHeaders.indexOf(this.props.headingObject);
            this.props.docList.forEach(d => (d[this.props.pivotField] = 'unset'));
            columnHeaders.splice(index, 1);
        }
    };

    menuCallback = (x: number, y: number) => {
        ContextMenu.Instance.clearItems();
        const layoutItems: ContextMenuProps[] = [];
        const docItems: ContextMenuProps[] = [];
        const dataDoc = this.props.DataDoc || this.props.Document;
        const pivotValue = this.getValue(this.props.heading);

        DocUtils.addDocumentCreatorMenuItems(
            doc => {
                const key = this.props.pivotField;
                doc[key] = this.getValue(this.props.heading);
                FormattedTextBox.SelectOnLoad = doc[Id];
                return this.props.addDocument?.(doc);
            },
            this.props.addDocument,
            x,
            y,
            true,
            this.props.pivotField,
            pivotValue
        );

        Array.from(Object.keys(Doc.GetProto(dataDoc)))
            .filter(fieldKey => dataDoc[fieldKey] instanceof RichTextField || dataDoc[fieldKey] instanceof ImageField || typeof dataDoc[fieldKey] === 'string')
            .map(fieldKey =>
                docItems.push({
                    description: ':' + fieldKey,
                    event: () => {
                        const created = DocUtils.DocumentFromField(dataDoc, fieldKey, Doc.GetProto(this.props.Document));
                        if (created) {
                            if (this.props.Document.isTemplateDoc) {
                                Doc.MakeMetadataFieldTemplate(created, this.props.Document);
                            }
                            return this.props.addDocument?.(created);
                        }
                    },
                    icon: 'compress-arrows-alt',
                })
            );
        Array.from(Object.keys(Doc.GetProto(dataDoc)))
            .filter(fieldKey => DocListCast(dataDoc[fieldKey]).length)
            .map(fieldKey =>
                docItems.push({
                    description: ':' + fieldKey,
                    event: () => {
                        const created = Docs.Create.CarouselDocument([], { _width: 400, _height: 200, title: fieldKey });
                        if (created) {
                            const container = this.props.Document.resolvedDataDoc ? Doc.GetProto(this.props.Document) : this.props.Document;
                            if (container.isTemplateDoc) {
                                Doc.MakeMetadataFieldTemplate(created, container);
                                return Doc.AddDocToList(container, Doc.LayoutFieldKey(container), created);
                            }
                            return this.props.addDocument?.(created) || false;
                        }
                    },
                    icon: 'compress-arrows-alt',
                })
            );
        !Doc.UserDoc().noviceMode && ContextMenu.Instance.addItem({ description: 'Doc Fields ...', subitems: docItems, icon: 'eye' });
        !Doc.UserDoc().noviceMode && ContextMenu.Instance.addItem({ description: 'Containers ...', subitems: layoutItems, icon: 'eye' });
        ContextMenu.Instance.setDefaultItem('::', (name: string): void => {
            Doc.GetProto(this.props.Document)[name] = '';
            const created = Docs.Create.TextDocument('', { title: name, _width: 250, _autoHeight: true });
            if (created) {
                if (this.props.Document.isTemplateDoc) {
                    Doc.MakeMetadataFieldTemplate(created, this.props.Document);
                }
                this.props.addDocument?.(created);
            }
        });
        ContextMenu.Instance.displayMenu(x, y, undefined, true);
    };

    @computed get innards() {
        TraceMobx();
        const key = this.props.pivotField;
        const heading = this._heading;
        const columnYMargin = this.props.headingObject ? 0 : this.props.yMargin;
        const evContents = heading ? heading : '25';
        const headingView = this.props.headingObject ? (
            <div
                key={heading}
                className="collectionNoteTakingView-sectionHeader"
                ref={this._headerRef}
                style={{
                    marginTop: 2 * this.props.yMargin,
                    // width: (this.props.columnWidth) /
                    //     ((uniqueHeadings.length) || 1)
                    width: this.columnWidth - 20,
                }}>
                <div
                    className="collectionNoteTakingView-sectionHeader-subCont"
                    title={evContents === `No Value` ? `Documents that don't have a ${key} value will go here. This column cannot be removed.` : ''}
                    style={{ background: evContents !== `No Value` ? this._color : 'inherit' }}>
                    <EditableView GetValue={() => evContents} SetValue={this.headingChanged} contents={evContents} oneLine={true} />
                </div>
            </div>
        ) : null;
        // const templatecols = `${this.props.columnWidth / this.props.numGroupColumns}px `;
        const templatecols = `${this.columnWidth}px `;
        const type = this.props.Document.type;
        return (
            <>
                {headingView}
                {
                    <div style={{ height: '100%' }}>
                        <div
                            key={`${heading}-stack`}
                            className={`collectionNoteTakingView-Nodes`}
                            style={{
                                padding: `${columnYMargin}px ${0}px ${this.props.yMargin}px ${0}px`,
                                margin: 'auto',
                                width: 'max-content', //singleColumn ? undefined : `${cols * (style.columnWidth + style.gridGap) + 2 * style.xMargin - style.gridGap}px`,
                                height: 'max-content',
                                position: 'relative',
                                gridGap: this.props.gridGap,
                                gridTemplateColumns: templatecols,
                                gridAutoRows: '0px',
                            }}>
                            {this.props.renderChildren(this.props.docList)}
                        </div>

                        {!this.props.chromeHidden && type !== DocumentType.PRES ? (
                            <div
                                className="collectionNoteTakingView-DocumentButtons"
                                // style={{ width: this.props.columnWidth / this.props.numGroupColumns, marginBottom: 10 }}>
                                style={{ width: this.columnWidth - 20, marginBottom: 10 }}>
                                <div key={`${heading}-add-document`} className="collectionNoteTakingView-addDocumentButton">
                                    <EditableView GetValue={returnEmptyString} SetValue={this.addNewTextDoc} textCallback={this.textCallback} placeholder={"Type ':' for commands"} contents={'+ New Node'} menuCallback={this.menuCallback} />
                                </div>
                                <div key={`${this.props.Document[Id]}-addGroup`} className="collectionNoteTakingView-addDocumentButton">
                                    <EditableView {...this.props.editableViewProps()} />
                                </div>
                                {this.props.columnHeaders?.length && this.props.columnHeaders.length > 1 && (
                                    <button className="collectionNoteTakingView-sectionDelete" onClick={this.deleteColumn}>
                                        <FontAwesomeIcon icon="trash" size="lg" />
                                    </button>
                                )}
                            </div>
                        ) : null}
                    </div>
                }
            </>
        );
    }

    render() {
        TraceMobx();
        const heading = this._heading;
        return (
            <div
                className={'collectionNoteTakingViewFieldColumn' + (SnappingManager.GetIsDragging() ? 'Dragging' : '')}
                key={heading}
                style={{
                    //TODO: change this so that it's based on the column width
                    width: this.columnWidth,
                    background: this._background,
                }}
                ref={this.createColumnDropRef}
                onPointerEnter={this.pointerEntered}
                onPointerLeave={this.pointerLeave}>
                {this.innards}
            </div>
        );
    }
}