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
|
import { action, computed, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { returnAlways, returnTrue } from '../../../ClientUtils';
import { Doc, Field, FieldResult, FieldType } from '../../../fields/Doc';
import { List } from '../../../fields/List';
import { RichTextField } from '../../../fields/RichTextField';
import { ComputedField, ScriptField } from '../../../fields/ScriptField';
import { DocCast } from '../../../fields/Types';
import { ImageField } from '../../../fields/URLField';
import { DocumentType } from '../../documents/DocumentTypes';
import { Docs, DocumentOptions } from '../../documents/Documents';
import { SetupDrag } from '../../util/DragManager';
import { CompiledScript } from '../../util/Scripting';
import { undoable } from '../../util/UndoManager';
import { ContextMenu } from '../ContextMenu';
import { ViewBoxBaseComponent } from '../DocComponent';
import { DocumentIconContainer } from './DocumentIcon';
import { FieldView, FieldViewProps } from './FieldView';
import { ImageBox } from './ImageBox';
import './KeyValueBox.scss';
import { KeyValuePair } from './KeyValuePair';
import { OpenWhere } from './OpenWhere';
import { FormattedTextBox } from './formattedText/FormattedTextBox';
import { DocLayout } from '../../../fields/DocSymbols';
export type KVPScript = {
script: CompiledScript;
type: 'computed' | 'script' | false;
onDelegate: boolean;
};
@observer
export class KeyValueBox extends ViewBoxBaseComponent<FieldViewProps>() {
public static LayoutString() {
return FieldView.LayoutString(KeyValueBox, 'data');
}
constructor(props: FieldViewProps) {
super(props);
makeObservable(this);
}
private _mainCont = React.createRef<HTMLDivElement>();
private _keyHeader = React.createRef<HTMLTableHeaderCellElement>();
private _keyInput = React.createRef<HTMLInputElement>();
private _valInput = React.createRef<HTMLInputElement>();
componentDidMount() {
this._props.setContentViewBox?.(this);
}
// ViewBoxInterface overrides
override isUnstyledView = returnTrue; // used by style provider via ViewBoxInterface - ignore opacity, anim effects, titles
override dontRegisterView = returnTrue; // don't want to follow links to this view
override onClickScriptDisable = returnAlways;
@observable private rows: KeyValuePair[] = [];
@observable _splitPercentage = 50;
@action
onEnterKey = (e: React.KeyboardEvent): void => {
if (e.key === 'Enter') {
e.stopPropagation();
if (this._keyInput.current?.value && this._valInput.current?.value && this.Document) {
if (KeyValueBox.SetField(this.Document, this._keyInput.current.value, this._valInput.current.value)) {
this._keyInput.current.value = '';
this._valInput.current.value = '';
document.body.focus();
}
}
}
};
/**
* this compiles a string as a script after parsing off initial characters that determine script parameters
* if the script starts with '=', then it will be stored on the delegate of the Doc, otherise on the data doc
* if the script then starts with a ':=', then it will be treated as ComputedField,
* '$=', then it will just be a Script
* @param value
* @returns
*/
public static CompileKVPScript = (rawvalueIn: string): KVPScript | undefined => {
let rawvalue = rawvalueIn;
const onDelegate = rawvalue.startsWith('=');
rawvalue = onDelegate ? rawvalue.substring(1) : rawvalue;
const type: 'computed' | 'script' | false = rawvalue.startsWith(':=') ? 'computed' : rawvalue.startsWith('$=') ? 'script' : false;
rawvalue = type ? rawvalue.substring(2) : rawvalue.replace(/^:/, '');
rawvalue = rawvalue.replace(/.*\(\((.*)\)\)/, 'dashCallChat(_setCacheResult_, this, `$1`)');
const value = ["'", '"', '`'].includes(rawvalue.length ? rawvalue[0] : '') || !isNaN(+rawvalue) ? rawvalue : '`' + rawvalue + '`';
let script = ScriptField.CompileScript(rawvalue, {}, true, undefined, DocumentIconContainer.getTransformer());
if (!script.compiled) {
script = ScriptField.CompileScript(value, {}, true, undefined, DocumentIconContainer.getTransformer());
}
return !script.compiled ? undefined : { script, type, onDelegate };
};
public static ApplyKVPScript = (doc: Doc, keyIn: string, kvpScript: KVPScript, forceOnDelegate?: boolean, setResult?: (value: FieldResult) => void) => {
const { script, type, onDelegate } = kvpScript;
const chooseDelegate = forceOnDelegate || onDelegate || keyIn.startsWith('_');
const key = chooseDelegate && keyIn.startsWith('$') ? keyIn.slice(1) : keyIn;
const target = chooseDelegate ? doc : DocCast(doc.proto, doc)!;
let field: FieldType | undefined;
switch (type) {
case 'computed': field = new ComputedField(script); break; // prettier-ignore
case 'script': field = new ScriptField(script); break; // prettier-ignore
default: {
const _setCacheResult_ = (value: FieldResult) => {
field = value as FieldType;
if (setResult) setResult(value);
else target[key] = field;
};
const res = script.run({ this: doc, _setCacheResult_ }, console.log);
if (!res.success) {
if (key) target[key] = script.originalScript;
return false;
}
field === undefined && (field = res.result instanceof Array ? new List<FieldType>(res.result) : typeof res.result === 'function' ? res.result.name : (res.result as FieldType));
}
}
if (!key) return false;
if (Field.IsField(field, true) && (key !== 'proto' || field !== target)) {
target[key] = field;
return true;
}
return false;
};
public static SetField = undoable((doc: Doc, key: string, value: string, forceOnDelegateIn?: boolean, setResult?: (value: FieldResult) => void) => {
const script = KeyValueBox.CompileKVPScript(value);
if (!script) return false;
const ldoc = key.startsWith('_') ? doc[DocLayout] : doc;
const forceOnDelegate = forceOnDelegateIn || (ldoc !== doc && !value.startsWith('='));
// an '=' value redirects a key targeting the render template to the root document.
// also, if ldoc and doc are equal, allow redirecting to data document when not using an equal
// in either case, get rid of initial '_' which forces writing to layout
const setKey = value.startsWith('=') || ldoc === doc ? key.replace(/^_/, '') : key;
return KeyValueBox.ApplyKVPScript(doc, setKey, script, forceOnDelegate, setResult);
}, 'Set Doc Field');
onPointerDown = (e: React.PointerEvent): void => {
if (e.buttons === 1 && this._props.isSelected()) {
e.stopPropagation();
}
};
onPointerWheel = (e: React.WheelEvent): void => e.stopPropagation();
rowHeight = () => 30;
@computed get createTable() {
const doc = this.Document;
if (!doc) {
return (
<tr>
<td>Loading...</td>
</tr>
);
}
const ids: { [key: string]: string } = {};
const protos = Doc.GetAllPrototypes(doc);
protos.forEach(proto => {
Object.keys(proto).forEach(key => {
if (!(key in ids) && doc[key] !== ComputedField.undefined) {
ids[key] = key;
}
});
});
const docinfos = new DocumentOptions();
const layoutProtos = this.layoutDoc !== doc ? Doc.GetAllPrototypes(this.layoutDoc) : [];
layoutProtos.forEach(proto => {
Object.keys(proto)
.filter(key => !(key in ids) || docinfos['_' + key]) // if '_key' is in docinfos (as opposed to just 'key'), then the template Doc's value should be displayed instead of the root document's value
.map(key => '_' + key)
.forEach(key => {
if (doc[key] !== ComputedField.undefined) {
if (key.replace(/^_/, '') in ids) delete ids[key.replace(/^_/, '')];
ids[key] = key;
}
});
});
const rows: JSX.Element[] = [];
let i = 0;
const keys = Object.keys(ids).slice();
// for (const key of [...keys.filter(id => id !== 'layout' && !id.includes('_')).sort(), ...keys.filter(id => id === 'layout' || id.includes('_')).sort()]) {
const sortedKeys = keys.sort((a: string, b: string) => {
const a_ = a.replace(/^_/, '').split('_')[0];
const b_ = b.replace(/^_/, '').split('_')[0];
if (a_ < b_) return -1;
if (a_ > b_) return 1;
if (a === a_) return -1;
if (b === b_) return 1;
return a === b ? 0 : a < b ? -1 : 1;
});
sortedKeys.forEach(key => {
rows.push(
<KeyValuePair
doc={doc}
addDocTab={this._props.addDocTab}
PanelWidth={this._props.PanelWidth}
PanelHeight={this.rowHeight}
ref={(() => {
let oldEl: KeyValuePair | undefined;
return (el: KeyValuePair) => {
if (oldEl) this.rows.splice(this.rows.indexOf(oldEl), 1);
oldEl = el;
if (el) this.rows.push(el);
};
})()}
keyWidth={100 - this._splitPercentage}
rowStyle={'keyValueBox-' + (i++ % 2 ? 'oddRow' : 'evenRow')}
key={key}
keyName={key}
/>
);
});
return rows;
}
@computed get newKeyValue() {
return (
<tr className="keyValueBox-valueRow">
<td
className="keyValueBox-td-key"
onClick={e => {
this._keyInput.current!.select();
e.stopPropagation();
}}
style={{ width: `${100 - this._splitPercentage}%` }}>
<input style={{ width: '100%' }} ref={this._keyInput} type="text" placeholder="Key" />
</td>
<td
className="keyValueBox-td-value"
onClick={e => {
this._valInput.current!.select();
e.stopPropagation();
}}
style={{ width: `${this._splitPercentage}%` }}>
<input style={{ width: '100%' }} ref={this._valInput} type="text" placeholder="Value" onKeyDown={this.onEnterKey} />
</td>
</tr>
);
}
@action
onDividerMove = (e: PointerEvent): void => {
const nativeWidth = this._mainCont.current!.getBoundingClientRect();
this._splitPercentage = Math.max(0, 100 - Math.round(((e.clientX - nativeWidth.left) / nativeWidth.width) * 100));
};
@action
onDividerUp = (): void => {
document.removeEventListener('pointermove', this.onDividerMove);
document.removeEventListener('pointerup', this.onDividerUp);
};
onDividerDown = (e: React.PointerEvent) => {
e.stopPropagation();
e.preventDefault();
document.addEventListener('pointermove', this.onDividerMove);
document.addEventListener('pointerup', this.onDividerUp);
};
getFieldView = () => {
const rows = this.rows.filter(row => row.isChecked);
if (rows.length > 1) {
const parent = Docs.Create.StackingDocument([], { _layout_autoHeight: true, _width: 300, title: `field views for ${this.Document.title}`, _chromeHidden: true });
rows.forEach(row => {
const field = this.createFieldView(this.Document, row);
field && Doc.AddDocToList(parent, 'data', field);
row.uncheck();
});
return parent;
}
return rows.length ? this.createFieldView(this.Document, rows.lastElement()) : undefined;
};
createFieldView = (templateDoc: Doc, row: KeyValuePair) => {
const metaKey = row._props.keyName;
const fieldTempDoc = Doc.IsDelegateField(templateDoc, metaKey) ? Doc.MakeDelegate(templateDoc) : Doc.MakeEmbedding(templateDoc);
fieldTempDoc.title = metaKey;
fieldTempDoc.layout_fitWidth = true;
fieldTempDoc._xMargin = 10;
fieldTempDoc._yMargin = 10;
fieldTempDoc._width = 100;
fieldTempDoc._height = 40;
fieldTempDoc.layout = this.inferType(templateDoc[metaKey], metaKey);
return fieldTempDoc;
};
inferType = (data: FieldResult, metaKey: string) => {
const options = { _width: 300, _height: 300, title: metaKey };
if (data instanceof RichTextField || typeof data === 'string' || typeof data === 'number') {
return FormattedTextBox.LayoutString(metaKey);
}
if (data instanceof List) {
if (data.length === 0) {
return Docs.Create.StackingDocument([], options);
}
const first = DocCast(data[0]);
if (!first || !first.data) {
return Docs.Create.StackingDocument([], options);
}
switch (first.data.constructor) {
case RichTextField: return Docs.Create.TreeDocument([], options);
case ImageField: return Docs.Create.MasonryDocument([], options);
default: console.log(`Template for ${first.data.constructor} not supported!`);
return undefined;
} // prettier-ignore
} else if (data instanceof ImageField) {
return ImageBox.LayoutString(metaKey);
}
return new Doc();
};
specificContextMenu = (): void => {
const cm = ContextMenu.Instance;
const open = cm.findByDescription('Change Perspective...');
const openItems = open?.subitems ?? [];
openItems.push({
description: 'Default Perspective',
event: () => {
this._props.addDocTab(this.Document, OpenWhere.close);
this._props.addDocTab(this.Document, OpenWhere.addRight);
},
icon: 'image',
});
!open && cm.addItem({ description: 'Change Perspective...', subitems: openItems, icon: 'external-link-alt' });
};
render() {
const dividerDragger =
this._splitPercentage === 0 ? null : (
<div className="keyValueBox-dividerDragger" style={{ transform: `translate(calc(${100 - this._splitPercentage}% - 5px), 0px)` }}>
<div className="keyValueBox-dividerDraggerThumb" onPointerDown={this.onDividerDown} />
</div>
);
return (
<div className="keyValueBox-cont" onWheel={this.onPointerWheel} onContextMenu={this.specificContextMenu} ref={this._mainCont}>
<table className="keyValueBox-table">
<tbody className="keyValueBox-tbody">
<tr className="keyValueBox-header">
<th className="keyValueBox-key" style={{ width: `${100 - this._splitPercentage}%` }} ref={this._keyHeader} onPointerDown={SetupDrag(this._keyHeader, this.getFieldView)}>
Key
</th>
<th className="keyValueBox-fields" style={{ width: `${this._splitPercentage}%` }}>
Fields
</th>
</tr>
{this.createTable}
{this.newKeyValue}
</tbody>
</table>
{dividerDragger}
</div>
);
}
public static Init() {
Doc.SetField = KeyValueBox.SetField;
}
}
Docs.Prototypes.TemplateMap.set(DocumentType.KVP, {
layout: { view: KeyValueBox, dataField: 'data' },
options: { acl: '', _layout_fitWidth: true, _height: 150 },
});
|