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
|
import { action, computed, observable } from "mobx";
import { observer } from "mobx-react";
import 'react-image-lightbox/style.css'; // This only needs to be imported once in your app
import { CompileScript, ScriptOptions, CompiledScript } from "../../util/Scripting";
import { FieldView, FieldViewProps } from './FieldView';
import "./KeyValueBox.scss";
import { KeyValuePair } from "./KeyValuePair";
import React = require("react");
import { NumCast, Cast, FieldValue, StrCast } from "../../../new_fields/Types";
import { Doc, Field, FieldResult, DocListCastAsync } from "../../../new_fields/Doc";
import { ComputedField, ScriptField } from "../../../new_fields/ScriptField";
import { SetupDrag } from "../../util/DragManager";
import { Docs } from "../../documents/Documents";
import { RawDataOperationParameters } from "../../northstar/model/idea/idea";
import { Templates } from "../Templates";
import { List } from "../../../new_fields/List";
import { TextField } from "../../util/ProsemirrorCopy/prompt";
import { RichTextField } from "../../../new_fields/RichTextField";
import { ImageField } from "../../../new_fields/URLField";
import { SelectionManager } from "../../util/SelectionManager";
import { listSpec } from "../../../new_fields/Schema";
export type KVPScript = {
script: CompiledScript;
type: "computed" | "script" | false;
onDelegate: boolean;
};
@observer
export class KeyValueBox extends React.Component<FieldViewProps> {
private _mainCont = React.createRef<HTMLDivElement>();
private _keyHeader = React.createRef<HTMLTableHeaderCellElement>();
@observable private rows: KeyValuePair[] = [];
public static LayoutString(fieldStr: string = "data") { return FieldView.LayoutString(KeyValueBox, fieldStr); }
@observable private _keyInput: string = "";
@observable private _valueInput: string = "";
@computed get splitPercentage() { return NumCast(this.props.Document.schemaSplitPercentage, 50); }
get fieldDocToLayout() { return this.props.fieldKey ? FieldValue(Cast(this.props.Document[this.props.fieldKey], Doc)) : this.props.Document; }
constructor(props: FieldViewProps) {
super(props);
}
@action
onEnterKey = (e: React.KeyboardEvent): void => {
if (e.key === 'Enter') {
if (this._keyInput && this._valueInput && this.fieldDocToLayout) {
if (KeyValueBox.SetField(this.fieldDocToLayout, this._keyInput, this._valueInput)) {
this._keyInput = "";
this._valueInput = "";
}
}
}
}
public static CompileKVPScript(value: string): KVPScript | undefined {
let eq = value.startsWith("=");
value = eq ? value.substr(1) : value;
const dubEq = value.startsWith(":=") ? "computed" : value.startsWith(";=") ? "script" : false;
value = dubEq ? value.substr(2) : value;
let options: ScriptOptions = { addReturn: true, params: { this: "Doc" } };
if (dubEq) options.typecheck = false;
let script = CompileScript(value, options);
if (!script.compiled) {
return undefined;
}
return { script, type: dubEq, onDelegate: eq };
}
public static ApplyKVPScript(doc: Doc, key: string, kvpScript: KVPScript): boolean {
const { script, type, onDelegate } = kvpScript;
const target = onDelegate ? doc : Doc.GetProto(doc);
let field: Field;
if (type === "computed") {
field = new ComputedField(script);
} else if (type === "script") {
field = new ScriptField(script);
} else {
let res = script.run({ this: target });
if (!res.success) return false;
field = res.result;
}
if (Field.IsField(field, true)) {
target[key] = field;
return true;
}
return false;
}
public static SetField(doc: Doc, key: string, value: string) {
const script = this.CompileKVPScript(value);
if (!script) return false;
return this.ApplyKVPScript(doc, key, script);
}
onPointerDown = (e: React.PointerEvent): void => {
if (e.buttons === 1 && this.props.isSelected()) {
e.stopPropagation();
}
}
onPointerWheel = (e: React.WheelEvent): void => {
e.stopPropagation();
}
createTable = () => {
let doc = this.fieldDocToLayout;
if (!doc) {
return <tr><td>Loading...</td></tr>;
}
let realDoc = doc;
let ids: { [key: string]: string } = {};
let protos = Doc.GetAllPrototypes(doc);
for (const proto of protos) {
Object.keys(proto).forEach(key => {
if (!(key in ids)) {
ids[key] = key;
}
});
}
let rows: JSX.Element[] = [];
let i = 0;
const self = this;
for (let key of Object.keys(ids).sort()) {
rows.push(<KeyValuePair doc={realDoc} ref={(function () {
let oldEl: KeyValuePair | undefined;
return (el: KeyValuePair) => {
if (oldEl) self.rows.splice(self.rows.indexOf(oldEl), 1);
oldEl = el;
if (el) self.rows.push(el);
};
})()} keyWidth={100 - this.splitPercentage} rowStyle={"keyValueBox-" + (i++ % 2 ? "oddRow" : "evenRow")} key={key} keyName={key} />);
}
return rows;
}
@action
keyChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
this._keyInput = e.currentTarget.value;
}
@action
valueChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
this._valueInput = e.currentTarget.value;
}
newKeyValue = () =>
(
<tr className="keyValueBox-valueRow">
<td className="keyValueBox-td-key" style={{ width: `${100 - this.splitPercentage}%` }}>
<input style={{ width: "100%" }} type="text" value={this._keyInput} placeholder="Key" onChange={this.keyChanged} />
</td>
<td className="keyValueBox-td-value" style={{ width: `${this.splitPercentage}%` }}>
<input style={{ width: "100%" }} type="text" value={this._valueInput} placeholder="Value" onChange={this.valueChanged} onKeyPress={this.onEnterKey} />
</td>
</tr>
)
@action
onDividerMove = (e: PointerEvent): void => {
let nativeWidth = this._mainCont.current!.getBoundingClientRect();
this.props.Document.schemaSplitPercentage = Math.max(0, 100 - Math.round((e.clientX - nativeWidth.left) / nativeWidth.width * 100));
}
@action
onDividerUp = (e: PointerEvent): 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);
}
getTemplate = async () => {
let parent = Docs.Create.StackingDocument([], { width: 800, height: 800, title: "Template" });
parent.singleColumn = false;
parent.columnWidth = 100;
for (let row of this.rows.filter(row => row.isChecked)) {
await this.createTemplateField(parent, row);
row.uncheck();
}
return parent;
}
createTemplateField = async (parentStackingDoc: Doc, row: KeyValuePair) => {
let metaKey = row.props.keyName;
let sourceDoc = await Cast(this.props.Document.data, Doc);
if (!sourceDoc) {
return;
}
let fieldTemplate = await this.inferType(sourceDoc[metaKey], metaKey);
let previousViewType = fieldTemplate.viewType;
Doc.MakeTemplate(fieldTemplate, metaKey, Doc.GetProto(parentStackingDoc));
previousViewType && (fieldTemplate.viewType = previousViewType);
Cast(parentStackingDoc.data, listSpec(Doc))!.push(fieldTemplate);
}
inferType = async (data: FieldResult, metaKey: string) => {
let options = { width: 300, height: 300, title: metaKey };
if (data instanceof RichTextField || typeof data === "string" || typeof data === "number") {
return Docs.Create.TextDocument(options);
} else if (data instanceof List) {
if (data.length === 0) {
return Docs.Create.StackingDocument([], options);
}
let first = await Cast(data[0], Doc);
if (!first) {
return Docs.Create.StackingDocument([], options);
}
switch (first.type) {
case "image":
return Docs.Create.StackingDocument([], options);
case "text":
return Docs.Create.TreeDocument([], options);
}
} else if (data instanceof ImageField) {
return Docs.Create.ImageDocument("https://image.flaticon.com/icons/png/512/23/23765.png", options);
}
return new Doc;
}
render() {
let 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} 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.getTemplate)}
>Key</th>
<th className="keyValueBox-fields" style={{ width: `${this.splitPercentage}%` }}>Fields</th>
</tr>
{this.createTable()}
{this.newKeyValue()}
</tbody>
</table>
{dividerDragger}
</div>);
}
}
|