Skip to content

Instantly share code, notes, and snippets.

@SealtielFreak
Last active December 10, 2023 01:01
Show Gist options
  • Save SealtielFreak/e94612dbccb666d8c97fd210d6826594 to your computer and use it in GitHub Desktop.
Save SealtielFreak/e94612dbccb666d8c97fd210d6826594 to your computer and use it in GitHub Desktop.
"""
MIT License
Copyright (c) 2023 D. Sealtiel Valderrama
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import abc
import collections.abc
import browser
import browser.html
import browser.worker
def to_came_case(_str: str) -> str:
_str = _str.split("_")
return _str[0] + "".join(
map(lambda _str: _str.capitalize(), _str[1:])
)
def create_html_element(elm: str, *args, **kwargs):
return getattr(browser.html, elm.upper())(*args, **kwargs)
def isiterable(_obj) -> bool:
return isinstance(_obj, collections.abc.Iterable)
def isdict(_obj) -> bool:
return isinstance(_obj, dict)
def iselement(obj) -> bool:
return isinstance(obj, Element)
def cast_to_html(_obj):
return _obj.html if isinstance(_obj, Element) else _obj
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class ElementNode(abc.ABC):
@abc.abstractmethod
def reload(self): ...
@property
@abc.abstractmethod
def html(self): ...
class State:
def __init__(self, value, fmt=str):
self.__value = value
self.__fmt = fmt
def __call__(self, _value=None, *args, **kwargs):
if _value:
self.__value = _value
return self.value
def change_fmt(self, fmt):
self.__fmt = fmt
@property
def value(self):
return self.__value
def __str__(self):
return self.__fmt(self.value)
class States:
def __init__(self):
self.__state = {}
def __call__(self, key, value, *args, **kwargs) -> State:
if key not in self.__state:
self.__state[key] = State(value, *args, **kwargs)
return self.__state[key]
class Component:
__all_components = {}
def __init__(self, root: object):
self.__root = root
Component.__all_components[root] = States()
def __del__(self):
raise "Invalid operation"
@property
def states(self):
return Component.__all_components[self.root]
@property
def root(self):
return self.__root
@staticmethod
def __getitem__(self, item):
return Component.__all_components[item]
@staticmethod
def __setitem__(self, key, value):
Component.__all_components[key] = value
class AttributeNode(abc.ABC):
def __init__(self, parent: ElementNode, _dict=None):
if _dict is None:
_dict = {}
self._elm = parent
self._dict = _dict
def __iter__(self):
return iter(self._dict.items())
def __getitem__(self, item):
return self._dict[item]
def __setitem__(self, key, value):
self._dict[key] = value
self._elm.reload()
@abc.abstractmethod
def update(self): ...
class Style(AttributeNode):
def update(self):
for key, v in self._dict.items():
self._elm.html.style[key] = v
class Attribute(AttributeNode):
def update(self):
for key, v in self._dict.items():
self._elm.html.attrs[key] = v
class Element(ElementNode):
def __init__(self, elm, *args, **kwargs):
self.__elm = create_html_element(elm, *args, **kwargs) if isinstance(elm, str) else elm
self.__attrs = Attribute(self)
self.__style = Style(self)
self.__childs = []
self.__parent = None
def __del__(self):
for _c in self.__childs:
del _c
def __matmul__(self, _obj: ElementNode | collections.abc.Iterable):
if isinstance(_obj, ElementNode):
if not self.parent:
raise ValueError("Invalid operation")
if not isiterable(_obj):
_obj = [_obj]
for o in _obj:
self.__childs.append(o)
self.__elm <= o.html
return self
def __xor__(self, _obj: ElementNode | object):
if isinstance(_obj, Element):
self.__childs.append(_obj)
_obj.__parent = self
self.__elm <= _obj.html
if isinstance(_obj, State):
self.__childs.append(_obj)
self.__elm <= str(_obj)
else:
self.__elm <= str(_obj)
return self
def __or__(self, _obj):
def _event_bind(ev):
_obj()
self.reload()
if callable(_obj):
self.html.bind(_obj.__name__, _event_bind)
elif isdict(_obj):
self.__style = Style(self, _obj)
self.reload()
return self
def __getitem__(self, item):
pass
def __setitem__(self, key, value):
pass
def reload(self):
self.__style.update()
self.__attrs.update()
for _obj in self.__childs:
if isinstance(_obj, Element):
_obj.reload()
elif isinstance(_obj, State):
self.__elm.innerText = str(_obj)
self.__style.update()
self.__attrs.update()
@property
def parent(self):
return self.__parent
@property
def html(self):
return self.__elm
@property
def style(self):
return self.__style
@property
def attribute(self):
return
def handler(name: str, _func):
_func.__name__ = name
return _func
def union(a, b):
return a <= b
def append(a, b):
return a + b
def div(*args, **kwargs):
return Element("div", *args, **kwargs)
def h(n: int, *args, **kwargs):
return Element(f"H{n}", *args, **kwargs)
def p(*args, **kwargs):
return Element("p", *args, **kwargs)
def button(*args, **kwargs):
return Element("button", *args, **kwargs)
def li(*args, **kwargs):
return Element("LI", *args, **kwargs)
def ul(*args, **kwargs):
return Element("ul", *args, **kwargs)
def mount(id: str):
def func_component():
pass
def inner(_func):
all_components = browser.document.select(id)
for com in all_components:
components = Component(com)
element = Element(components.root)
_obj = _func(components.states)
if isinstance(_obj, Element):
_obj = [_obj]
for o in _obj:
element.html <= o.html
return _func
return inner
"""
Operators NOP (Node Oriented Paradigm):
- @ "Group union"
- ^ "Inner"
- | "Attribute"
- & ""
- % ""
- ! ""
- ~ ""
- < ""
"""
@mount(".demo")
def my_component_demo(states):
import random
COLORS = ("pink", "red", "red", "blue", "green", "white", "brown", "yellow", "chocolate", "coral", "AliceBlue",
"AntiqueWhite", "Aqua", "Aquamarine", "Azure",
"Beige", "Bisque", "Black", "BlanchedAlmond", "Blue",
"BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse",
"Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson",
"Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray",
"DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen",
"DarkOrange", "DarkOrchid", "DarkRed", "DarkSlateBlue", "DarkSlateGray",
"DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue",
"DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite",
"ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold",
"GoldenRod", "Gray", "Grey", "Green", "GreenYellow",
"HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory",
"Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon",
"LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray",
"LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen")
btn_style = {
"background-color": ""
}
counter = states("counter", 0, lambda n: f"Counter {n}")
def click():
btn_style["background-color"] = random.choice(COLORS)
counter(counter() + 1)
return div(class_name="hello-demo") @ (
h(1, "Hello world"),
p() ^ "Element 1",
p() ^ "Element 2",
button() ^ counter | click | btn_style
)
if __name__ == '__main__':
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment