-
Notifications
You must be signed in to change notification settings - Fork 17
/
html.py
930 lines (655 loc) · 20 KB
/
html.py
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
"""
Copyright (c) 2017-2019, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file LICENSE.txt, distributed with this software.
Created on Apr 2, 2017
@author: jrm
"""
from __future__ import annotations
from typing import Any, Generator, Optional
from atom.api import (
Atom,
Event,
Bool,
Enum,
ContainerList,
Dict,
Value,
Int,
Str,
Instance,
ForwardTyped,
Typed,
Coerced,
observe,
set_default,
)
from enaml.core.declarative import d_, Declarative
from enaml.widgets.toolkit_object import ToolkitObject, ProxyToolkitObject
ChangeDict = dict[str, Any]
try:
from web.core.speedups import gen_id, lookup_child_index
except ImportError as e:
def lookup_child_index(parent: "Tag", child: "Tag") -> int:
"""Find the index of the child ignoring any pattern nodes"""
i = 0
for c in parent.children:
if c is child:
return i
elif isinstance(c, Tag):
i += 1
raise KeyError("Child not found")
def gen_id(tag, id=id, mod=divmod):
"""Generate a short id for the tag"""
number = id(tag)
output = ""
alpha = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
while number:
number, digit = mod(number, 59)
output += alpha[digit]
return output
class ProxyTag(ProxyToolkitObject):
#: Reference to the declaration
declaration = ForwardTyped(lambda: Tag)
#: A cached reference to the root element.
#: WARNING: If the root is changed this becomes invalid
root = ForwardTyped(lambda: ProxyTag)
def xpath(self, query: str, **kwargs) -> Generator[ProxyToolkitObject, None, None]:
"""Perform an xpath lookup on the node"""
raise NotImplementedError
def render(self, method: str = "html", encoding: str = "unicode", **kwargs) -> str:
"""Render the node and all children"""
raise NotImplementedError
def set_attribute(self, name: str, value: Any):
raise NotImplementedError
class Tag(ToolkitObject):
#: Reference to the proxy object
proxy = Typed(ProxyTag)
#: Object ID
id = d_(Str()).tag(attr=False)
#: Tag name
tag = d_(Str()).tag(attr=False)
#: CSS classes
cls = d_(Instance((list, tuple, str))).tag(attr=False)
#: CSS styles
style = d_(Instance((dict, str))).tag(attr=False)
#: Node text
text = d_(Str()).tag(attr=False)
#: Node tail text
tail = d_(Str()).tag(attr=False)
#: Alt attribute
alt = d_(Str()).tag(attr=False)
#: Custom attributes not explicitly defined
attrs = d_(Dict()).tag(attr=False)
#: JS onclick definition
onclick = d_(Str()).tag(attr=False)
#: Used to tell js to send click events back to the server
clickable = d_(Coerced(bool)).tag(attr=False)
#: Used to tell js to send drag events back to the server and sets the
#: draggable attribute. Must be used with ondragstart.
draggable = d_(Coerced(bool)).tag(attr=False)
#: JS ondragstart definition
ondragstart = d_(Str()).tag(attr=False)
#: JS ondragover definition
ondragover = d_(Str()).tag(attr=False)
#: JS ondragend definition
ondragend = d_(Str()).tag(attr=False)
#: JS ondragenter definition
ondragenter = d_(Str()).tag(attr=False)
#: JS ondragleave definition
ondragleave = d_(Str()).tag(attr=False)
#: JS ondrop definition
ondrop = d_(Str()).tag(attr=False)
#: Event triggered on click
clicked = d_(Event())
#: Event triggered when a drag starts
dragstart = d_(Event())
#: Event triggered when a drag ends
dragend = d_(Event())
#: Event triggered when a node is dragged over a valid drop target
dragenter = d_(Event(ToolkitObject))
#: Event triggered when a node leaves a valid drop target
dragleave = d_(Event(ToolkitObject))
#: Event triggered when a drop occurs
dropped = d_(Event(ToolkitObject))
def _default_id(self):
return gen_id(self)
@observe(
"id",
"tag",
"cls",
"style",
"text",
"tail",
"alt",
"attrs",
"clickable",
"draggable",
"onclick",
"ondragstart",
"ondragover",
"ondragend",
"ondragenter",
"ondragleave",
"ondrop",
)
def _update_proxy(self, change: ChangeDict):
"""Update the proxy widget when the Widget data changes.
This also notifies the root that the dom has been modified.
"""
if self.proxy_is_active and change["type"] == "update":
name = change["name"]
value = change["value"]
proxy = self.proxy
assert proxy is not None
handler = getattr(proxy, f"set_{name}", None)
if handler is not None:
handler(value)
else:
proxy.set_attribute(name, value)
root = proxy.root
if root is not None and root.rendered:
self._notify_modified(
root.declaration,
{
"id": self.id,
"type": change["type"],
"name": name,
"value": value,
"oldvalue": change["oldvalue"],
},
)
# =========================================================================
# Object API
# =========================================================================
def child_added(self, child: Declarative):
super().child_added(child)
if self.proxy_is_active and isinstance(child, Tag):
proxy = self.proxy
assert proxy is not None
root = proxy.root
assert root is not None
if root.rendered:
self._notify_modified(
root.declaration,
{
"id": self.id,
"type": "added",
"name": "children",
"value": child.render(),
"index": self._child_index(child),
},
)
def child_moved(self, child: Declarative):
super().child_moved(child)
if self.proxy_is_active and isinstance(child, Tag):
proxy = self.proxy
assert proxy is not None
root = proxy.root
assert root is not None
if root.rendered and proxy.child_moved(child.proxy):
self._notify_modified(
root.declaration,
{
"id": self.id,
"type": "moved",
"name": "children",
"value": child.id,
"index": self._child_index(child),
},
)
def child_removed(self, child: Declarative):
"""Handles the child removed event.
This will generate a modified event indicating which child was removed.
"""
super().child_removed(child)
if self.proxy_is_active and isinstance(child, Tag):
proxy = self.proxy
assert proxy is not None
root = proxy.root
assert root is not None
if root.rendered:
self._notify_modified(
root.declaration,
{
"id": self.id,
"type": "removed",
"name": "children",
"value": child.id,
},
)
def _notify_modified(self, root: Optional[Tag], change: ChangeDict):
"""Trigger a modified event on the root node. Subclasses may override
this to update change parameters if needed.
"""
if root is not None:
root.modified(change)
def _child_index(self, child: Tag) -> int:
"""Find the index of the child ignoring any pattern nodes"""
return lookup_child_index(self, child)
# =========================================================================
# Tag API
# =========================================================================
def xpath(self, query: str, **kwargs) -> list[Tag]:
"""Find nodes matching the given xpath query
Parameters
----------
query: str
The xpath query to run
kwargs: dict
Parameters to xpath.
Returns
-------
nodes: List[Tag]
List of tags matching the xpath query.
"""
proxy = self.proxy
assert proxy is not None
return [n.declaration for n in proxy.xpath(query, **kwargs)]
def prepare(self, **kwargs: dict[str, Any]):
"""Prepare this node for rendering.
This sets any attributes given, initializes and actives the proxy
as needed.
"""
for k, v in kwargs.items():
setattr(self, k, v)
if not self.is_initialized:
self.initialize()
if not self.proxy_is_active:
self.activate_proxy()
def render(
self, render_options: Optional[dict] = None, **kwargs: dict[str, Any]
) -> str:
"""Render this tag and all children to a string.
Parameters
-------
render_options: dict
Options to pass to render
kwargs: dict
Attributes to set on the view
Returns
-------
html: str
The rendered html content of the node.
"""
self.prepare(**kwargs)
proxy = self.proxy
assert proxy is not None
if render_options:
return proxy.render(**render_options)
return proxy.render()
class Html(Tag):
__slots__ = "__weakref__"
#: Set the tag name
tag = set_default("html")
#: Dom modified event. This will fire when any child node is updated, added
#: or removed. Observe this event to handle updating websockets.
modified = d_(Event(dict), writable=False).tag(attr=False)
class Head(Tag):
#: Set the tag name
tag = set_default("head")
class Body(Tag):
#: Set the tag name
tag = set_default("body")
class Title(Tag):
#: Set the tag name
tag = set_default("title")
class P(Tag):
#: Set the tag name
tag = set_default("p")
class H1(Tag):
#: Set the tag name
tag = set_default("h1")
class H2(Tag):
#: Set the tag name
tag = set_default("h2")
class H3(Tag):
#: Set the tag name
tag = set_default("h3")
class H4(Tag):
#: Set the tag name
tag = set_default("h4")
class H5(Tag):
#: Set the tag name
tag = set_default("h5")
class H6(Tag):
#: Set the tag name
tag = set_default("h6")
class Hr(Tag):
#: Set the tag name
tag = set_default("hr")
class Br(Tag):
#: Set the tag name
tag = set_default("br")
class Pre(Tag):
#: Set the tag name
tag = set_default("pre")
class Kbd(Tag):
#: Set the tag name
tag = set_default("kbd")
class Samp(Tag):
#: Set the tag name
tag = set_default("samp")
class Var(Tag):
#: Set the tag name
tag = set_default("var")
class Div(Tag):
#: Set the tag name
tag = set_default("div")
class Span(Tag):
#: Set the tag name
tag = set_default("span")
class A(Tag):
#: Set the tag name
tag = set_default("a")
#: Set the url
href = d_(Str())
#: Set the target options
target = d_(Enum("", "_blank", "_self", "_parent", "_top", "framename"))
@observe("href", "target")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class B(Tag):
#: Set the tag name
tag = set_default("b")
class I(Tag):
#: Set the tag name
tag = set_default("i")
class Strong(Tag):
#: Set the tag name
tag = set_default("strong")
class Em(Tag):
#: Set the tag name
tag = set_default("em")
class Mark(Tag):
#: Set the tag name
tag = set_default("mark")
class Small(Tag):
#: Set the tag name
tag = set_default("small")
class Del(Tag):
#: Set the tag name
tag = set_default("del")
class Ins(Tag):
#: Set the tag name
tag = set_default("ins")
class Sub(Tag):
#: Set the tag name
tag = set_default("sub")
class Sup(Tag):
#: Set the tag name
tag = set_default("sup")
class Q(Tag):
#: Set the tag name
tag = set_default("q")
class Blockquote(Tag):
#: Set the tag name
tag = set_default("blockquote")
cite = d_(Str())
@observe("cite")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Abbr(Tag):
#: Set the tag name
tag = set_default("abbr")
class Address(Tag):
#: Set the tag name
tag = set_default("address")
class Cite(Tag):
#: Set the tag name
tag = set_default("cite")
class Bdo(Tag):
#: Set the tag name
tag = set_default("bdo")
dir = d_(Str())
class Img(Tag):
#: Set the tag name
tag = set_default("img")
src = d_(Str())
width = d_(Str())
height = d_(Str())
@observe("src", "width", "height")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Style(Tag):
#: Set the tag name
tag = set_default("style")
class Link(Tag):
#: Set the tag name
tag = set_default("link")
type = d_(Str())
rel = d_(Str())
href = d_(Str())
media = d_(Str())
@observe("type", "rel", "href", "media")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Map(Tag):
#: Set the tag name
tag = set_default("map")
name = d_(Str())
@observe("name")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Area(Tag):
#: Set the tag name
tag = set_default("area")
shape = d_(Str())
coords = d_(Str())
href = d_(Str())
@observe("shape", "coords", "href")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Table(Tag):
#: Set the tag name
tag = set_default("table")
class Tr(Tag):
#: Set the tag name
tag = set_default("tr")
class Td(Tag):
#: Set the tag name
tag = set_default("td")
colspan = d_(Str())
rowspan = d_(Str())
@observe("colspan", "rowspan")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Th(Tag):
#: Set the tag name
tag = set_default("th")
colspan = d_(Str())
rowspan = d_(Str())
@observe("colspan", "rowspan")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class THead(Tag):
#: Set the tag name
tag = set_default("thead")
class TBody(Tag):
#: Set the tag name
tag = set_default("tbody")
class TFoot(Tag):
#: Set the tag name
tag = set_default("tfoot")
class Caption(Tag):
#: Set the tag name
tag = set_default("caption")
class Ul(Tag):
#: Set the tag name
tag = set_default("ul")
class Ol(Tag):
#: Set the tag name
tag = set_default("ol")
type = d_(Enum("", "1", "A", "a", "I", "i"))
@observe("type")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Li(Tag):
#: Set the tag name
tag = set_default("li")
class Dl(Tag):
#: Set the tag name
tag = set_default("dl")
class Dt(Tag):
#: Set the tag name
tag = set_default("dt")
class Dd(Tag):
#: Set the tag name
tag = set_default("dd")
class IFrame(Tag):
#: Set the tag name
tag = set_default("iframe")
src = d_(Str())
height = d_(Str())
width = d_(Str())
target = d_(Str())
@observe("src", "height", "width", "target")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Script(Tag):
#: Set the tag name
tag = set_default("script")
src = d_(Str())
type = d_(Str())
@observe("type", "src")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class NoScript(Tag):
#: Set the tag name
tag = set_default("noscript")
class Meta(Tag):
#: Set the tag name
tag = set_default("meta")
name = d_(Str())
content = d_(Str())
@observe("name", "content")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Base(Tag):
#: Set the tag name
tag = set_default("base")
href = d_(Str())
target = d_(Enum("", "_blank", "_self", "_parent", "_top", "framename"))
@observe("href", "target")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Header(Tag):
#: Set the tag name
tag = set_default("header")
class Nav(Tag):
#: Set the tag name
tag = set_default("nav")
class Section(Tag):
#: Set the tag name
tag = set_default("section")
class Aside(Tag):
#: Set the tag name
tag = set_default("aside")
class Article(Tag):
#: Set the tag name
tag = set_default("article")
class Footer(Tag):
#: Set the tag name
tag = set_default("footer")
class Summary(Tag):
#: Set the tag name
tag = set_default("summary")
class Details(Tag):
#: Set the tag name
tag = set_default("details")
class Form(Tag):
#: Set the tag name
tag = set_default("form")
action = d_(Str())
method = d_(Enum("post", "get"))
@observe("action", "method")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Fieldset(Tag):
#: Set the tag name
tag = set_default("fieldset")
class Legend(Tag):
#: Set the tag name
tag = set_default("legend")
class Label(Tag):
#: Set the tag name
tag = set_default("label")
class Select(Tag):
#: Set the tag name
tag = set_default("select")
name = d_(Str())
value = d_(Str())
disabled = d_(Coerced(bool))
def _default_name(self):
return self.id
@observe("name", "value", "disabled")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Option(Tag):
#: Set the tag name
tag = set_default("option")
value = d_(Str())
selected = d_(Coerced(bool))
@observe("value", "selected")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class OptGroup(Tag):
#: Set the tag name
tag = set_default("optgroup")
label = d_(Str())
disabled = d_(Coerced(bool))
@observe("label", "disabled")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Input(Tag):
#: Set the tag name
tag = set_default("input")
name = d_(Str())
type = d_(Str())
placeholder = d_(Str())
disabled = d_(Coerced(bool))
checked = d_(Coerced(bool))
value = d_(Value())
def _default_name(self):
return self.id
@observe("name", "type", "disabled", "checked", "value", "placeholder")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Textarea(Tag):
#: Set the tag name
tag = set_default("textarea")
name = d_(Str())
rows = d_(Str())
cols = d_(Str())
disabled = d_(Coerced(bool))
def _default_name(self):
return self.id
@observe("name", "rows", "cols", "disabled")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Button(Tag):
#: Set the tag name
tag = set_default("button")
name = d_(Str())
type = d_(Str())
value = d_(Str("1"))
def _default_name(self):
return self.id
@observe("type")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Video(Tag):
#: Set the tag name
tag = set_default("video")
controls = d_(Coerced(bool))
@observe("controls")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)
class Source(Tag):
#: Set the tag name
tag = set_default("source")
src = d_(Str())
type = d_(Str())
@observe("src", "type")
def _update_proxy(self, change: ChangeDict):
super()._update_proxy(change)