aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/DocumentContentsView.tsx
blob: 504c1491e3e30fbff214a91710e4631ead9556da (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
import { computed, makeObservable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import * as XRegExp from 'xregexp';
import { OmitKeys } from '../../../ClientUtils';
import { Without } from '../../../Utils';
import { Doc, Opt } from '../../../fields/Doc';
import { AclPrivate, DocData } from '../../../fields/DocSymbols';
import { ScriptField } from '../../../fields/ScriptField';
import { Cast, DocCast, StrCast } from '../../../fields/Types';
import { GetEffectiveAcl, TraceMobx } from '../../../fields/util';
import { ObservableReactComponent, ObserverJsxParser } from '../ObservableReactComponent';
import './DocumentView.scss';
import { FieldViewProps, FieldViewSharedProps } from './FieldView';
import { DragManager } from '../../util/DragManager';
import { dropActionType } from '../../util/DropActionTypes';
import { Property } from 'csstype';

interface DocOnlyProps {
    LayoutTemplate?: () => Opt<Doc>;
    LayoutTemplateString?: string;
    hideDecorations?: boolean; // whether to suppress all DocumentDecorations when doc is selected
    hideResizeHandles?: boolean; // whether to suppress resized handles on doc decorations when this document is selected
    hideTitle?: boolean; // forces suppression of title. e.g, treeView document labels suppress titles in case they are globally active via settings
    hideDecorationTitle?: boolean; // forces suppression of title. e.g, treeView document labels suppress titles in case they are globally active via settings
    hideDocumentButtonBar?: boolean;
    hideOpenButton?: boolean;
    hideDeleteButton?: boolean;
    hideLinkAnchors?: boolean;
    hideLinkButton?: boolean;
    hideCaptions?: boolean;
    contentPointerEvents?: Property.PointerEvents | undefined; // pointer events allowed for content of a document view.  eg. set to "none" in menuSidebar for sharedDocs so that you can select a document, but not interact with its contents
    dontCenter?: 'x' | 'y' | 'xy';
    showTags?: boolean;
    showAIEditor?: boolean;
    hideFilterStatus?: boolean;
    childHideDecorationTitle?: boolean;
    childHideResizeHandles?: boolean;
    childDragAction?: dropActionType; // allows child documents to be dragged out of collection without holding the embedKey or dragging the doc decorations title bar.
    dragWhenActive?: boolean;
    dontHideOnDrag?: boolean;
    onClickScriptDisable?: 'never' | 'always'; // undefined = only when selected
    DataTransition?: () => string | undefined;
    NativeWidth?: () => number;
    NativeHeight?: () => number;
    contextMenuItems?: () => { script?: ScriptField; method?: () => void; filter?: ScriptField; label: string; icon: string }[];
    dragConfig?: (data: DragManager.DocumentDragData) => void;
    dragStarting?: () => void;
    dragEnding?: () => void;

    reactParent?: React.Component; // parent React component view (see CollectionFreeFormDocumentView)
}
const DocOnlyProps = [
    'layoutFieldKey',
    'LayoutTemplate',
    'LayoutTemplateString',
    'hideDecorations', // whether to suppress all DocumentDecorations when doc is selected
    'hideResizeHandles', // whether to suppress resized handles on doc decorations when this document is selected
    'hideTitle', // forces suppression of title. e.g, treeView document labels suppress titles in case they are globally active via settings
    'hideDecorationTitle', // forces suppression of title. e.g, treeView document labels suppress titles in case they are globally active via settings
    'hideDocumentButtonBar',
    'hideOpenButton',
    'hideDeleteButton',
    'hideLinkAnchors',
    'hideLinkButton',
    'hideCaptions',
    'contentPointerEvents', // pointer events allowed for content of a document view.  eg. set to "none" in menuSidebar for sharedDocs so that you can select a document, but not interact with its contents
    'dontCenter',
    'showTags',
    'showAIEditor',
    'hideFilterStatus',
    'childHideDecorationTitle',
    'childHideResizeHandles',
    'childDragAction', // allows child documents to be dragged out of collection without holding the embedKey or dragging the doc decorations title bar.
    'dragWhenActive',
    'dontHideOnDrag',
    'onClickScriptDisable', // undefined = only when selected
    'DataTransition',
    'NativeWidth',
    'NativeHeight',
    'contextMenuItems',
    'dragConfig',
    'dragStarting',
    'dragEnding',

    'reactParent', // parent React component view (see CollectionFreeFormDocumentView)
];

export interface DocumentViewProps extends DocOnlyProps, FieldViewSharedProps {}

type BindingProps = Without<FieldViewProps, 'fieldKey'>;
interface JsxBindings {
    props: BindingProps;
}

interface HTMLtagProps {
    Document: Doc;
    htmltag: string;
    onClick?: ScriptField;
    onInput?: ScriptField;
    children?: JSX.Element[];
}

// "<HTMLdiv borderRadius='100px' onClick={this.bannerColor=this.bannerColor==='red'?'green':'red'} overflow='hidden' position='absolute' width='100%' height='100%' transform='rotate({2*this.x+this.y}deg)'> <ImageBox {...props} fieldKey={'data'}/> <HTMLspan width='200px' top='0' height='35px' textAlign='center' paddingTop='10px' transform='translate(-40px, 45px) rotate(-45deg)' position='absolute' color='{this.bannerColor===`green`?`light`:`dark`}blue' backgroundColor='{this.bannerColor===`green`?`dark`:`light`}blue'> {this.title}</HTMLspan></HTMLdiv>"
// "<HTMLdiv borderRadius='100px' overflow='hidden' position='absolute' width='100%' height='100%'
//          transform='rotate({2*this.x+this.y}deg)'
//          onClick = { this.bannerColor = this.bannerColor === 'red' ? 'green' : 'red' } >
//    <ImageBox {...props} fieldKey={'data'}/>
//    <HTMLspan width='200px' top='0' height='35px' textAlign='center' paddingTop='10px'
//              transform='translate(-40px, 45px) rotate(-45deg)' position='absolute'
//              color='{this.bannerColor===`green`?`light`:`dark`}blue'
//              backgroundColor='{this.bannerColor===`green`?`dark`:`light`}blue'>
//       {this.title}
//    </HTMLspan>
//  </HTMLdiv>"
@observer
export class HTMLtag extends React.Component<HTMLtagProps> {
    click = () => {
        const clickScript = this.props.onClick as Opt<ScriptField>;
        clickScript?.script.run({ this: this.props.Document });
    };
    onInput = (e: React.FormEvent<unknown>) => {
        const onInputScript = this.props.onInput as Opt<ScriptField>;
        onInputScript?.script.run({ this: this.props.Document, value: (e.target as HTMLElement).textContent });
    };
    render() {
        const style: { [key: string]: unknown } = {};
        const divKeys = OmitKeys(this.props, [
            'children', //
            'dragStarting',
            'dragEnding',
            'htmltag',
            'Document',
            'key',
            'onInput',
            'onClick',
            '__proto__',
        ]).omit;
        const replacer = (match: string, expr: string) =>
            // bcz: this executes a script to convert a property expression string:  { script }  into a value
            (ScriptField.MakeFunction(expr, { this: Doc.name })?.script.run({ this: this.props.Document }).result as string) || '';
        Object.keys(divKeys).forEach((prop: string) => {
            const p = (this.props as unknown as { [key: string]: string })[prop] as string;
            style[prop] = p?.replace(/{([^.'][^}']+)}/g, replacer);
        });
        const Tag = this.props.htmltag as keyof JSX.IntrinsicElements;
        return (
            <Tag style={style} onClick={this.click} onInput={this.onInput}>
                {this.props.children}
            </Tag>
        );
    }
}

interface DocumentContentsViewProps extends DocumentViewProps, FieldViewProps {
    layoutFieldKey: string;
}
@observer
export class DocumentContentsView extends ObservableReactComponent<DocumentContentsViewProps> {
    private static DefaultLayoutString: string;
    /**
     * Set of all available rendering componets for Docs (e.g., ImageBox, CollectionFreeFormView, etc)
     */
    private static Components: { [key: string]: unknown };
    public static Init(defaultLayoutString: string, components: { [key: string]: unknown }) {
        DocumentContentsView.DefaultLayoutString = defaultLayoutString;
        DocumentContentsView.Components = components;
    }
    constructor(props: DocumentContentsViewProps) {
        super(props);
        makeObservable(this);
    }
    @computed get layout(): string {
        TraceMobx();
        if (this._props.LayoutTemplateString) return this._props.LayoutTemplateString;
        if (!this.layoutDoc) return '<p>awaiting layout</p>';
        if (this._props.layoutFieldKey === 'layout_keyValue') return StrCast(this._props.Document.layout_keyValue, DocumentContentsView.DefaultLayoutString);
        const tempLayout = DocCast(this.layoutDoc[this.layoutDoc === this._props.Document && this._props.layoutFieldKey ? this._props.layoutFieldKey : StrCast(this.layoutDoc.layout_fieldKey, 'layout')]);
        const layoutDoc = tempLayout ?? this.layoutDoc;
        const layout = Cast(layoutDoc[layoutDoc === this._props.Document && this._props.layoutFieldKey ? this._props.layoutFieldKey : StrCast(layoutDoc.layout_fieldKey, 'layout')], 'string');
        if (layout === undefined) return this._props.Document.data ? "<FieldView {...props} fieldKey='data' />" : DocumentContentsView.DefaultLayoutString;
        if (typeof layout === 'string') return layout;
        return '<p>Loading layout</p>';
    }

    get layoutDoc() {
        const template: Doc =
            this._props.LayoutTemplate?.() ||
            (this._props.LayoutTemplateString && this._props.Document) ||
            (this._props.layoutFieldKey && StrCast(this._props.Document[this._props.layoutFieldKey]) && this._props.Document) ||
            Doc.LayoutDoc(this._props.Document, DocCast(this._props.Document[this._props.layoutFieldKey]));
        return Doc.expandTemplateLayout(template, this._props.Document, this._props.layoutFieldKey);
    }

    CreateBindings(onClick: Opt<ScriptField>, onInput: Opt<ScriptField>): JsxBindings {
        const templateDataDoc = this._props.TemplateDataDocument ?? (this.layoutDoc !== this._props.Document ? this._props.Document[DocData] : undefined);
        const list: BindingProps & React.DetailedHTMLProps<React.HtmlHTMLAttributes<HTMLDivElement>, HTMLDivElement> = {
            ...this._props,
            Document: this.layoutDoc ?? this._props.Document,
            TemplateDataDocument: templateDataDoc instanceof Promise ? undefined : templateDataDoc,
            onClick: onClick as unknown as React.MouseEventHandler, // pass onClick script as if it were a real function -- it will be interpreted properly in the HTMLtag
            onInput: onInput as unknown as React.FormEventHandler,
        };
        return {
            props: {
                ...OmitKeys(list, DocOnlyProps, '').omit,
            } as BindingProps,
        };
    }

    // componentWillUpdate(oldProps: any, newState: any) {
    //     // console.log("willupdate", oldProps, this._props); // bcz: if you get a message saying something invalidated because reactive props changed, then this method allows you to figure out which prop changed
    // }

    @computed get renderData() {
        TraceMobx();
        let layoutFrame = this.layout;

        // replace code content with a script  >{content}<   as in  <HTMLdiv>{this.title}</HTMLdiv>
        const replacer = (match: string, prefix: string, expr: string, postfix: string) => prefix + ((ScriptField.MakeFunction(expr, { this: Doc.name })?.script.run({ this: this._props.Document }).result as string) || '') + postfix;
        layoutFrame = layoutFrame.replace(/(>[^{]*)[^=]\{([^.'][^<}]+)\}([^}]*<)/g, replacer);

        // replace HTML<tag> with corresponding HTML tag as in:  <HTMLdiv> becomes  <HTMLtag Document={props.Document} htmltag='div'>
        const replacer2 = (match: string, p1: string) => `<HTMLtag Document={props.Document} htmltag='${p1}'`;
        layoutFrame = layoutFrame.replace(/<HTML([a-zA-Z0-9_-]+)/g, replacer2);

        // replace /HTML<tag> with </HTMLdiv>  as in:  </HTMLdiv> becomes  </HTMLtag>
        const replacer3 = (/* match: any, p1: string, offset: any, string: any */) => `</HTMLtag`;
        layoutFrame = layoutFrame.replace(/<\/HTML([a-zA-Z0-9_-]+)/g, replacer3);

        // add onClick function to props
        const makeFuncProp = (func: string) => {
            const splits = layoutFrame.split(`${func}=`);
            if (splits.length > 1) {
                const code = XRegExp.matchRecursive(splits[1], '{', '}', '', { valueNames: ['between', 'left', 'match', 'right', 'between'] });
                layoutFrame = splits[0] + ` ${func}={props.${func}} ` + splits[1].substring(code[1].end + 1);
                const script = code[1].value.replace(/^‘/, '').replace(/’$/, ''); // ‘’ are not valid quotes in javascript so get rid of them -- they may be present to make it easier to write complex scripts - see headerTemplate in currentUserUtils.ts
                return ScriptField.MakeScript(script, { this: Doc.name, value: 'string' });
            }
            return undefined;
            // add input function to props
        };
        const onClick = makeFuncProp('onClick');
        const onInput = makeFuncProp('onInput');
        const bindings = this.CreateBindings(onClick, onInput);
        return { bindings, layoutFrame };
    }

    blacklistedAttrs = [];
    render() {
        TraceMobx();
        const { bindings, layoutFrame } = this.renderData;

        return this._props.renderDepth > 12 || !layoutFrame || !this.layoutDoc || GetEffectiveAcl(this.layoutDoc) === AclPrivate ? null : (
            <ObserverJsxParser
                key={42}
                blacklistedAttrs={this.blacklistedAttrs}
                renderInWrapper={false}
                components={DocumentContentsView.Components}
                bindings={bindings}
                jsx={layoutFrame}
                showWarnings
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                onError={(test: any) => {
                    console.log('DocumentContentsView:' + test, bindings, layoutFrame);
                }}
            />
        );
    }
}