Skip to content

Commit

Permalink
Simplify imports
Browse files Browse the repository at this point in the history
  • Loading branch information
laffra committed Nov 23, 2023
1 parent 285bbdc commit 7976b4e
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 65 deletions.
6 changes: 3 additions & 3 deletions examples/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import logging
import ltk
from pyscript import window as js # type: ignore
from pyscript import window # type: ignore

search = js.URLSearchParams.new(js.location.search)
search = window.URLSearchParams.new(window.location.search)
runtime = search.get("runtime") or "mpy"

logger = logging.getLogger()
Expand Down Expand Up @@ -42,7 +42,7 @@ def change(event):
def set_runtime(event):
chosen = ltk.jQuery(event.target).attr("value")
if chosen != runtime:
js.setSearchParameter("runtime", chosen)
window.setSearchParameter("runtime", chosen)

widgets = [
ltk.VBox(
Expand Down
6 changes: 3 additions & 3 deletions kitchensink.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ltk # Load early on MicroPython, before logging

import examples
from pyscript import window as js # type: ignore
from pyscript import window # type: ignore
import logging

logger = logging.getLogger("kitchensink")
Expand All @@ -25,7 +25,7 @@ def setsource(src):


ltk.find("#progress").remove()
ltk.find("#title").append(f" took {js.startTime() / 1000}s to load")
ltk.find("#title").append(f" took {window.startTime() / 1000}s to load")


tabs = ltk.Tabs(
Expand Down Expand Up @@ -62,7 +62,7 @@ def activate_tab(event, ui=None):

tabs.activate(ltk.get_url_parameter("tab") or 0)

ltk.body.append(
ltk.find(window.document.body).append(
ltk.Logger().element,
ltk.Div(
tabs.css("margin-bottom", 24)
Expand Down
12 changes: 4 additions & 8 deletions ltk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
inject_script("ltk/ltk.js")
inject_css("ltk/ltk.css")

from pyscript import window as js # type: ignore
from pyscript import window # type: ignore

def fix_time():
import time
Expand All @@ -15,16 +15,12 @@ class MonkeyPatchedTimeModuleForMicroPython: pass
clone = MonkeyPatchedTimeModuleForMicroPython()
for key in dir(time):
setattr(clone, key, getattr(time, key))
setattr(clone, "time", lambda: js.Date.new().getTime() / 1000)
setattr(clone, "time", lambda: window.Date.new().getTime() / 1000)
sys.modules["time"] = clone

fix_time()

from ltk.widgets import *
from ltk.logger import Logger

from ltk.pubsub import publish
from ltk.pubsub import subscribe


from ltk.pubsub import *
from ltk.logger import *
from ltk.jquery import time
67 changes: 39 additions & 28 deletions ltk/jquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,102 +2,113 @@

import json
import pyodide # type: ignore
import pyscript # type: ignore
from pyscript import window


timers = {}

js = pyscript.window

jQuery = js.jQuery
console = js.console
window = jQuery(js.window)
document = jQuery(js.document)
head = jQuery("head")
body = jQuery("body")
parse_int = js.parseInt
parse_float = js.parseFloat
local_storage = js.localStorage
jQuery = window.jQuery
parse_int = window.parseInt
parse_float = window.parseFloat
local_storage = window.localStorage


def find(selector):
return jQuery(selector)


def create(selector):
return jQuery(selector)


def find_list(selector):
elements = jQuery(selector)
return [ elements.eq(n) for n in range(elements.length) ]


def to_js(dict):
return js.to_js(json.dumps(dict))
return window.to_js(json.dumps(dict))


def to_py(jsobj):
try:
return jsobj.to_py()
except:
try:
return json.loads(js.to_py(jsobj)) # Micropython has no built-in to_py
return json.loads(window.to_py(jsobj)) # Micropython has no built-in to_py
except:
return str(jsobj)


def number(s):
return js.parseFloat(s)
return parse_float(s)


def schedule(python_function, timeout_seconds=0.1):
if not python_function:
raise ValueError(f"schedule: Expecting a function, not {python_function}")
if python_function in timers:
js.clearTimeout(timers[python_function])
timers[python_function] = js.setTimeout(proxy(python_function), int(timeout_seconds * 1000))
window.clearTimeout(timers[python_function])
timers[python_function] = window.setTimeout(proxy(python_function), int(timeout_seconds * 1000))


def repeat(python_function, timeout_seconds=1):
js.setInterval(proxy(python_function), int(timeout_seconds * 1000))
window.setInterval(proxy(python_function), int(timeout_seconds * 1000))


def get(route, handler, kind="json"):
def wrapper(data, *rest):
handler(data if isinstance(data, str) else to_py(data))
return jQuery.get(route, proxy(wrapper), kind)


def delete(route, handler):
wrapper = proxy(lambda data, *rest: handler(to_py(data)))
return js.ajax(route, "DELETE", wrapper)
return window.ajax(route, "DELETE", wrapper)


def time():
return js.time() / 1000
return window.time() / 1000


def post(route, data, handler):
payload = js.encodeURIComponent(json.dumps(data))
wrapper = proxy(lambda data, *rest: handler(js.JSON.stringify(data)))
payload = window.encodeURIComponent(json.dumps(data))
wrapper = proxy(lambda data, *rest: handler(window.JSON.stringify(data)))
return jQuery.post(route, payload, wrapper, "json")


def async_proxy(function):
async def call_function(*args):
return await function(*args)
return pyodide.ffi.create_proxy(call_function)


def proxy(function):
return pyodide.ffi.create_proxy(function)


def get_url_parameter(key):
return js.URLSearchParams.new(js.document.location.search).get(key)
return window.URLSearchParams.new(window.document.location.search).get(key)


def set_url_parameter(key, value, reload=True):
search = js.URLSearchParams.new(js.window.location.search)
search = window.URLSearchParams.new(window.location.search)
search.set(key, value)
url = f"{js.window.location.href.split('?')[0]}?{search.toString()}"
url = f"{window.location.href.split('?')[0]}?{search.toString()}"
if reload:
js.document.location = url
window.document.location = url
else:
push_state(url)


def push_state(url):
js.history.pushState(None, "", url)
window.history.pushState(None, "", url)


def inject_script(url):
create("<script>").attr("src", url).appendTo(head)
create("<script>").attr("src", url).appendTo(window.document.head)


def inject_css(url):
create("<link>").attr("rel", "stylesheet").attr("href", url).appendTo(head)
create("<link>").attr("rel", "stylesheet").attr("href", url).appendTo(window.document.head)
19 changes: 9 additions & 10 deletions ltk/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import json
import logging
from ltk.widgets import *
from ltk.pubsub import PubSubUI
from ltk import *

logger = logging.getLogger('root')
logger.setLevel(logging.DEBUG)
Expand Down Expand Up @@ -112,21 +111,21 @@ def add(self, level, *args, **argv):
.animate(to_js({ "height": 24 }), 700)
)
if level == logging.ERROR:
console.orig_error(*args)
window.console.orig_error(*args)
else:
console.orig_log(*args)
window.console.orig_log(*args)
self.filter_rows()
self.element.animate(to_js({"opacity": 1}), 1300)
except Exception as e:
print("Log error:", e)

def setup_console(self):
console.orig_log = console.log
console.orig_warn = console.warn
console.orig_error = console.error
console.log = self.console_log
console.warn = self.console_log
console.error = self.console_log
window.console.orig_log = window.console.log
window.console.orig_warn = window.console.warn
window.console.orig_error = window.console.error
window.console.log = self.console_log
window.console.warn = self.console_log
window.console.error = self.console_log
try:
import warnings
warnings.warn = self.console_log
Expand Down
26 changes: 13 additions & 13 deletions ltk/widgets.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# LTK - Copyrights Reserved 2023 - chrislaffra.com - See LICENSE

from pyscript import window as js # type: ignore
from pyscript import window # type: ignore
from ltk.jquery import *

timers = {}
Expand Down Expand Up @@ -342,7 +342,7 @@ class RadioGroup(VBox):
classes = [ "ltk-vbox ltk-radiogroup" ]

def __init__(self, *buttons, style=DEFAULT_CSS):
name = f"ltk-radiogroup-{js.time()}"
name = f"ltk-radiogroup-{window.time()}"
for button in buttons:
button.find("input").attr("name", name)
VBox.__init__(self, *buttons, style)
Expand All @@ -366,19 +366,19 @@ class Table(Widget):

def __init__(self, *rows):
self.element = (
js.table()
window.table()
.addClass(" ".join(self.classes))
.append(*self._flatten(rows))
)

def title(self, column, title):
js.tableTitle(self.element, column, title)
window.tableTitle(self.element, column, title)

def get(self, column, row):
return js.tableGet(self.element, column, row)
return window.tableGet(self.element, column, row)

def set(self, column, row, value):
js.tableSet(self.element, column, row, value)
window.tableSet(self.element, column, row, value)


class TableRow(Widget):
Expand Down Expand Up @@ -418,7 +418,7 @@ class Code(Widget):

def __init__(self, language, code, style=DEFAULT_CSS):
Widget.__init__(self, style)
if not hasattr(js, "hljs"):
if not hasattr(window, "hljs"):
inject_css("https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css")
inject_script("https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js")
inject_script(f"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/{language}.min.js")
Expand All @@ -428,8 +428,8 @@ def __init__(self, language, code, style=DEFAULT_CSS):
def highlight(self):
if self.highlighted:
return
if hasattr(js, "hljs"):
js.hljs.highlightElement(self.element[0])
if hasattr(window, "hljs"):
window.hljs.highlightElement(self.element[0])
self.element.animate(to_js({ "opacity": 1}))
self.highlighted = True
else:
Expand Down Expand Up @@ -499,9 +499,9 @@ def show(self, element):
close_all_menus()
find("#main").css("opacity", 0.3)
(self
.appendTo(body)
.appendTo(jQuery(window.document.body))
.css("top", element.offset().top + 28)
.css("left", min(element.offset().left + 2, body.width() - self.width() - 12))
.css("left", min(element.offset().left + 2, jQuery(window.document.body).width() - self.width() - 12))
.addClass("ltk-menupopup-open")
)

Expand Down Expand Up @@ -568,15 +568,15 @@ def close_all_menus(event=None):
return
find(".ltk-menupopup-open").removeClass("ltk-menupopup-open")

body.on("click", proxy(close_all_menus))
jQuery(window.document.body).on("click", proxy(close_all_menus))

def _handle_shortcuts():
def handle_keydown(event):
shortcut = f"{'Cmd+' if event.metaKey else ''}{event.key.upper() if event.key else ''}"
if shortcut in shortcuts:
event.preventDefault()
shortcuts[shortcut].select(event)
document.on("keydown", proxy(handle_keydown))
jQuery(window.document).on("keydown", proxy(handle_keydown))


_handle_shortcuts()

0 comments on commit 7976b4e

Please sign in to comment.