|
| 1 | +from pyscript import window, document |
| 2 | + |
| 3 | +SHOW_COMMENT = window.NodeFilter.SHOW_COMMENT |
| 4 | + |
| 5 | +already_parsed = {} |
| 6 | + |
| 7 | +# accepts a t-string template, returns a JS DOM node 🤯 |
| 8 | +def domdom(template): |
| 9 | + strings = template.strings |
| 10 | + if strings in already_parsed: |
| 11 | + content = already_parsed[strings].cloneNode(True) |
| 12 | + else: |
| 13 | + interpolations = template.interpolations |
| 14 | + el = document.createElement('template') |
| 15 | + |
| 16 | + # create unique content that can be understood by the parser |
| 17 | + el.innerHTML = '<!--🐍-->'.join(strings) |
| 18 | + content = el.content |
| 19 | + already_parsed[strings] = el.content |
| 20 | + |
| 21 | + tw = document.createTreeWalker(content, SHOW_COMMENT) |
| 22 | + i = 0 |
| 23 | + while True : |
| 24 | + node = tw.nextNode() |
| 25 | + if node is None: break |
| 26 | + if node.data == '🐍': |
| 27 | + node.replaceWith(interpolations[i].value.node) |
| 28 | + i += 1 |
| 29 | + |
| 30 | + return content |
| 31 | + |
| 32 | + |
| 33 | +class Text: |
| 34 | + def __init__(self, value, node=None): |
| 35 | + self._value = str(value) |
| 36 | + self.node = document.createTextNode(self._value) if node is None else node |
| 37 | + |
| 38 | + @property |
| 39 | + def value(self): |
| 40 | + return self._value |
| 41 | + |
| 42 | + @value.setter |
| 43 | + def value(self, value): |
| 44 | + self._value = str(value) |
| 45 | + self.node.data = self._value |
| 46 | + |
| 47 | + def __str__(self): |
| 48 | + return f'#text: {self._value}' |
| 49 | + |
| 50 | + # just to demo JS string casting |
| 51 | + def toString(self): |
| 52 | + return str(self) |
| 53 | + |
| 54 | + |
| 55 | +# create a new text and leak it for demo purposes |
| 56 | +content = Text('Hello World!') |
| 57 | +window.content = content |
| 58 | + |
| 59 | +print(f"<div>{content}</div>") |
| 60 | + |
| 61 | +# see domdom in action 🥳 |
| 62 | +document.body.append( |
| 63 | + domdom( |
| 64 | + t"<div>{content}</div>" |
| 65 | + ), |
| 66 | + # domdom( |
| 67 | + # t"<div>{content}</div>" |
| 68 | + # ) |
| 69 | +) |
0 commit comments