-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtme.py
2142 lines (1512 loc) · 71.6 KB
/
htme.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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
HTME | The Hypertext Markup Engine
================================== """
from __future__ import print_function, unicode_literals
from types import GeneratorType
# The ASCII global constants...
empty, tab, newline, space, underscore, quote = "", "\t", "\n", " ", "_", "'"
bar, colon, bang, ask, pound, dollar = "|", ":", "!", "?", "#", "$"
dot, comma, plus, minus, ampersand, at = ".", ",", "+", "-", "&", "@"
modulo, caret, asterisk, equals, semicolon = "%", "^", "*", "=", ";"
slash, backslash, backtick, tilde, doublequote = "/", "\\", "`", "~", '"'
openparen, closedparen, openbracket, closedbracket = "(", ")", "[", "]"
openbrace, closedbrace, openangle, closedangle = "{", "}", "<", ">"
# The generic helper functions...
def read(path): # TODO: look into `io.open` for unicode (bipy) support
"""This simple helper function wraps `file.read` with the idiomatic
with-statement, so we can read from a file in a single expression.
It takes one required arg (`path`) which is a path to the file,
and returns the body of the file as a string."""
with open(path, "r") as file: return file.read()
def readlines(path):
"""This helper function works just like `read`, but returns the file
as a list of lines (instead of a string)."""
with open(path, "r") as file: return file.readlines()
def write(content, path):
"""This helper function complements `read` and `readlines. It wraps
`file.write` with an idiomatic with-statement, so we can write to a
file (creating one if it does not exist) in a single expression. The
function takes two required args (`path` and `content`). The content
can be any object. It is passed to `str`, then written to the file
(replacing anything the file may have already contained) specified
by the path. Once complete, this function returns `None`."""
with open(path, "w+") as file: file.write(str(content))
def writelines(lines, path):
"""This helper function works just like `write`, but its first arg is
a string iterable. Each string is written to the file specified by the
second arg (`path`) as individual lines."""
with open(path, "w+") as file: file.writelines(lines)
def cat(sequence, seperator=""):
"""This function takes one required arg (`sequence`) and an optional arg
(`seperator`) that defaults to an empty string. Each item in the sequence
is passed to `str` and all of the results are concatenated together using
the seperator. The result of the concatenation is returned:
>>> print(cat(["<", "spam", ">"]))
<spam>
>>> print(cat(("spam", "eggs", "spam and eggs"), space))
spam eggs spam and eggs
This function is used extensively throughout the library, just because
it is often a bit prettier than using `join` directly, especially with
the default seperator."""
return seperator.join(str(item) for item in sequence)
def filetype(path, length=1):
"""This helper function takes one required arg (`path`), which should be
filename or path (a string). By default, this function returns everything
after the last dot in `path`, which is useful for getting the extension
from a filename or path:
>>> print(filetype("/static/jquery.min.js"))
js
The function takes an optional second arg (`length`) that defaults to `1`.
The argument must be a positive integer, and specifies how many parts an
extension has. If there are more than one, the dots in between the parts
are included as well:
>>> print(filetype("/static/jquery.min.js", 2))
min.js
This function is used by `Favicon` to automatically generate the `type`
attribute from the `path` argument."""
# split on dots, get `length` parts from the end, join on dots, return
return cat(path.split(dot)[-length:], dot)
# The library specific helper functions...
def flatten(sequence):
"""This function takes one required argument (`sequence`), which is a
potentially nested sequence of child nodes. It flattens the sequence,
then returns the result as a new instance of `Nodes`.
This function is important to the internal API, as it implements the
rules that element constructors and child operators use to flatten
all of their child arguments and operands.
The function treats tuples, lists and instances of their subclasses
(like `Nodes`) as non-terminal, and every other object as terminal
(except for two special cases that are discussed below).
For simplicity, we use integers in a couple of the following examples,
although we would expect the terminal items to be elements and text
nodes in practice:
>>> flatten([0, [], 1, 2, (3), (4, 5, [6]), 7, ((())), [[], 8], [[9]]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Special Case: Generators are internally converted to tuples (by just
passing each generator through `tuple`):
>>> flatten(n * 2 for n in (1, 2, 3))
[2, 4, 6]
Special Case: Element classes are converted to empty instances of the
class (by invoking it with no args):
>>> flatten([DIV, ASIDE]) == flatten([DIV(), ASIDE()])
True
Aside: Other Python Hypertext DSLs use flattening as a core concept. In
HTME, flattening just happens automatically."""
results = Nodes()
terminal = lambda item: not isinstance(item, (list, tuple))
for item in sequence:
# Prevent dicts from being accidently provided as children:
if isinstance(item, dict): raise ValueError("dicts cannot be children")
# Invoke element classes to convert them to element instances:
if type(item) is type and issubclass(item, _Element): item = item()
# Convert generators to tuples (so generator expressions work as args):
elif isinstance(item, GeneratorType): item = tuple(item)
# Append a terminal or recursively flattened non-terminal to `results`:
results += [item] if terminal(item) else flatten(item)
return results
# The concrete container classes...
class Pairs(dict):
"""This class complements `Nodes`. It inherits from `dict`, while `Nodes`
inherits from `list`. Both classes extended their base classes without
modifying any inherited functionality. Elements with `attributes` use
a `Pairs` instance. Those with `children` use `Nodes`. We extend the
builtin containers to make them HTML aware."""
def sorted(self):
"""This method takes no args. It works a lot like the `dict.items`
method, returning two-tuples of key, value pairs.
This method implements a lot of the HTME attribute rendering logic
(simplifying `Configurable.render_attributes`) with three stages:
1) The method first expands the names of any data attributes that use
the dollar syntax.
2) The method then sorts attributes (putting element attributes before
data attributes, sorting each subset asciibetically by name).
3) The method then simplifies and escapes the values, so they are the
exact strings that will be rendered (or `None`).
Note: The term *sequential value* refers to values that are instances
of `tuple`, `list` or a subclass. It does not include strings.
The rest of this docstring contains examples of the different aspects
of the attribute rendering logic...
Attribute names that start with a dollar (`$`) are *data attributes*.
The dollar will be automatically replaced in the rendered output with
the string `data` followed by a hyphen:
>>> DIV({"$visitors": "50000"})
<div data-visitors="50000"></div>
Attribute names are rendered in asciibetical order:
>>> DIV({"aa": "0", "bb": "3", "ab": "1", "ba": "2"})
<div aa="0" ab="1" ba="2" bb="3"></div>
The element attribute's are rendered before any data attributes:
>>> DIV({"aa": "0", "$bb": "3", "$ab": "2", "ba": "1"})
<div aa="0" ba="1" data-ab="2" data-bb="3"></div>
Note: Sorting attribute names in the output is important to making the
rendering process deterministic.
If an attribute's value is a bool, it is converted to a string and
then converted to lowercase:
>>> DIV({"true": True, "false": False})
<div false="false" true="true"></div>
Numerical values are converted to strings:
>>> DIV({"aa": 0, "bb": 3, "ab": 1, "ba": 2})
<div aa="0" ab="1" ba="2" bb="3"></div>
If an attribute's value is a list or tuple (or any subclass), then
each of the values in the sequence are converted according to the
same rules as single values, then joined with spaces to form the
string used in the output:
>>> attributes = {"viewbox": (1, 1, 100, 100)}
>>> attributes["xmlns"] = "http://www.w3.org/2000/svg"
>>> SVG(attributes)
<svg viewbox="1 1 100 100" xmlns="http://www.w3.org/2000/svg"></svg>
Null values are special. If an attribute's value is `None` it will be
left unchanged (the value will still be `None` in the two-tuple that
is returned by this method). This allows `render_attributes` to omit
nullified attributes:
>>> DIV({"class": None})
<div></div>
If a value is sequential and any of its subvalues are `None`, those
values are omitted from the generated string:
>>> DIV({"test": ("string", 1, [2, 3], None)})
<div test="string 1 2 3"></div>
>>> DIV({"test": (0, None, 1, [2, 3], None)})
<div test="0 1 2 3"></div>
Attribute values are escaped in the expectation that they will be
wrapped in double quotes (as `_Configurable.render_attributes` does)
All open angle brackets, ampersands and doublequotes are escaped
automatically:
>>> div = DIV({"foo": "spam & eggs", "bar": '<>"'})
>>> print(div.render_attributes().strip())
bar="<>"" foo="spam & eggs"
"""
def expand(key):
"""This internal helper takes a key that may be spelled using the
shorthand for data attributes (using the dollar prefix). If it is,
the dollar is replaced with the `data` prefix and a hyphen. The
function returns the key (expanded or unchanged)."""
return "data-" + key[1:] if key.startswith(dollar) else key
def convert(value):
"""This internal helper function takes an attribute value or the
subvalue in a sequential value. It returns the equivalent value,
according to the HTME attribute rendering logic (which is always
a string or `None`):
* If `value` is `None`, it is returned.
* If `value` is `True`, the string `true` is returned. If `value`
is `False`, the string `false` is returned (note the case).
* If `value` is a number, the `str` version of `value` is returned.
* The subvalues in sequences (that are not `None`) are recursively
converted according to the same rules as terminal values, then
joined on spaces. The resulting string is returned.
* If none of the above, `value` is passed to `str` to ensure it
is a string, then any open angle brackets, ampersands and
doublequotes are replaced with escape codes (like `&`) """
# map the characters that need escaping to their escape codes...
escapees = {'<': '<', '&': '&', '"': '"'}
if value is None: return value # None
if value is True: return "true" # True
if value is False: return "false" # False
if isinstance(value, (int, float)): return str(value) # Number
if isinstance(value, (list, tuple)): # Array
values = (convert(each) for each in value if each is not None)
return cat(values, space)
return cat(escapees.get(char, char) for char in str(value))
# the data attributes follow any element attributes in the output,
# so they are collected into two lists and sorted independently...
element_attributes, data_attributes = [], []
# iterate over the attributes, expanding keys and converting values,
# creating the two-tuples, and appending each to the correct list...
for key, value in self.items():
key, value = expand(key), convert(value)
if key.startswith("data-"): data_attributes.append((key, value))
else: element_attributes.append((key, value))
# sort both lists of tuples, concatenate them together and return the
# result (`sort` operates on the first item in each tuple (the key),
# and the result is asciibetical)...
element_attributes.sort()
data_attributes.sort()
return element_attributes + data_attributes
class Nodes(list):
"""This class extends `list` without overriding any of the inherited
functionality. The `Pairs` class has a docstring that which explains
how `Pairs` and `Nodes` compliment each other.
Each element's `children` attribute is an instance of this class.
Slice operations on an element's children evaluate to an instance of
this class, which implements operations on slices (operating on each
element in the slice that supports the operator), for example:
element[1:-1] **= {"class": "selected"}
That code updates the class of all but the first and last child of
`element`, skipping any children that do not have attributes."""
@property
def configurable_elements(self):
"""This property returns an iterable of the children in the list
that are instances of `_Configurable`:
>>> children = DIV(P("ElementA"), "ElementB", P("ElementC"))[:]
>>> for element in children.configurable_elements: print(element)
<p>ElementA</p>
<p>ElementC</p>
"""
return (child for child in self if isinstance(child, _Configurable))
@property
def parental_elements(self):
"""This property returns an iterable of the children in the list
that are instances of `_Parental`:
>>> children = DIV(IMG({"src": "img.png"}), "Text", P("Open"))[:]
>>> for element in children.parental_elements: print(element)
<p>Open</p>
"""
return (child for child in self if isinstance(child, _Parental))
def __ipow__(self, attributes):
"""This method implements the `**=` operator:
>>> div = DIV(P("ALI"), P("BOB"), P("CAZ"))
>>> div[1:] **= {"class": "foo"}
>>> div
<div><p>ALI</p><p class="foo">BOB</p><p class="foo">CAZ</p></div>
"""
for child in self.configurable_elements: child **= attributes
def __ifloordiv__(self, attributes):
"""This method implements the `//=` operator:
>>> div = DIV(P("ALI"), P({"class": "foo"}, "BOB"), P("CAZ"))
>>> div[1:] //= {"class": "bar"}
>>> div
<div><p>ALI</p><p class="bar">BOB</p><p class="bar">CAZ</p></div>
"""
for child in self.configurable_elements: child //= attributes
def __imul__(self, families):
"""This method implements the `*=` operator:
>>> div = DIV(P("ALI"), P("BOB"))
>>> div[:] *= SPAN("SUB")
>>> div
<div><p>ALI<span>SUB</span></p><p>BOB<span>SUB</span></p></div>
"""
for child in self.parental_elements: child *= families
def __idiv__(self, families):
"""This method implements the `/=` operator:
>>> div = DIV(P("ALI"), P("BOB"))
>>> div[:] /= SPAN("SUB")
>>> div
<div><p><span>SUB</span></p><p><span>SUB</span></p></div>
"""
for child in self.parental_elements: child /= families
def __getitem__(self, arg):
"""This method overrides `list.__getitem__` to ensure slices of
slices recursively evaluate to `Nodes` (not `list`), which
depends on this method in Python 3.
>>> DIV(P("ALI"), P("BOB"), P("CAZ"))[:][1]
<p>BOB</p>
Note: Python invokes different methods to handle slice operations,
depending on whether it is Python 2 or 3."""
result = super(Nodes, self).__getitem__(arg)
return Nodes(result) if type(result) is list else result
def __setitem__(self, *args):
"""This method ensures slices of slices recursively evaluate to
`Nodes` (not `list`) in Python 3.
>>> children = DIV(P("ALI"), P("BOB"), P("CAZ"))[:-1]
>>> children[1] = ASIDE("REPLACEMENT")
>>> children
[<p>ALI</p>, <aside>REPLACEMENT</aside>]
>>> SECTION(children)
<section><p>ALI</p><aside>REPLACEMENT</aside></section>
Note: Python invokes different methods to handle slice operations,
depending on whether it is Python 2 or 3."""
if type(args[0]) is slice: return self[args[0]]
else: super(Nodes, self).__setitem__(*args)
def __getslice__(self, start, end=None):
"""This method ensures slices of slices recursively evaluate to
`Nodes` (not `list`) in Python 2.
>>> div = DIV(P("ALI"), P("BOB"))
>>> type(div[:]).__name__
'Nodes'
>>> type(div[:][:]).__name__
'Nodes'
Note: Python invokes different methods to handle slice operations,
depending on whether it is Python 2 or 3."""
return Nodes(self[slice(start, end)])
def __setslice__(self, start, end, other):
"""This method ensures slices of slices recursively evaluate to
`Nodes` (not `list`) in Python 2:
>>> div = DIV(P("ALI"), P({"class": "foo"}, "BOB"), P("CAZ"))
>>> div[1:][:] **= {"class": "bar"}
>>> div
<div><p>ALI</p><p class="bar">BOB</p><p class="bar">CAZ</p></div>
>>> div = DIV(P("ALI"), P("BOB"), P("CAZ"))
>>> div[1:][:] /= "REPLACEMENT"
>>> div
<div><p>ALI</p><p>REPLACEMENT</p><p>REPLACEMENT</p></div>
Note: Python invokes different methods to handle slice operations,
depending on whether it is Python 2 or 3."""
return self[start:end]
__itruediv__ = __idiv__
def blit(self, index, *children):
"""This method takes a required arg (`index`), followed by one or more
children. It swaps the item that is currently at the index with the
child elements (in the order they were passed in):
>>> div = DIV(P("A"), P("B"), P("C"))
>>> div.children.blit(0, SPAN("X"))
>>> div
<div><span>X</span><p>B</p><p>C</p></div>
>>> div.children.blit(1, [SPAN("Y"), SPAN("Z")])
>>> div
<div><span>X</span><span>Y</span><span>Z</span><p>C</p></div>
"""
# Flatten the values, then reverse them, so they can be iteratively
# blitted into the array and end up back in the same order:
children = flatten(children)
children.reverse()
# Remove the single item being blitted over, then insert each of the
# new items, one by one:
del self[index]
for child in children: self.insert(index, child)
# The feature mixins for adding blocks of functionality to the abstract
# element classes...
class _Tagged(object):
"""This mixin provides abstract element classes with support for tag
names by implementing their `tagname` property."""
@property
def tagname(self):
"""This computed property returns the tag name, which is computed
from a class name by converting it to lowercase, then replacing
each underscore with a hyphen.
The property is computed so that an element instance can have its
class reassigned (this is not officially supported, as it is only
safe if you use a class with the same abstract element class):
>>> element = LINK()
>>> element **= {"src": "img.png"}
>>> element.__class__ = IMG
>>> element
<img src="img.png">
The method iterates over the method resolution order, looking for
the first class name that does not change when it is converted to
uppercase. This allows element subclasses to inherit their names
from a standard element base class (subclasses always include at
least one lowercase character in their names):
>>> class Foo(DIV): pass
>>> Foo()
<div></div>
Note: If a name starts with an underscore, that character is treated
as though it is not there (this feature is used internally):
>>> class _FAKE(VoidElement): pass
>>> _FAKE()
<fake>
>>> class _FAKE(NormalElement): pass
>>> _FAKE()
<fake></fake>
>>> class _FAKE(ForeignElement): pass
>>> _FAKE()
<fake/>
"""
# iterate over the element's class and parent classes in the order
# of inheritance (the method resolution order (the mro))
for Class in self.__class__.__mro__:
name = Class.__name__ # get the name of the class as a string
# if the name changes when converted to uppercase, it is not a
# standard element class, so we need to move on to the next one
if name.upper() != name: continue
# now we have the right class name, remove any leading underscore
# (they are only used to prevent internal classes being exported)
if name[0] == underscore: name = name[1:]
# convert to lowercase, replace underscores with hyphens, return
return name.lower().replace(underscore, minus)
class _Configurable(object):
"""This mixin provides abstract element classes with *configurability*.
It implements attribute operators and the `render_attributes` method.
If this mixin is used with `_Parental` then `_Parental` should be mixed
in first. See `_Parental` below for more details."""
def __ipow__(self, other):
"""This method allows the `**=` operator to be used to merge a dict
of attributes with the element attributes:
>>> img = IMG()
>>> img **= {"src": "img.png"}
>>> img
<img src="img.png">
"""
self.attributes.update(other)
return self
def __ifloordiv__(self, other):
"""This method allows the `//=` operator to be used to assign a new
dict of attributes to `self.attributes`:
>>> img = IMG({"src": "img.png"})
>>> img //= {"src": "mugshot.png", "class": "selected"}
>>> img
<img class="selected" src="mugshot.png">
Note: This method mutates the attributes in place.
Note: This method complements `NormalElement.__idiv__`, which provides
similar functionality for replacing children."""
# cannot assign `other` as we need to mutate the container in place
self.attributes.clear()
self.attributes.update(other)
return self
def __getitem__(self, name):
"""This method allows the square brackets suffix operator to be used
to access element attributes by name:
>>> img = IMG({"src": "img.png"})
>>> print(img["src"])
img.png
Note: This method complements `NormalElement.__getitem__`, which also
supports accessing children."""
return self.attributes[name]
def __setitem__(self, name, other):
"""This method complements the `Element.__getitem__` method, allowing
single attributes to be updated:
>>> img = IMG({"src": "img.png"})
>>> img["src"] = "mugshot.png"
>>> print(img["src"])
mugshot.png
Note: The `**=` and `//=` operators can update multiple attributes in
a single invocation."""
self.attributes[name] = other
return self
def __eq__(self, other):
"""This method checks whether two elements are equal by checking that
they both evaluate to the same string:
>>> x = IMG({"src": "img.png", "class": "selected"})
>>> y = IMG({"class": "selected", "src": "img.png"})
>>> x == y
True
"""
return repr(self) == repr(other)
def __ne__(self, other):
"""This method checks that two elements are not equal by checking that
they both evaluate to different strings:
>>> x = IMG({"src": "img.png", "class": "selected"})
>>> y = IMG({"class": "selected", "src": "img.png"})
>>> x != y
False
"""
return repr(self) != repr(other)
def __len__(self):
"""This method complements `NormalElement.__len__`, but it only ever
returns zero as `VoidElement` instances have no children.
>>> len(IMG({"src": "img.png"})) == 0
True
"""
return 0
def render_attributes(self):
"""This helper method renders the attributes dict, as the attributes
would be appear in a HTML opening tag.
This method is generally only used internally, though users can access
it if they want to use it.
If an attribute has an empty string as its value, the method
outputs it as a boolean attribute.
>>> DIV({"contenteditable": ""})
<div contenteditable></div>
If an attribute's value is `None`, the attribute is not rendered
at all:
>>> DIV({"foo": None, "bar": "include"})
<div bar="include"></div>
"""
if not self.attributes: return ""
results = []
for key, value in self.attributes.sorted():
if value is None: continue # ignore null attributes
elif value == "": results.append(key) # fix boolean attributes
else: results.append('{}="{}"'.format(key, value)) # normal pairs
return space + cat(results, space) if results else ""
class _Parental(object):
"""This mixin makes abstract element classes *parental*. It implements
the child operators and the `render_children` method.
If this mixin is mixed with the `_Configurable` mixin, then this class
must come first in the MRO. This class provides methods for getting and
setting items (using the square brackets operator) that will correctly
distinguish between keys, indexes and slices. `_Configurable` also
implements those methods, but they always expect keys."""
def __imul__(self, *families):
"""This method allows families to be appended to `self.children`,
using the `*=` operator:
>>> ul = UL({"class": "nav"})
>>> ul *= LI("Coffee"), LI("Tea"), LI("Milk")
>>> print(ul)
<ul class="nav"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
Note: `Document.__imul__` operates the same way, operating on the
`Document.tree` element."""
self.children += flatten(families)
return self
def __idiv__(self, *families):
"""This method allows families to be assigned to `self.children`,
replacing any existing children, using the `/=` operator:
>>> ul = UL(LI("Coffee"), LI("Tea"))
>>> ul /= LI("Milk")
>>> print(ul)
<ul><li>Milk</li></ul>
Note: This method mutates the list of children in place.
Note: The `NormalElement.__itruediv__` method is aliased to this one,
as Python 3 renamed it and changed its semantics (the differences
do not affect the operator's HTME semantics).
Note: `Document.__idiv__` maps this method to the tree. """
# This is slightly convoluted, but a slice of `Nodes` is not the same
# instance as the instance it is a slice of, so we have to juggle the
# values a bit to replace all the children in the original container:
del self.children[:]
self.children += flatten(families)
return self
def __getitem__(self, arg):
"""This method allows the square brackets suffix operator to be used
to access element attributes by name and children by index:
>>> ul = UL({"class": "nav"}, LI("Coffee"), LI("Tea"), LI("Milk"))
>>> print(ul["class"])
nav
>>> print(ul[1])
<li>Tea</li>
>>> print(ul[1][0])
Tea
The method also supports slicing an element into an instance of
`Nodes` containing the children expressed by the slice.
>>> print(UL(LI("Coffee"), LI("Tea"), LI("Milk"))[1:])
[<li>Tea</li>, <li>Milk</li>]
Note: For doctests operating on slices see, `Nodes`."""
# If the arg is an int, return the child at that index. If the arg is
# a slice, return an instance of `Nodes` containing the contents of
# the slice. Otherwise, treat the arg as an attributes dict key,
# and return its value:
if isinstance(arg, int): return self.children[arg]
elif isinstance(arg, slice): return Nodes(self.children[arg])
else: return self.attributes[arg]
def __setitem__(self, arg, other):
"""This method complements `__getitem__`, handling assignments to
keys, indexes and slices:
>>> ul = UL({"class": "nav"}, LI("Coffee"), LI("Tea"), LI("Milk"))
>>> ul["class"] = "buttons"
>>> ul[1] = P("replacement")
>>> print(ul)
<ul class="buttons"><li>Coffee</li><p>replacement</p><li>Milk</li></ul>
>>> ul = UL(DIV("content"))
>>> ul[0] = LI(), LI(), LI()
>>> print(ul)
<ul><li></li><li></li><li></li></ul>
Note: For doctests operating on slices see, `Nodes`."""
# This makes the same distinction as `__getitem__`, but assigns to
# the index, attribute or list of `Nodes` expressed by a slice:
if isinstance(arg, int): self.children.blit(arg, other)
elif isinstance(arg, slice): return Nodes(self.children[arg])
else: self.attributes[arg] = other
def __len__(self):
"""This method implements `len(element)`, returning the total number
of children the element has:
>>> ul = UL({"class": "nav"}, LI("Coffee"), LI("Tea"), LI("Milk"))
>>> len(ul) == 3
True
"""
return len(self.children)
def __iter__(self):
"""This method allows iteration over an open element's children (by
doing something like `child for child in element`):
>>> ul = UL(LI("Coffee"), LI("Tea"), LI("Milk"))
>>> for li in ul: print(li)
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
"""
for child in self.children: yield child
__itruediv__ = __idiv__
def render_children(self):
"""This method complements `_Configurable.render_attributes`, and
turns the list of children into HTML by simply concatenating them
all together:
>>> ul = UL(LI("Coffee"), LI("Tea"), LI("Milk"))
>>> print(ul.render_children())
<li>Coffee</li><li>Tea</li><li>Milk</li>
This method is generally used internally, though it is exposed to
users, so they can use it if they wish."""
return cat(self.children)
class Signature0(object):
def __init__(self, attributes=None):
"""This method implements Signature 0, which takes one optional arg
(`attributes`). If the arg is an instance of `Pairs`, it is used as
the element's `attributes` property. If the arg is a dict, it is
passed to `Pairs` and the result is used. If the arg is `None`,
an empty `Pairs` instance is used:
>>> IMG()
<img>
>>> IMG({"src": "img.png"})
<img src="img.png">
Note: This method also ensures elements have a freezer."""
self.attributes = self.signature(attributes)
self.freezer = {}
@staticmethod
def signature(attributes):
"""This static method implements the signature, so it can be used by
subclasses that override the init method."""
if isinstance(attributes, Pairs): return attributes
return Pairs({} if attributes is None else attributes)
class Signature1(object):
def __init__(self, *children):
"""This method implements Signature 1, which takes zero or more
children, which are flattened into a `Nodes` instance, which is
then used as the element's `children` attribute:
>>> print(UL({"class": "nav"}, LI("Coffee"), LI("Tea"), LI("Milk")))
<ul class="nav"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
Note: This method also ensures elements have a freezer."""
self.children = self.signature(children)
self.freezer = {}
@staticmethod
def signature(children):
"""This static method implements the signature, so it can be used by
subclasses that override the init method. The signature is so simple
that this method is not very useful in itself, but all three classes
that implement element signatures have the same API, and the other
two have more complex signatures."""
return flatten(children)
class Signature2(object):
def __init__(self, *args):
"""This method implements Signature 2, which takes an optional
attibutes dict, followed by zero or more children. It does the
same thing as Signature 0 with any attributes and the same as
Signature 1 with any children:
>>> print(UL({"class": "nav"}, LI("Coffee"), LI("Tea"), LI("Milk")))
<ul class="nav"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
Note: This method also ensures elements have a freezer."""
self.attributes, self.children = self.signature(args)
self.freezer = {}
@staticmethod
def signature(args):
"""This static method implements the signature, so it can be used by
subclasses that override the init method."""
args = list(args)
attributes = args.pop(0) if args and isinstance(args[0], dict) else {}
if isinstance(attributes, Pairs): return attributes, flatten(args)
return Pairs(attributes), flatten(args)
# The abstract element base class...
class _Element(object):
"""This is the abstract base class that all elements ultimately inherit
from. It implements the common functionality (the freezer and `write`
method) that all elements support."""
def __call__(self, key, *args, **kargs):
"""This method makes it possible to access and format frozen elements
by invoking the instance, passing in the key for the frozen element.
Users can also pass args and keyword args, which just get passed on
to the `str.format` method, which is called on the frozen string
before it is returned:
>>> img = IMG({"src": "{IMG}.png"})
>>> img.freeze("foo")
>>> print(img("foo", IMG="mugshot"))
<img src="mugshot.png">
"""
return self.freezer[key].format(*args, **kargs)
def freeze(self, key):
"""This method freezes the current state of the element, turning it
into a string of HTML. The one required arg is the key used to store
the frozen element in `self.freezer`.