-
Notifications
You must be signed in to change notification settings - Fork 5
/
HtmlDomNode.java
472 lines (402 loc) · 17 KB
/
HtmlDomNode.java
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
package org.genericsystem.reactor;
import io.vertx.core.json.JsonObject;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javafx.beans.property.Property;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.SetChangeListener;
import javafx.collections.transformation.FilteredList;
import org.genericsystem.defaults.tools.ObservableListWrapper;
import org.genericsystem.defaults.tools.TransformationObservableList;
import org.genericsystem.reactor.context.TagSwitcher;
public class HtmlDomNode {
static int count = 0;
protected static final String MSG_TYPE = "msgType";
protected static final String ADD = "A";
protected static final String UPDATE = "U";
static final String REMOVE = "R";
static final String UPDATE_TEXT = "UT";
private static final String UPDATE_SELECTION = "US";
static final String ADD_STYLECLASS = "AC";
static final String REMOVE_STYLECLASS = "RC";
static final String ADD_STYLE = "AS";
static final String REMOVE_STYLE = "RS";
static final String ADD_ATTRIBUTE = "AA";
static final String REMOVE_ATTRIBUTE = "RA";
static final String PARENT_ID = "parentId";
public static final String ID = "nodeId";
static final String NEXT_ID = "nextId";
static final String STYLE_PROPERTY = "styleProperty";
static final String STYLE_VALUE = "styleValue";
static final String ATTRIBUTE_NAME = "attributeName";
static final String ATTRIBUTE_VALUE = "attributeValue";
static final String STYLECLASS = "styleClass";
protected static final String TEXT_CONTENT = "textContent";
static final String TAG_HTML = "tagHtml";
protected static final String ELT_TYPE = "eltType";
protected static final String SELECTED_INDEX = "selectedIndex";
private final String id;
private HtmlDomNode parent;
private Tag tag;
private Context context;
private boolean destroyed = false;
public static interface Sender {
public void send(String message);
}
private final Consumer<Tag> tagAdder = tagAdder();
private Map<Tag, Integer> sizeBySubTag = new IdentityHashMap<Tag, Integer>() {
private static final long serialVersionUID = 6725720602283055930L;
@Override
public Integer get(Object key) {
Integer size = super.get(key);
if (size == null)
put((Tag) key, size = 0);
return size;
};
};
private ListChangeListener<Tag> tagListener = change -> {
while (change.next()) {
if (change.wasRemoved())
change.getRemoved().forEach(childTag -> context.removeTag(childTag));
if (change.wasAdded())
change.getAddedSubList().forEach(tagAdder::accept);
}
};
public List<HtmlDomNode> getChildren() {
List<HtmlDomNode> result = new ArrayList<>();
List<Tag> subTags = tag.getObservableChildren();
for (Tag subTag : subTags) {
if (subTag.getMetaBinding() == null)
result.add(context.getHtmlDomNode(subTag));
else
for (Context subContext : context.getSubContexts(subTag))
result.add(subContext.getHtmlDomNode(subTag));
}
return result;
}
public String header() {
String header = "";
String appName = this.tag.getClass().getSimpleName().toLowerCase();
header = "<!DOCTYPE html>\n";
header += "<html>\n";
header += "<head>\n";
header += "<meta charset=\"UTF-8\" name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n";
header += "<LINK rel=stylesheet type=\"text/css\" href=\"" + appName + ".css\"/>\n";
header += "<LINK rel=stylesheet type=\"text/css\" href=\"reactor.css\"/>\n";
header += "<script>\n";
header += "var serviceLocation = \"ws://\" + document.location.host + \"" + "\";\n";
header += "</script>\n";
header += "<script type=\"text/javascript\" src=\"" + appName + ".js\"></script>\n";
header += "</head>\n";
header += "<body onload=\"connect();\" id=\"root\">\n";
return header;
}
public String footer() {
String footer = "</body>\n";
footer += "</html>\n";
return footer;
}
public String toHTMLString(String body) {
String tagText = this.tag.getTag();
String classes = tag.getDomNodeStyleClasses(context).stream().collect(Collectors.joining(" "));
classes = ("section".equals(tagText) || "div".equals(tagText) || "header".equals(tagText) || "footer".equals(tagText)) ? classes += " adding" : classes;
String styles = tag.getDomNodeStyles(context).entrySet().stream().map(m -> m.getKey() + ": " + m.getValue()).collect(Collectors.joining("; "));
body = "\n<" + tagText + " id=\"" + this.id + "\"";
if (!classes.equals(""))
body += " class=\"" + classes + "\"";
if (!styles.equals(""))
body += " style=\"" + styles + "\"";
String tagAttributes = tag.getDomNodeAttributes(context).entrySet().stream().filter(m -> m.getValue() != null && !m.getValue().isEmpty()).map(m -> m.getKey() + "=\"" + m.getValue() + "\"").collect(Collectors.joining(""));
body += tagAttributes + ">";
for (HtmlDomNode node : getChildren())
body += node.toHTMLString(body);
String tagValue = tag.getDomNodeTextProperty(context).getValue();
if (tagValue != null)
body += tagValue;
body += "</" + tagText + ">";
return body;
}
public void toHtmlFile(String sourceCode, String extention, String path) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(path + "index." + extention));
writer.write(sourceCode);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public HtmlDomNode(HtmlDomNode parent, Context context, Tag tag) {
this.id = String.format("%010d", Integer.parseInt(this.hashCode() + "")).substring(0, 10);
this.parent = parent;
this.tag = tag;
this.context = context;
tag.getRootTag().initDomNode(this);
}
private <BETWEEN> Consumer<Tag> tagAdder() {
return childTag -> {
Property<MetaBinding<BETWEEN>> metaBinding = childTag.getMetaBindingProperty();
metaBinding.addListener(metaBindingListeners.get(childTag));
updateMetaBinding(childTag, metaBinding.getValue());
};
}
private <BETWEEN> void updateMetaBinding(Tag childTag, MetaBinding<BETWEEN> metaBinding) {
if (metaBinding != null) {
if (context.getSubContexts(childTag) == null) {
FilteredChildContexts<BETWEEN> subContexts = new FilteredChildContexts<>(metaBinding, childTag);
childTag.createNewInitializedProperty("filteredContexts", context, c -> subContexts);
context.setSubContexts(childTag, new TransformationObservableList<Context, Context>(subContexts.filteredSubContexts, (i, subContext) -> {
childTag.createNode(this, subContext).init(computeIndex(i, childTag));
if (subContext.isInCache())
childTag.addStyleClass(subContext, "opaque");
return subContext;
}, subContext -> subContext.removeTag(childTag)));
}
} else if (context.getHtmlDomNode(childTag) == null)
childTag.createNode(this, context).init(computeIndex(0, childTag));
}
void destroy() {
// System.out.println("Attempt to destroy : " + getId());
assert !destroyed : "Node : " + getId();
destroyed = true;
((FilteredTagChildren) tag.getProperty("filteredChildren", context).getValue()).filteredList.removeListener(tagListener);
for (Tag childTag : tag.getObservableChildren()) {
childTag.getMetaBindingProperty().removeListener(metaBindingListeners.get(childTag));
if (childTag.getMetaBinding() != null && context.getSubContexts(childTag) != null)
((FilteredChildContexts<?>) childTag.getProperty("filteredContexts", context).getValue()).transformationListSubContexts.unbind();
}
tag.getDomNodeTextProperty(context).removeListener(textListener);
tag.getDomNodeStyles(context).removeListener(stylesListener);
tag.getDomNodeAttributes(context).removeListener(attributesListener);
tag.getDomNodeStyleClasses(context).removeListener(styleClassesListener);
getRootHtmlDomNode().remove(getId());
parent.decrementSize(tag);
}
protected <BETWEEN> void init(int index) {
context.register(this);
if (parent != null)
insertChild(index);
for (Consumer<Context> binding : tag.getPreFixedBindings())
binding.accept(context);
assert (!context.containsProperty(tag, "filteredChildren"));
FilteredTagChildren filteredChildren = new FilteredTagChildren();
tag.createNewInitializedProperty("filteredChildren", context, c -> filteredChildren);
for (Tag childTag : filteredChildren.filteredList)
tagAdder.accept(childTag);
filteredChildren.filteredList.addListener(tagListener);
for (Consumer<Context> binding : tag.getPostFixedBindings())
binding.accept(context);
}
private class FilteredChildren<T> {
final Map<T, ObservableList<TagSwitcher>> selectorsByChild = new HashMap<>();// Prevents garbage collection
final Map<T, Map<TagSwitcher, ObservableValue<Boolean>>> selectorsByChildAndSwitcher = new HashMap<T, Map<TagSwitcher, ObservableValue<Boolean>>>() {
private static final long serialVersionUID = -5831485781427983238L;
@Override
public Map<TagSwitcher, ObservableValue<Boolean>> get(Object key) {
Map<TagSwitcher, ObservableValue<Boolean>> result = super.get(key);
if (result == null)
put((T) key, result = new HashMap<>());
return result;
}
};
}
private class FilteredTagChildren extends FilteredChildren<Tag> {
final ObservableList<Tag> filteredList = new FilteredList<>(new ObservableListWrapper<>(context.getRootContext().getObservableChildren(tag), child -> {
if (child.getMetaBinding() != null)
return new ObservableValue[] {};
ObservableList<TagSwitcher> result = new ObservableListWrapper<>(child.getObservableSwitchers(), s -> {
ObservableValue<Boolean> selector = s.apply(context, child);
selectorsByChildAndSwitcher.get(child).put(s, selector);
return new ObservableValue[] { selector };
});
selectorsByChild.put(child, result);
return new ObservableList[] { result };
}), child -> child.getMetaBinding() != null || selectorsByChildAndSwitcher.get(child).entrySet().stream().allMatch(entry -> !selectorsByChild.get(child).contains(entry.getKey()) || Boolean.TRUE.equals(entry.getValue().getValue())));
}
class FilteredChildContexts<BETWEEN> extends FilteredChildren<Context> {
final ObservableList<Context> filteredSubContexts;
final TransformationObservableList<BETWEEN, Context> transformationListSubContexts;
FilteredChildContexts(MetaBinding<BETWEEN> metaBinding, Tag childTag) {
transformationListSubContexts = new TransformationObservableList<>(metaBinding.buildBetweenChildren(context), (i, between) -> metaBinding.buildModel(context, between), Context::destroy, childContext -> {
ObservableList<TagSwitcher> result = new ObservableListWrapper<>(childTag.getObservableSwitchers(), s -> {
ObservableValue<Boolean> selector = s.apply(childContext, childTag);
selectorsByChildAndSwitcher.get(childContext).put(s, selector);
return new ObservableValue[] { selector };
});
selectorsByChild.put(childContext, result);
return new ObservableList[] { result };
});
filteredSubContexts = new FilteredList<>(transformationListSubContexts, childContext -> selectorsByChildAndSwitcher.get(childContext).entrySet().stream()
.allMatch(entry -> !selectorsByChild.get(childContext).contains(entry.getKey()) || Boolean.TRUE.equals(entry.getValue().getValue())));
}
}
private int computeIndex(int indexInChildren, Tag childElement) {
for (Tag child : context.getRootContext().getObservableChildren(tag)) {
if (child == childElement)
return indexInChildren;
indexInChildren += sizeBySubTag.get(child);
}
return indexInChildren;
}
public Context getModelContext() {
return context;
}
protected RootHtmlDomNode getRootHtmlDomNode() {
return parent.getRootHtmlDomNode();
}
void insertChild(int index) {
parent.incrementSize(tag);
sendAdd(index);
getRootHtmlDomNode().add(getId(), this);
}
private void incrementSize(Tag child) {
sizeBySubTag.put(child, sizeBySubTag.get(child) + 1);
}
private void decrementSize(Tag child) {
int size = sizeBySubTag.get(child) - 1;
assert size >= 0;
if (size == 0)
sizeBySubTag.remove(child);// remove map if empty
else
sizeBySubTag.put(child, size);
}
public Sender getSender() {
return parent.getSender();
}
private final MapChangeListener<String, String> stylesListener = change -> {
if (!change.wasAdded() || change.getValueAdded() == null || change.getValueAdded().equals(""))
sendMessage(new JsonObject().put(MSG_TYPE, REMOVE_STYLE).put(ID, getId()).put(STYLE_PROPERTY, change.getKey()));
else if (change.wasAdded())
sendMessage(new JsonObject().put(MSG_TYPE, ADD_STYLE).put(ID, getId()).put(STYLE_PROPERTY, change.getKey()).put(STYLE_VALUE, change.getValueAdded()));
};
private final MapChangeListener<String, String> attributesListener = change -> {
if (!change.wasAdded() || change.getValueAdded() == null || change.getValueAdded().equals(""))
sendMessage(new JsonObject().put(MSG_TYPE, REMOVE_ATTRIBUTE).put(ID, getId()).put(ATTRIBUTE_NAME, change.getKey()));
else if (change.wasAdded())
sendMessage(new JsonObject().put(MSG_TYPE, ADD_ATTRIBUTE).put(ID, getId()).put(ATTRIBUTE_NAME, change.getKey()).put(ATTRIBUTE_VALUE, change.getValueAdded()));
};
private final SetChangeListener<String> styleClassesListener = change -> {
if (change.wasAdded())
sendMessage(new JsonObject().put(MSG_TYPE, ADD_STYLECLASS).put(ID, getId()).put(STYLECLASS, change.getElementAdded()));
else
sendMessage(new JsonObject().put(MSG_TYPE, REMOVE_STYLECLASS).put(ID, getId()).put(STYLECLASS, change.getElementRemoved()));
};
private final ChangeListener<String> textListener = (o, old, newValue) -> sendMessage(new JsonObject().put(MSG_TYPE, UPDATE_TEXT).put(ID, getId()).put(TEXT_CONTENT, newValue != null ? newValue : ""));
private final Map<Tag, ChangeListener<MetaBinding<?>>> metaBindingListeners = new HashMap<Tag, ChangeListener<MetaBinding<?>>>() {
private static final long serialVersionUID = 6179552869588758790L;
@Override
public ChangeListener<MetaBinding<?>> get(Object key) {
ChangeListener<MetaBinding<?>> listener = super.get(key);
if (listener == null && key instanceof Tag) {
Tag childTag = (Tag) key;
put(childTag, listener = (o, ov, nv) -> {
context.removeTag(childTag);
updateMetaBinding(childTag, nv);
});
}
return listener;
}
};
private final ChangeListener<Number> indexListener = (o, old, newValue) -> {
// System.out.println(new JsonObject().put(MSG_TYPE,
// UPDATE_SELECTION).put(ID, getId()).put(SELECTED_INDEX, newValue !=
// null ? newValue : 0)
// .encodePrettily());
sendMessage(new JsonObject().put(MSG_TYPE, UPDATE_SELECTION).put(ID, getId()).put(SELECTED_INDEX, newValue != null ? newValue : 0));
};
public ChangeListener<Number> getIndexListener() {
return indexListener;
}
public ChangeListener<String> getTextListener() {
return textListener;
}
public MapChangeListener<String, String> getStylesListener() {
return stylesListener;
}
public MapChangeListener<String, String> getAttributesListener() {
return attributesListener;
}
public SetChangeListener<String> getStyleClassesListener() {
return styleClassesListener;
}
public void sendAdd(int index) {
JsonObject jsonObj = new JsonObject().put(MSG_TYPE, ADD);
jsonObj.put(PARENT_ID, getParentId());
jsonObj.put(ID, id);
jsonObj.put(TAG_HTML, getTag().getTag());
jsonObj.put(NEXT_ID, index);
// System.out.println(jsonObj.encodePrettily());
sendMessage(jsonObj);
}
public void sendRemove() {
sendMessage(new JsonObject().put(MSG_TYPE, REMOVE).put(ID, id));
// System.out.println(new JsonObject().put(MSG_TYPE, REMOVE).put(ID,
// id).encodePrettily());
}
public void sendMessage(JsonObject jsonObj) {
jsonObj.put("count", count++);
// if (jsonObj.getString(MSG_TYPE).equals(ADD) ||
// jsonObj.getString(MSG_TYPE).equals(REMOVE))
// System.out.println(jsonObj.encodePrettily());
getSender().send(jsonObj.encode());
}
public String getId() {
return id;
}
public String getParentId() {
return parent.getId();
}
public Tag getTag() {
return tag;
}
public void handleMessage(JsonObject json) {
}
public static class RootHtmlDomNode extends HtmlDomNode {
private final Map<String, HtmlDomNode> nodeById = new HashMap<>();
private final Sender send;
private final String rootId;
public RootHtmlDomNode(Context rootModelContext, RootTag rootTag, String rootId, Sender send) {
super(null, rootModelContext, rootTag);
this.rootId = rootId;
this.send = send;
sendAdd(0);
init(0);
}
@Override
public Sender getSender() {
return send;
}
@Override
protected RootHtmlDomNode getRootHtmlDomNode() {
return this;
}
@Override
public String getParentId() {
return rootId;
}
private Map<String, HtmlDomNode> getMap() {
return nodeById;
}
public HtmlDomNode getNodeById(String id) {
return getMap().get(id);
}
public void add(String id, HtmlDomNode domNode) {
getMap().put(id, domNode);
}
public void remove(String id) {
getMap().remove(id);
}
}
}