def __hrepr__(self, H, hrepr): params = sktk_hjson(self.parameters) self.active = True tmpid = f"$$tmp{next(_count)}" return H.div( H.div(id=tmpid), H.script(f""" (() => {{ let elem = document.getElementById('{tmpid}'); let existing = document.getElementById('{self.jsid}'); if (existing && existing.handler) {{ // Move the existing div elem.parentElement.replaceChild( existing, elem ); }} else {{ elem.id = '{self.jsid}'; requirejs.undef('{self.jsid}'); define( '{self.jsid}', ['{self.js_constructor}'], ctor => {{ let obj = new ctor(elem, {params}); elem.handler = obj; return new WeakRef(obj); }} ); require(['{self.jsid}'], _ => null); }} }})(); """), )
def test_bracketed(): brack = H.bracketed["kls"]( H.pair("a", "b", delimiter=" -> "), H.pair("c", "d", delimiter=" <- "), "e", start="START", end="END", stuff="xyz", ) assert sht(brack(vertical=True)) == H.div["kls", "hrepr-bracketed"]( H.div["hrepr-open"]("START"), H.table["hrepr-body"]( H.tr(H.td("a"), H.td["hrepr-delim"](" -> "), H.td("b"),), H.tr(H.td("c"), H.td["hrepr-delim"](" <- "), H.td("d"),), H.tr(H.td("e", colspan="3"),), ), H.div["hrepr-close"]("END"), stuff="xyz", ) assert sht(brack(horizontal=True)) == H.div["kls", "hrepr-bracketed"]( H.div["hrepr-open"]("START"), H.div["hreprl-h", "hrepr-body"]( H.div(H.div["hrepr-pair"]("a", " -> ", "b",)), H.div(H.div["hrepr-pair"]("c", " <- ", "d",)), H.div("e"), ), H.div["hrepr-close"]("END"), stuff="xyz", )
def test_nesting(): assert matches(H.div(H.div(H.b("inner"))), "<div><div><b>inner</b></div></div>") assert matches(H.div(H.b("hello"), H.i("there")), "<div><b>hello</b><i>there</i></div>") assert matches( H.div([[[H.b("hello"), [H.i("there")]]]]), "<div><b>hello</b><i>there</i></div>", )
def command_quit(self, expr, glb, lcl): self.session.queue_result(H.div("/quit"), type="echo") self.session.queue_result( H.div("Quitting interpreter in ", self.format_modname()), type="info", ) # Small delay so that the messages get flushed time.sleep(0.01) raise StopEvaluator()
def test_multiref(): li = [1, 2] lili = [li, li] assert hrepr(lili) == H.div["hreprt-list", "hrepr-bracketed"]( H.div["hrepr-open"]("["), H.div["hreprl-h", "hrepr-body"]( H.div( H.div["hrepr-refbox"]( H.span["hrepr-ref"]("#", 1, "="), H.div["hreprt-list", "hrepr-bracketed"]( H.div["hrepr-open"]("["), H.div["hreprl-h", "hrepr-body"]( H.div(H.span["hreprt-int"]("1")), H.div(H.span["hreprt-int"]("2")), ), H.div["hrepr-close"]("]"), ), ) ), H.div( H.div["hrepr-refbox"]( H.span["hrepr-ref"]("#", 1, "="), H.div["hreprt-list", "hrepr-bracketed"]( H.div["hrepr-open"]("["), H.div["hreprl-s", "hrepr-body"](H.div("..."),), H.div["hrepr-close"]("]"), ), ) ), ), H.div["hrepr-close"]("]"), ) assert hrepr(lili, shortrefs=True) == H.div[ "hreprt-list", "hrepr-bracketed" ]( H.div["hrepr-open"]("["), H.div["hreprl-h", "hrepr-body"]( H.div( H.div["hrepr-refbox"]( H.span["hrepr-ref"]("#", 1, "="), H.div["hreprt-list", "hrepr-bracketed"]( H.div["hrepr-open"]("["), H.div["hreprl-h", "hrepr-body"]( H.div(H.span["hreprt-int"]("1")), H.div(H.span["hreprt-int"]("2")), ), H.div["hrepr-close"]("]"), ), ) ), H.div(H.span["hrepr-ref"]("#", 1)), ), H.div["hrepr-close"]("]"), )
def test_dataclass(): pt = Point(1, 2) assert hrepr(pt) == H.div["hreprt-Point", "hrepr-instance", "hreprl-v"]( H.div["hrepr-title"]("Point"), H.table["hrepr-body"]( H.tr( H.td(H.span["hreprt-symbol"]("x")), H.td["hrepr-delim"]("="), H.td(H.span["hreprt-int"]("1")), ), H.tr( H.td(H.span["hreprt-symbol"]("y")), H.td["hrepr-delim"]("="), H.td(H.span["hreprt-int"]("2")), ), ), ) assert hrepr(pt, max_depth=0) == H.div[ "hreprt-Point", "hrepr-instance", "hreprl-s" ]( H.div["hrepr-title"]("Point"), H.div["hreprl-s", "hrepr-body"](H.div("...")), )
def loop(self): pyv = sys.version_info self.session.queue_result( H.div( "Starting interpreter in ", self.format_modname(), H.br(), f"Snektalk {version} using Python {pyv.major}.{pyv.minor}.{pyv.micro}", ), type="info", ) try: while True: try: prompt = H.span["snek-input-mode-python"](self.prompt) with self.session.prompt(prompt) as cmd: if cmd["command"] == "expr": expr = cmd["expr"] if expr.strip(): try: self.dispatch(expr) except SnektalkInterrupt as exc: print(exc) elif cmd["command"] == "noop": pass except SnektalkInterrupt: continue except StopEvaluator: return
def command_debug(self, expr, glb, lcl): from .debug import SnekTalkDb expr = expr.lstrip() glb = glb or self.glb lcl = lcl or self.lcl if expr: self.session.queue(command="echo", value=f"/debug {expr}", process=False) result = SnekTalkDb().runeval_step(expr, glb, lcl) typ = "statement" if result is None else "expression" self.session.queue_result(result, type=typ) else: exc = self.session.blt.get("$$exc_info", None) if exc: self.session.queue( command="echo", value=f"Debugging {exc[0].__qualname__}: {exc[1]}", language="text", process=False, ) tb = exc[2] SnekTalkDb().interaction(tb.tb_frame, tb) else: self.session.queue_result( H.div("Last expression was not an exception"), type="exception", )
def __hrepr__(self, H, hrepr): return H.div( constructor="make_plot", options=[{ "x": list(range(len(self.data))), "y": list(self.data) }], )
def test_structures(): for typ, o, c in ( (tuple, "(", ")"), (list, "[", "]"), (set, "{", "}"), (frozenset, "{", "}"), ): clsname = typ.__name__ assert hrepr(typ((1, 2))) == H.div[ f"hreprt-{clsname}", "hrepr-bracketed" ]( H.div["hrepr-open"](o), H.div["hreprl-h", "hrepr-body"]( H.div(H.span["hreprt-int"]("1")), H.div(H.span["hreprt-int"]("2")), ), H.div["hrepr-close"](c), )
def __hrepr__(self, H, hrepr): size = hrepr.config.swatch_size or 25 style = f""" background: rgb({self.r}, {self.g}, {self.b}); width: {size}px; height: {size}px; margin: 3px; """ return H.div(style=style)
def test_as_page(): tag = H.div("simplicity") utf8 = H.meta({"http-equiv": "Content-type"}, content="text/html", charset="UTF-8") page = H.inline( H.raw("<!DOCTYPE html>"), H.html(H.head(utf8), H.body(tag)), ) assert tag.as_page() == page
def test_div(): assert matches(H.div(), "<div></div>") assert matches(H.div("Some content"), "<div>Some content</div>") assert matches( H.div(" \n\n Some content \n "), "<div> \n\n Some content \n </div>", ) assert matches(H.div["classy"](), '<div class="classy"></div>') assert matches(H.div["classy"](), '<div class="classy"></div>') assert matches( H.div["classy"](id="eyedee", thing="thang"), '<div class="classy" id="eyedee" thing="thang"></div>', ) assert matches(H.div(dash_es=True), "<div dash-es></div>") assert matches( H.div.fill(attributes={"un_der_scores": True}), "<div un_der_scores></div>", ) assert matches( H.div['qu"ote'](id='qu"ite'), '<div class="qu"ote" id="qu"ite"></div>', )
def test_as_page_with_resources(): sty = H.style("b { color: red; }") scr = H.script("x = 1234;") resources = (sty, scr) inner = H.b("resources").fill(resources=scr) tag = H.div("with ", inner).fill(resources=sty) utf8 = H.meta({"http-equiv": "Content-type"}, content="text/html", charset="UTF-8") page = H.inline( H.raw("<!DOCTYPE html>"), H.html(H.head(utf8, *resources), H.body(tag)), ) assert tag.as_page() == page
def run(): reason = " finished" self.threads[word] = thread with session.set_context(): with new_evalid(): session.queue_result( H.div("Starting thread ", H.strong(word)), type="info", ) try: fn() except ThreadKilledException: reason = " killed" except Exception as e: session.queue_result(e, type="exception") finally: thread._dead = True session._clean_owners() del self.threads[word] self.words.append(word) session.queue_result( H.div("Thread ", H.strong(word), reason), type="info", )
def command_help(self, arg, gs, ls): """<b>h(elp)</b> Without argument, print the list of available commands. With a command name as argument, print help about that command. """ if arg: html = H.div(style="border:1px solid black; padding: 5px") self.session.queue( command="result", type="print", value=html(H.raw(self.__commands__[arg].__doc__)), ) else: commands = [x.__doc__ for x in set(self.__commands__.values())] commands.sort() html = H.div(style="border:1px solid black; padding: 5px") for cmd in commands: html = html(H.div(H.raw(cmd))) self.session.queue( command="result", type="print", value=html, )
def test_recursive(): li = [1] li.append(li) assert hrepr(li) == H.div["hrepr-refbox"]( H.span["hrepr-ref"]("#", 1, "="), H.div["hreprt-list", "hrepr-bracketed"]( H.div["hrepr-open"]("["), H.div["hreprl-h", "hrepr-body"]( H.div(H.span["hreprt-int"]("1")), H.div( H.div["hrepr-refbox"]( H.span["hrepr-ref"]("⟳", 1, "="), H.div["hreprt-list", "hrepr-bracketed"]( H.div["hrepr-open"]("["), H.div["hreprl-s", "hrepr-body"](H.div("..."),), H.div["hrepr-close"]("]"), ), ) ), ), H.div["hrepr-close"]("]"), ), ) assert hrepr(li, shortrefs=True) == H.div["hrepr-refbox"]( H.span["hrepr-ref"]("#", 1, "="), H.div["hreprt-list", "hrepr-bracketed"]( H.div["hrepr-open"]("["), H.div["hreprl-h", "hrepr-body"]( H.div(H.span["hreprt-int"]("1")), H.div(H.span["hrepr-ref"]("⟳", 1)), ), H.div["hrepr-close"]("]"), ), )
def test_short_structures(): for val, o, c in ( ((1, 2), "(", ")"), ([1, 2], "[", "]"), ({1, 2}, "{", "}"), (frozenset({1, 2}), "{", "}"), ({"x": 1, "y": 2}, "{", "}"), ): clsname = type(val).__name__ assert hrepr(val, max_depth=0) == H.div[ f"hreprt-{clsname}", "hrepr-bracketed" ]( H.div["hrepr-open"](o), H.div["hreprl-s", "hrepr-body"](H.div("...")), H.div["hrepr-close"](c), )
def __hrepr__(self, H, hrepr): width = hrepr.config.graph_width or 500 height = hrepr.config.graph_height or 500 style = hrepr.config.graph_style or cystyle data = [{"data": {"id": node}} for node in self.nodes] data += [{ "data": { "source": src, "target": tgt } } for src, tgt in self.edges] return H.div( style=f"width:{width}px;height:{height}px;", constructor="make_graph", options={ "data": data, "style": style, "layout": "cose" }, )
def test_incremental(): d0 = H.div() assert matches(d0, "<div></div>") d = d0("crumpet") assert matches(d0, "<div></div>") assert matches(d, "<div>crumpet</div>") d = d(H.b("tea")) assert matches(d, "<div>crumpet<b>tea</b></div>") d = d(id="paramount") assert matches(d, '<div id="paramount">crumpet<b>tea</b></div>') d = d({"sheep": "bah"}, quack=True) assert matches( d, '<div id="paramount" sheep="bah" quack>crumpet<b>tea</b></div>') d = d(quack=False) assert matches(d, '<div id="paramount" sheep="bah" >crumpet<b>tea</b></div>')
def image(probe, key_name=None): if key_name: probe = probe.pipe(op.getitem(key_name)) divid = f"$analyze__{next(monitor_count)}" def redraw(arr): while len(arr.shape) > 2: arr = arr[0] arr = arr.detach().numpy() arr = (arr - arr.min()) / (arr.max() - arr.min()) * 255 arr = arr.astype(numpy.uint8) img = Image.fromarray(arr, "L") buffered = BytesIO() img.save(buffered, format="PNG") b = base64.b64encode(buffered.getvalue()) s = b.decode("utf8") fill_at(divid, H.img(src=f"data:image/png;base64,{s}")) probe.subscribe(redraw) print(H.div(id=divid))
def __hrepr__(self, H, hrepr): return H.div["snek-print-sequence"](*[H.div(hrepr(x)) for x in self], onclick=False)
def _safe_set(elem, **props): if elem.is_virtual(): return H.div(elem, **props) else: return elem(**props)
def test_misc(): assert matches(H.whimsy("cal"), "<whimsy>cal</whimsy>") assert H.div(H.b("hello")) == H.div(H.b("hello")) assert H.div(H.b("hello")) != H.div(H.i("hello")) assert isinstance(hash(H.div(H.div("yay!"))), int) assert repr(H.div("soupe")) == str(H.div("soupe"))
def test_quote(): assert matches(H.div("<quoted>"), "<div><quoted></div>")
def missing(self, expr, cmd, arg, glb, lcl): self.session.queue(command="echo", value=expr, process=False) self.session.queue_result(H.div(f"Command '{cmd}' does not exist"), type="exception")